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, making it lowercase and checking some synonyms,
217 * and ensure it's clean. Extensions with non-alphanumeric characters will be discarded.
218 * Keep in sync with mw.Title.normalizeExtension() in JS.
220 * @param string $extension File extension (without the leading dot)
221 * @return string File extension in canonical form
223 static function normalizeExtension( $extension ) {
224 $lower = strtolower( $extension );
231 if ( isset( $squish[$lower] ) ) {
232 return $squish[$lower];
233 } elseif ( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
241 * Checks if file extensions are compatible
243 * @param File $old Old file
244 * @param string $new New name
248 static function checkExtensionCompatibility( File
$old, $new ) {
249 $oldMime = $old->getMimeType();
250 $n = strrpos( $new, '.' );
251 $newExt = self
::normalizeExtension( $n ?
substr( $new, $n +
1 ) : '' );
252 $mimeMagic = MimeMagic
::singleton();
254 return $mimeMagic->isMatchingExtension( $newExt, $oldMime );
258 * Upgrade the database row if there is one
259 * Called by ImagePage
262 function upgradeRow() {
266 * Split an internet media type into its two components; if not
267 * a two-part name, set the minor type to 'unknown'.
269 * @param string $mime "text/html" etc
270 * @return array ("text", "html") etc
272 public static function splitMime( $mime ) {
273 if ( strpos( $mime, '/' ) !== false ) {
274 return explode( '/', $mime, 2 );
276 return array( $mime, 'unknown' );
281 * Callback for usort() to do file sorts by name
285 * @return int Result of name comparison
287 public static function compare( File
$a, File
$b ) {
288 return strcmp( $a->getName(), $b->getName() );
292 * Return the name of this file
296 public function getName() {
297 if ( !isset( $this->name
) ) {
298 $this->assertRepoDefined();
299 $this->name
= $this->repo
->getNameFromTitle( $this->title
);
306 * Get the file extension, e.g. "svg"
310 function getExtension() {
311 if ( !isset( $this->extension
) ) {
312 $n = strrpos( $this->getName(), '.' );
313 $this->extension
= self
::normalizeExtension(
314 $n ?
substr( $this->getName(), $n +
1 ) : '' );
317 return $this->extension
;
321 * Return the associated title object
325 public function getTitle() {
330 * Return the title used to find this file
334 public function getOriginalTitle() {
335 if ( $this->redirected
) {
336 return $this->getRedirectedTitle();
343 * Return the URL of the file
347 public function getUrl() {
348 if ( !isset( $this->url
) ) {
349 $this->assertRepoDefined();
350 $ext = $this->getExtension();
351 $this->url
= $this->repo
->getZoneUrl( 'public', $ext ) . '/' . $this->getUrlRel();
358 * Return a fully-qualified URL to the file.
359 * Upload URL paths _may or may not_ be fully qualified, so
360 * we check. Local paths are assumed to belong on $wgServer.
364 public function getFullUrl() {
365 return wfExpandUrl( $this->getUrl(), PROTO_RELATIVE
);
371 public function getCanonicalUrl() {
372 return wfExpandUrl( $this->getUrl(), PROTO_CANONICAL
);
378 function getViewURL() {
379 if ( $this->mustRender() ) {
380 if ( $this->canRender() ) {
381 return $this->createThumb( $this->getWidth() );
383 wfDebug( __METHOD__
. ': supposed to render ' . $this->getName() .
384 ' (' . $this->getMimeType() . "), but can't!\n" );
386 return $this->getURL(); # hm... return NULL?
389 return $this->getURL();
394 * Return the storage path to the file. Note that this does
395 * not mean that a file actually exists under that location.
397 * This path depends on whether directory hashing is active or not,
398 * i.e. whether the files are all found in the same directory,
399 * or in hashed paths like /images/3/3c.
401 * Most callers don't check the return value, but ForeignAPIFile::getPath
404 * @return string|bool ForeignAPIFile::getPath can return false
406 public function getPath() {
407 if ( !isset( $this->path
) ) {
408 $this->assertRepoDefined();
409 $this->path
= $this->repo
->getZonePath( 'public' ) . '/' . $this->getRel();
416 * Get an FS copy or original of this file and return the path.
417 * Returns false on failure. Callers must not alter the file.
418 * Temporary files are cleared automatically.
420 * @return string|bool False on failure
422 public function getLocalRefPath() {
423 $this->assertRepoDefined();
424 if ( !isset( $this->fsFile
) ) {
425 $starttime = microtime( true );
426 $this->fsFile
= $this->repo
->getLocalReference( $this->getPath() );
428 $statTiming = microtime( true ) - $starttime;
429 RequestContext
::getMain()->getStats()->timing(
430 'media.thumbnail.generate.fetchoriginal', 1000 * $statTiming );
432 if ( !$this->fsFile
) {
433 $this->fsFile
= false; // null => false; cache negative hits
437 return ( $this->fsFile
)
438 ?
$this->fsFile
->getPath()
443 * Return the width of the image. Returns false if the width is unknown
447 * Overridden by LocalFile, UnregisteredLocalFile
452 public function getWidth( $page = 1 ) {
457 * Return the height of the image. Returns false if the height is unknown
461 * Overridden by LocalFile, UnregisteredLocalFile
464 * @return bool|int False on failure
466 public function getHeight( $page = 1 ) {
471 * Return the smallest bucket from $wgThumbnailBuckets which is at least
472 * $wgThumbnailMinimumBucketDistance larger than $desiredWidth. The returned bucket, if any,
473 * will always be bigger than $desiredWidth.
475 * @param int $desiredWidth
479 public function getThumbnailBucket( $desiredWidth, $page = 1 ) {
480 global $wgThumbnailBuckets, $wgThumbnailMinimumBucketDistance;
482 $imageWidth = $this->getWidth( $page );
484 if ( $imageWidth === false ) {
488 if ( $desiredWidth > $imageWidth ) {
492 if ( !$wgThumbnailBuckets ) {
496 $sortedBuckets = $wgThumbnailBuckets;
498 sort( $sortedBuckets );
500 foreach ( $sortedBuckets as $bucket ) {
501 if ( $bucket >= $imageWidth ) {
505 if ( $bucket - $wgThumbnailMinimumBucketDistance > $desiredWidth ) {
510 // Image is bigger than any available bucket
515 * Returns ID or name of user who uploaded the file
518 * @param string $type 'text' or 'id'
521 public function getUser( $type = 'text' ) {
526 * Get the duration of a media file in seconds
530 public function getLength() {
531 $handler = $this->getHandler();
533 return $handler->getLength( $this );
540 * Return true if the file is vectorized
544 public function isVectorized() {
545 $handler = $this->getHandler();
547 return $handler->isVectorized( $this );
554 * Gives a (possibly empty) list of languages to render
557 * If the file doesn't have translations, or if the file
558 * format does not support that sort of thing, returns
564 public function getAvailableLanguages() {
565 $handler = $this->getHandler();
567 return $handler->getAvailableLanguages( $this );
574 * In files that support multiple language, what is the default language
575 * to use if none specified.
577 * @return string|null Lang code, or null if filetype doesn't support multiple languages.
580 public function getDefaultRenderLanguage() {
581 $handler = $this->getHandler();
583 return $handler->getDefaultRenderLanguage( $this );
590 * Will the thumbnail be animated if one would expect it to be.
592 * Currently used to add a warning to the image description page
594 * @return bool False if the main image is both animated
595 * and the thumbnail is not. In all other cases must return
596 * true. If image is not renderable whatsoever, should
599 public function canAnimateThumbIfAppropriate() {
600 $handler = $this->getHandler();
602 // We cannot handle image whatsoever, thus
603 // one would not expect it to be animated
607 if ( $this->allowInlineDisplay()
608 && $handler->isAnimatedImage( $this )
609 && !$handler->canAnimateThumbnail( $this )
611 // Image is animated, but thumbnail isn't.
612 // This is unexpected to the user.
615 // Image is not animated, so one would
616 // not expect thumb to be
623 * Get handler-specific metadata
624 * Overridden by LocalFile, UnregisteredLocalFile
628 public function getMetadata() {
633 * Like getMetadata but returns a handler independent array of common values.
634 * @see MediaHandler::getCommonMetaArray()
635 * @return array|bool Array or false if not supported
638 public function getCommonMetaArray() {
639 $handler = $this->getHandler();
645 return $handler->getCommonMetaArray( $this );
649 * get versioned metadata
651 * @param array|string $metadata Array or string of (serialized) metadata
652 * @param int $version Version number.
653 * @return array Array containing metadata, or what was passed to it on fail
654 * (unserializing if not array)
656 public function convertMetadataVersion( $metadata, $version ) {
657 $handler = $this->getHandler();
658 if ( !is_array( $metadata ) ) {
659 // Just to make the return type consistent
660 $metadata = unserialize( $metadata );
663 return $handler->convertMetadataVersion( $metadata, $version );
670 * Return the bit depth of the file
671 * Overridden by LocalFile
675 public function getBitDepth() {
680 * Return the size of the image file, in bytes
681 * Overridden by LocalFile, UnregisteredLocalFile
685 public function getSize() {
690 * Returns the MIME type of the file.
691 * Overridden by LocalFile, UnregisteredLocalFile
696 function getMimeType() {
697 return 'unknown/unknown';
701 * Return the type of the media in the file.
702 * Use the value returned by this function with the MEDIATYPE_xxx constants.
703 * Overridden by LocalFile,
707 function getMediaType() {
708 return MEDIATYPE_UNKNOWN
;
712 * Checks if the output of transform() for this file is likely
713 * to be valid. If this is false, various user elements will
714 * display a placeholder instead.
716 * Currently, this checks if the file is an image format
717 * that can be converted to a format
718 * supported by all browsers (namely GIF, PNG and JPEG),
719 * or if it is an SVG image and SVG conversion is enabled.
723 function canRender() {
724 if ( !isset( $this->canRender
) ) {
725 $this->canRender
= $this->getHandler() && $this->handler
->canRender( $this ) && $this->exists();
728 return $this->canRender
;
732 * Accessor for __get()
735 protected function getCanRender() {
736 return $this->canRender();
740 * Return true if the file is of a type that can't be directly
741 * rendered by typical browsers and needs to be re-rasterized.
743 * This returns true for everything but the bitmap types
744 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
745 * also return true for any non-image formats.
749 function mustRender() {
750 return $this->getHandler() && $this->handler
->mustRender( $this );
754 * Alias for canRender()
758 function allowInlineDisplay() {
759 return $this->canRender();
763 * Determines if this media file is in a format that is unlikely to
764 * contain viruses or malicious content. It uses the global
765 * $wgTrustedMediaFormats list to determine if the file is safe.
767 * This is used to show a warning on the description page of non-safe files.
768 * It may also be used to disallow direct [[media:...]] links to such files.
770 * Note that this function will always return true if allowInlineDisplay()
771 * or isTrustedFile() is true for this file.
775 function isSafeFile() {
776 if ( !isset( $this->isSafeFile
) ) {
777 $this->isSafeFile
= $this->getIsSafeFileUncached();
780 return $this->isSafeFile
;
784 * Accessor for __get()
788 protected function getIsSafeFile() {
789 return $this->isSafeFile();
797 protected function getIsSafeFileUncached() {
798 global $wgTrustedMediaFormats;
800 if ( $this->allowInlineDisplay() ) {
803 if ( $this->isTrustedFile() ) {
807 $type = $this->getMediaType();
808 $mime = $this->getMimeType();
809 # wfDebug( "LocalFile::isSafeFile: type= $type, mime= $mime\n" );
811 if ( !$type ||
$type === MEDIATYPE_UNKNOWN
) {
812 return false; # unknown type, not trusted
814 if ( in_array( $type, $wgTrustedMediaFormats ) ) {
818 if ( $mime === "unknown/unknown" ) {
819 return false; # unknown type, not trusted
821 if ( in_array( $mime, $wgTrustedMediaFormats ) ) {
829 * Returns true if the file is flagged as trusted. Files flagged that way
830 * can be linked to directly, even if that is not allowed for this type of
833 * This is a dummy function right now and always returns false. It could be
834 * implemented to extract a flag from the database. The trusted flag could be
835 * set on upload, if the user has sufficient privileges, to bypass script-
836 * and html-filters. It may even be coupled with cryptographics signatures
841 function isTrustedFile() {
842 # this could be implemented to check a flag in the database,
843 # look for signatures, etc
848 * Load any lazy-loaded file object fields from source
850 * This is only useful when setting $flags
852 * Overridden by LocalFile to actually query the DB
854 * @param integer $flags Bitfield of File::READ_* constants
856 public function load( $flags = 0 ) {
860 * Returns true if file exists in the repository.
862 * Overridden by LocalFile to avoid unnecessary stat calls.
864 * @return bool Whether file exists in the repository.
866 public function exists() {
867 return $this->getPath() && $this->repo
->fileExists( $this->path
);
871 * Returns true if file exists in the repository and can be included in a page.
872 * It would be unsafe to include private images, making public thumbnails inadvertently
874 * @return bool Whether file exists in the repository and is includable.
876 public function isVisible() {
877 return $this->exists();
883 function getTransformScript() {
884 if ( !isset( $this->transformScript
) ) {
885 $this->transformScript
= false;
887 $script = $this->repo
->getThumbScriptUrl();
889 $this->transformScript
= wfAppendQuery( $script, array( 'f' => $this->getName() ) );
894 return $this->transformScript
;
898 * Get a ThumbnailImage which is the same size as the source
900 * @param array $handlerParams
904 function getUnscaledThumb( $handlerParams = array() ) {
905 $hp =& $handlerParams;
906 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
907 $width = $this->getWidth( $page );
909 return $this->iconThumb();
911 $hp['width'] = $width;
912 // be sure to ignore any height specification as well (bug 62258)
913 unset( $hp['height'] );
915 return $this->transform( $hp );
919 * Return the file name of a thumbnail with the specified parameters.
920 * Use File::THUMB_FULL_NAME to always get a name like "<params>-<source>".
921 * Otherwise, the format may be "<params>-<source>" or "<params>-thumbnail.<ext>".
923 * @param array $params Handler-specific parameters
924 * @param int $flags Bitfield that supports THUMB_* constants
925 * @return string|null
927 public function thumbName( $params, $flags = 0 ) {
928 $name = ( $this->repo
&& !( $flags & self
::THUMB_FULL_NAME
) )
929 ?
$this->repo
->nameForThumb( $this->getName() )
932 return $this->generateThumbName( $name, $params );
936 * Generate a thumbnail file name from a name and specified parameters
938 * @param string $name
939 * @param array $params Parameters which will be passed to MediaHandler::makeParamString
940 * @return string|null
942 public function generateThumbName( $name, $params ) {
943 if ( !$this->getHandler() ) {
946 $extension = $this->getExtension();
947 list( $thumbExt, ) = $this->getHandler()->getThumbType(
948 $extension, $this->getMimeType(), $params );
949 $thumbName = $this->getHandler()->makeParamString( $params );
951 if ( $this->repo
->supportsSha1URLs() ) {
952 $thumbName .= '-' . $this->getSha1() . '.' . $thumbExt;
954 $thumbName .= '-' . $name;
956 if ( $thumbExt != $extension ) {
957 $thumbName .= ".$thumbExt";
965 * Create a thumbnail of the image having the specified width/height.
966 * The thumbnail will not be created if the width is larger than the
967 * image's width. Let the browser do the scaling in this case.
968 * The thumbnail is stored on disk and is only computed if the thumbnail
969 * file does not exist OR if it is older than the image.
972 * Keeps aspect ratio of original image. If both width and height are
973 * specified, the generated image will be no bigger than width x height,
974 * and will also have correct aspect ratio.
976 * @param int $width Maximum width of the generated thumbnail
977 * @param int $height Maximum height of the image (optional)
981 public function createThumb( $width, $height = -1 ) {
982 $params = array( 'width' => $width );
983 if ( $height != -1 ) {
984 $params['height'] = $height;
986 $thumb = $this->transform( $params );
987 if ( !$thumb ||
$thumb->isError() ) {
991 return $thumb->getUrl();
995 * Return either a MediaTransformError or placeholder thumbnail (if $wgIgnoreImageErrors)
997 * @param string $thumbPath Thumbnail storage path
998 * @param string $thumbUrl Thumbnail URL
999 * @param array $params
1001 * @return MediaTransformOutput
1003 protected function transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags ) {
1004 global $wgIgnoreImageErrors;
1006 $handler = $this->getHandler();
1007 if ( $handler && $wgIgnoreImageErrors && !( $flags & self
::RENDER_NOW
) ) {
1008 return $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
1010 return new MediaTransformError( 'thumbnail_error',
1011 $params['width'], 0, wfMessage( 'thumbnail-dest-create' )->text() );
1016 * Transform a media file
1018 * @param array $params An associative array of handler-specific parameters.
1019 * Typical keys are width, height and page.
1020 * @param int $flags A bitfield, may contain self::RENDER_NOW to force rendering
1021 * @return MediaTransformOutput|bool False on failure
1023 function transform( $params, $flags = 0 ) {
1024 global $wgThumbnailEpoch;
1027 if ( !$this->canRender() ) {
1028 $thumb = $this->iconThumb();
1029 break; // not a bitmap or renderable image, don't try
1032 // Get the descriptionUrl to embed it as comment into the thumbnail. Bug 19791.
1033 $descriptionUrl = $this->getDescriptionUrl();
1034 if ( $descriptionUrl ) {
1035 $params['descriptionUrl'] = wfExpandUrl( $descriptionUrl, PROTO_CANONICAL
);
1038 $handler = $this->getHandler();
1039 $script = $this->getTransformScript();
1040 if ( $script && !( $flags & self
::RENDER_NOW
) ) {
1041 // Use a script to transform on client request, if possible
1042 $thumb = $handler->getScriptedTransform( $this, $script, $params );
1048 $normalisedParams = $params;
1049 $handler->normaliseParams( $this, $normalisedParams );
1051 $thumbName = $this->thumbName( $normalisedParams );
1052 $thumbUrl = $this->getThumbUrl( $thumbName );
1053 $thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
1055 if ( $this->repo
) {
1056 // Defer rendering if a 404 handler is set up...
1057 if ( $this->repo
->canTransformVia404() && !( $flags & self
::RENDER_NOW
) ) {
1058 wfDebug( __METHOD__
. " transformation deferred.\n" );
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 );
1065 // Check if an up-to-date thumbnail already exists...
1066 wfDebug( __METHOD__
. ": Doing stat for $thumbPath\n" );
1067 if ( !( $flags & self
::RENDER_FORCE
) && $this->repo
->fileExists( $thumbPath ) ) {
1068 $timestamp = $this->repo
->getFileTimestamp( $thumbPath );
1069 if ( $timestamp !== false && $timestamp >= $wgThumbnailEpoch ) {
1070 // XXX: Pass in the storage path even though we are not rendering anything
1071 // and the path is supposed to be an FS path. This is due to getScalerType()
1072 // getting called on the path and clobbering $thumb->getUrl() if it's false.
1073 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
1074 $thumb->setStoragePath( $thumbPath );
1077 } elseif ( $flags & self
::RENDER_FORCE
) {
1078 wfDebug( __METHOD__
. " forcing rendering per flag File::RENDER_FORCE\n" );
1081 // If the backend is ready-only, don't keep generating thumbnails
1082 // only to return transformation errors, just return the error now.
1083 if ( $this->repo
->getReadOnlyReason() !== false ) {
1084 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
1089 $tmpFile = $this->makeTransformTmpFile( $thumbPath );
1092 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
1094 $thumb = $this->generateAndSaveThumb( $tmpFile, $params, $flags );
1098 return is_object( $thumb ) ?
$thumb : false;
1102 * Generates a thumbnail according to the given parameters and saves it to storage
1103 * @param TempFSFile $tmpFile Temporary file where the rendered thumbnail will be saved
1104 * @param array $transformParams
1106 * @return bool|MediaTransformOutput
1108 public function generateAndSaveThumb( $tmpFile, $transformParams, $flags ) {
1109 global $wgIgnoreImageErrors;
1111 $stats = RequestContext
::getMain()->getStats();
1113 $handler = $this->getHandler();
1115 $normalisedParams = $transformParams;
1116 $handler->normaliseParams( $this, $normalisedParams );
1118 $thumbName = $this->thumbName( $normalisedParams );
1119 $thumbUrl = $this->getThumbUrl( $thumbName );
1120 $thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
1122 $tmpThumbPath = $tmpFile->getPath();
1124 if ( $handler->supportsBucketing() ) {
1125 $this->generateBucketsIfNeeded( $normalisedParams, $flags );
1128 $starttime = microtime( true );
1130 // Actually render the thumbnail...
1131 $thumb = $handler->doTransform( $this, $tmpThumbPath, $thumbUrl, $transformParams );
1132 $tmpFile->bind( $thumb ); // keep alive with $thumb
1134 $statTiming = microtime( true ) - $starttime;
1135 $stats->timing( 'media.thumbnail.generate.transform', 1000 * $statTiming );
1137 if ( !$thumb ) { // bad params?
1139 } elseif ( $thumb->isError() ) { // transform error
1140 /** @var $thumb MediaTransformError */
1141 $this->lastError
= $thumb->toText();
1142 // Ignore errors if requested
1143 if ( $wgIgnoreImageErrors && !( $flags & self
::RENDER_NOW
) ) {
1144 $thumb = $handler->getTransform( $this, $tmpThumbPath, $thumbUrl, $transformParams );
1146 } elseif ( $this->repo
&& $thumb->hasFile() && !$thumb->fileIsSource() ) {
1147 // Copy the thumbnail from the file system into storage...
1149 $starttime = microtime( true );
1151 $disposition = $this->getThumbDisposition( $thumbName );
1152 $status = $this->repo
->quickImport( $tmpThumbPath, $thumbPath, $disposition );
1153 if ( $status->isOK() ) {
1154 $thumb->setStoragePath( $thumbPath );
1156 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $transformParams, $flags );
1159 $statTiming = microtime( true ) - $starttime;
1160 $stats->timing( 'media.thumbnail.generate.store', 1000 * $statTiming );
1162 // Give extensions a chance to do something with this thumbnail...
1163 Hooks
::run( 'FileTransformed', array( $this, $thumb, $tmpThumbPath, $thumbPath ) );
1170 * Generates chained bucketed thumbnails if needed
1171 * @param array $params
1173 * @return bool Whether at least one bucket was generated
1175 protected function generateBucketsIfNeeded( $params, $flags = 0 ) {
1177 ||
!isset( $params['physicalWidth'] )
1178 ||
!isset( $params['physicalHeight'] )
1183 $bucket = $this->getThumbnailBucket( $params['physicalWidth'] );
1185 if ( !$bucket ||
$bucket == $params['physicalWidth'] ) {
1189 $bucketPath = $this->getBucketThumbPath( $bucket );
1191 if ( $this->repo
->fileExists( $bucketPath ) ) {
1195 $starttime = microtime( true );
1197 $params['physicalWidth'] = $bucket;
1198 $params['width'] = $bucket;
1200 $params = $this->getHandler()->sanitizeParamsForBucketing( $params );
1202 $tmpFile = $this->makeTransformTmpFile( $bucketPath );
1208 $thumb = $this->generateAndSaveThumb( $tmpFile, $params, $flags );
1210 $buckettime = microtime( true ) - $starttime;
1212 if ( !$thumb ||
$thumb->isError() ) {
1216 $this->tmpBucketedThumbCache
[$bucket] = $tmpFile->getPath();
1217 // For the caching to work, we need to make the tmp file survive as long as
1218 // this object exists
1219 $tmpFile->bind( $this );
1221 RequestContext
::getMain()->getStats()->timing(
1222 'media.thumbnail.generate.bucket', 1000 * $buckettime );
1228 * Returns the most appropriate source image for the thumbnail, given a target thumbnail size
1229 * @param array $params
1230 * @return array Source path and width/height of the source
1232 public function getThumbnailSource( $params ) {
1234 && $this->getHandler()->supportsBucketing()
1235 && isset( $params['physicalWidth'] )
1236 && $bucket = $this->getThumbnailBucket( $params['physicalWidth'] )
1238 if ( $this->getWidth() != 0 ) {
1239 $bucketHeight = round( $this->getHeight() * ( $bucket / $this->getWidth() ) );
1244 // Try to avoid reading from storage if the file was generated by this script
1245 if ( isset( $this->tmpBucketedThumbCache
[$bucket] ) ) {
1246 $tmpPath = $this->tmpBucketedThumbCache
[$bucket];
1248 if ( file_exists( $tmpPath ) ) {
1252 'height' => $bucketHeight
1257 $bucketPath = $this->getBucketThumbPath( $bucket );
1259 if ( $this->repo
->fileExists( $bucketPath ) ) {
1260 $fsFile = $this->repo
->getLocalReference( $bucketPath );
1264 'path' => $fsFile->getPath(),
1266 'height' => $bucketHeight
1272 // Thumbnailing a very large file could result in network saturation if
1273 // everyone does it at once.
1274 if ( $this->getSize() >= 1e7
) { // 10MB
1276 $work = new PoolCounterWorkViaCallback( 'GetLocalFileCopy', sha1( $this->getName() ),
1278 'doWork' => function () use ( $that ) {
1279 return $that->getLocalRefPath();
1283 $srcPath = $work->execute();
1285 $srcPath = $this->getLocalRefPath();
1291 'width' => $this->getWidth(),
1292 'height' => $this->getHeight()
1297 * Returns the repo path of the thumb for a given bucket
1298 * @param int $bucket
1301 protected function getBucketThumbPath( $bucket ) {
1302 $thumbName = $this->getBucketThumbName( $bucket );
1303 return $this->getThumbPath( $thumbName );
1307 * Returns the name of the thumb for a given bucket
1308 * @param int $bucket
1311 protected function getBucketThumbName( $bucket ) {
1312 return $this->thumbName( array( 'physicalWidth' => $bucket ) );
1316 * Creates a temp FS file with the same extension and the thumbnail
1317 * @param string $thumbPath Thumbnail path
1318 * @return TempFSFile
1320 protected function makeTransformTmpFile( $thumbPath ) {
1321 $thumbExt = FileBackend
::extensionFromPath( $thumbPath );
1322 return TempFSFile
::factory( 'transform_', $thumbExt );
1326 * @param string $thumbName Thumbnail name
1327 * @param string $dispositionType Type of disposition (either "attachment" or "inline")
1328 * @return string Content-Disposition header value
1330 function getThumbDisposition( $thumbName, $dispositionType = 'inline' ) {
1331 $fileName = $this->name
; // file name to suggest
1332 $thumbExt = FileBackend
::extensionFromPath( $thumbName );
1333 if ( $thumbExt != '' && $thumbExt !== $this->getExtension() ) {
1334 $fileName .= ".$thumbExt";
1337 return FileBackend
::makeContentDisposition( $dispositionType, $fileName );
1341 * Hook into transform() to allow migration of thumbnail files
1343 * Overridden by LocalFile
1344 * @param string $thumbName
1346 function migrateThumbFile( $thumbName ) {
1350 * Get a MediaHandler instance for this file
1352 * @return MediaHandler|bool Registered MediaHandler for file's MIME type
1353 * or false if none found
1355 function getHandler() {
1356 if ( !isset( $this->handler
) ) {
1357 $this->handler
= MediaHandler
::getHandler( $this->getMimeType() );
1360 return $this->handler
;
1364 * Get a ThumbnailImage representing a file type icon
1366 * @return ThumbnailImage
1368 function iconThumb() {
1369 global $wgResourceBasePath, $IP;
1370 $assetsPath = "$wgResourceBasePath/resources/assets/file-type-icons/";
1371 $assetsDirectory = "$IP/resources/assets/file-type-icons/";
1373 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
1374 foreach ( $try as $icon ) {
1375 if ( file_exists( $assetsDirectory . $icon ) ) { // always FS
1376 $params = array( 'width' => 120, 'height' => 120 );
1378 return new ThumbnailImage( $this, $assetsPath . $icon, false, $params );
1386 * Get last thumbnailing error.
1390 function getLastError() {
1391 return $this->lastError
;
1395 * Get all thumbnail names previously generated for this file
1397 * Overridden by LocalFile
1400 function getThumbnails() {
1405 * Purge shared caches such as thumbnails and DB data caching
1407 * Overridden by LocalFile
1408 * @param array $options Options, which include:
1409 * 'forThumbRefresh' : The purging is only to refresh thumbnails
1411 function purgeCache( $options = array() ) {
1415 * Purge the file description page, but don't go after
1416 * pages using the file. Use when modifying file history
1417 * but not the current data.
1419 function purgeDescription() {
1420 $title = $this->getTitle();
1422 $title->invalidateCache();
1423 $title->purgeSquid();
1428 * Purge metadata and all affected pages when the file is created,
1429 * deleted, or majorly updated.
1431 function purgeEverything() {
1432 // Delete thumbnails and refresh file metadata cache
1433 $this->purgeCache();
1434 $this->purgeDescription();
1436 // Purge cache of all pages using this file
1437 $title = $this->getTitle();
1439 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $title, 'imagelinks' ) );
1444 * Return a fragment of the history of file.
1447 * @param int $limit Limit of rows to return
1448 * @param string $start Only revisions older than $start will be returned
1449 * @param string $end Only revisions newer than $end will be returned
1450 * @param bool $inc Include the endpoints of the time range
1454 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1459 * Return the history of this file, line by line. Starts with current version,
1460 * then old versions. Should return an object similar to an image/oldimage
1464 * Overridden in LocalFile
1467 public function nextHistoryLine() {
1472 * Reset the history pointer to the first element of the history.
1473 * Always call this function after using nextHistoryLine() to free db resources
1475 * Overridden in LocalFile.
1477 public function resetHistory() {
1481 * Get the filename hash component of the directory including trailing slash,
1483 * If the repository is not hashed, returns an empty string.
1487 function getHashPath() {
1488 if ( !isset( $this->hashPath
) ) {
1489 $this->assertRepoDefined();
1490 $this->hashPath
= $this->repo
->getHashPath( $this->getName() );
1493 return $this->hashPath
;
1497 * Get the path of the file relative to the public zone root.
1498 * This function is overridden in OldLocalFile to be like getArchiveRel().
1503 return $this->getHashPath() . $this->getName();
1507 * Get the path of an archived file relative to the public zone root
1509 * @param bool|string $suffix If not false, the name of an archived thumbnail file
1513 function getArchiveRel( $suffix = false ) {
1514 $path = 'archive/' . $this->getHashPath();
1515 if ( $suffix === false ) {
1516 $path = substr( $path, 0, -1 );
1525 * Get the path, relative to the thumbnail zone root, of the
1526 * thumbnail directory or a particular file if $suffix is specified
1528 * @param bool|string $suffix If not false, the name of a thumbnail file
1531 function getThumbRel( $suffix = false ) {
1532 $path = $this->getRel();
1533 if ( $suffix !== false ) {
1534 $path .= '/' . $suffix;
1541 * Get urlencoded path of the file relative to the public zone root.
1542 * This function is overridden in OldLocalFile to be like getArchiveUrl().
1546 function getUrlRel() {
1547 return $this->getHashPath() . rawurlencode( $this->getName() );
1551 * Get the path, relative to the thumbnail zone root, for an archived file's thumbs directory
1552 * or a specific thumb if the $suffix is given.
1554 * @param string $archiveName The timestamped name of an archived image
1555 * @param bool|string $suffix If not false, the name of a thumbnail file
1558 function getArchiveThumbRel( $archiveName, $suffix = false ) {
1559 $path = 'archive/' . $this->getHashPath() . $archiveName . "/";
1560 if ( $suffix === false ) {
1561 $path = substr( $path, 0, -1 );
1570 * Get the path of the archived file.
1572 * @param bool|string $suffix If not false, the name of an archived file.
1575 function getArchivePath( $suffix = false ) {
1576 $this->assertRepoDefined();
1578 return $this->repo
->getZonePath( 'public' ) . '/' . $this->getArchiveRel( $suffix );
1582 * Get the path of an archived file's thumbs, or a particular thumb if $suffix is specified
1584 * @param string $archiveName The timestamped name of an archived image
1585 * @param bool|string $suffix If not false, the name of a thumbnail file
1588 function getArchiveThumbPath( $archiveName, $suffix = false ) {
1589 $this->assertRepoDefined();
1591 return $this->repo
->getZonePath( 'thumb' ) . '/' .
1592 $this->getArchiveThumbRel( $archiveName, $suffix );
1596 * Get the path of the thumbnail directory, or a particular file if $suffix is specified
1598 * @param bool|string $suffix If not false, the name of a thumbnail file
1601 function getThumbPath( $suffix = false ) {
1602 $this->assertRepoDefined();
1604 return $this->repo
->getZonePath( 'thumb' ) . '/' . $this->getThumbRel( $suffix );
1608 * Get the path of the transcoded directory, or a particular file if $suffix is specified
1610 * @param bool|string $suffix If not false, the name of a media file
1613 function getTranscodedPath( $suffix = false ) {
1614 $this->assertRepoDefined();
1616 return $this->repo
->getZonePath( 'transcoded' ) . '/' . $this->getThumbRel( $suffix );
1620 * Get the URL of the archive directory, or a particular file if $suffix is specified
1622 * @param bool|string $suffix If not false, the name of an archived file
1625 function getArchiveUrl( $suffix = false ) {
1626 $this->assertRepoDefined();
1627 $ext = $this->getExtension();
1628 $path = $this->repo
->getZoneUrl( 'public', $ext ) . '/archive/' . $this->getHashPath();
1629 if ( $suffix === false ) {
1630 $path = substr( $path, 0, -1 );
1632 $path .= rawurlencode( $suffix );
1639 * Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified
1641 * @param string $archiveName The timestamped name of an archived image
1642 * @param bool|string $suffix If not false, the name of a thumbnail file
1645 function getArchiveThumbUrl( $archiveName, $suffix = false ) {
1646 $this->assertRepoDefined();
1647 $ext = $this->getExtension();
1648 $path = $this->repo
->getZoneUrl( 'thumb', $ext ) . '/archive/' .
1649 $this->getHashPath() . rawurlencode( $archiveName ) . "/";
1650 if ( $suffix === false ) {
1651 $path = substr( $path, 0, -1 );
1653 $path .= rawurlencode( $suffix );
1660 * Get the URL of the zone directory, or a particular file if $suffix is specified
1662 * @param string $zone Name of requested zone
1663 * @param bool|string $suffix If not false, the name of a file in zone
1664 * @return string Path
1666 function getZoneUrl( $zone, $suffix = false ) {
1667 $this->assertRepoDefined();
1668 $ext = $this->getExtension();
1669 $path = $this->repo
->getZoneUrl( $zone, $ext ) . '/' . $this->getUrlRel();
1670 if ( $suffix !== false ) {
1671 $path .= '/' . rawurlencode( $suffix );
1678 * Get the URL of the thumbnail directory, or a particular file if $suffix is specified
1680 * @param bool|string $suffix If not false, the name of a thumbnail file
1681 * @return string Path
1683 function getThumbUrl( $suffix = false ) {
1684 return $this->getZoneUrl( 'thumb', $suffix );
1688 * Get the URL of the transcoded directory, or a particular file if $suffix is specified
1690 * @param bool|string $suffix If not false, the name of a media file
1691 * @return string Path
1693 function getTranscodedUrl( $suffix = false ) {
1694 return $this->getZoneUrl( 'transcoded', $suffix );
1698 * Get the public zone virtual URL for a current version source file
1700 * @param bool|string $suffix If not false, the name of a thumbnail file
1703 function getVirtualUrl( $suffix = false ) {
1704 $this->assertRepoDefined();
1705 $path = $this->repo
->getVirtualUrl() . '/public/' . $this->getUrlRel();
1706 if ( $suffix !== false ) {
1707 $path .= '/' . rawurlencode( $suffix );
1714 * Get the public zone virtual URL for an archived version source file
1716 * @param bool|string $suffix If not false, the name of a thumbnail file
1719 function getArchiveVirtualUrl( $suffix = false ) {
1720 $this->assertRepoDefined();
1721 $path = $this->repo
->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
1722 if ( $suffix === false ) {
1723 $path = substr( $path, 0, -1 );
1725 $path .= rawurlencode( $suffix );
1732 * Get the virtual URL for a thumbnail file or directory
1734 * @param bool|string $suffix If not false, the name of a thumbnail file
1737 function getThumbVirtualUrl( $suffix = false ) {
1738 $this->assertRepoDefined();
1739 $path = $this->repo
->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
1740 if ( $suffix !== false ) {
1741 $path .= '/' . rawurlencode( $suffix );
1750 function isHashed() {
1751 $this->assertRepoDefined();
1753 return (bool)$this->repo
->getHashLevels();
1757 * @throws MWException
1759 function readOnlyError() {
1760 throw new MWException( get_class( $this ) . ': write operations are not supported' );
1764 * Record a file upload in the upload log and the image table
1766 * Overridden by LocalFile
1767 * @param string $oldver
1768 * @param string $desc
1769 * @param string $license
1770 * @param string $copyStatus
1771 * @param string $source
1772 * @param bool $watch
1773 * @param string|bool $timestamp
1774 * @param null|User $user User object or null to use $wgUser
1776 * @throws MWException
1778 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1779 $watch = false, $timestamp = false, User
$user = null
1781 $this->readOnlyError();
1785 * Move or copy a file to its public location. If a file exists at the
1786 * destination, move it to an archive. Returns a FileRepoStatus object with
1787 * the archive name in the "value" member on success.
1789 * The archive name should be passed through to recordUpload for database
1792 * Options to $options include:
1793 * - headers : name/value map of HTTP headers to use in response to GET/HEAD requests
1795 * @param string $srcPath Local filesystem path to the source image
1796 * @param int $flags A bitwise combination of:
1797 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1798 * @param array $options Optional additional parameters
1799 * @return FileRepoStatus On success, the value member contains the
1800 * archive name, or an empty string if it was a new file.
1803 * Overridden by LocalFile
1805 function publish( $srcPath, $flags = 0, array $options = array() ) {
1806 $this->readOnlyError();
1810 * @param bool|IContextSource $context Context to use (optional)
1813 function formatMetadata( $context = false ) {
1814 if ( !$this->getHandler() ) {
1818 return $this->getHandler()->formatMetadata( $this, $context );
1822 * Returns true if the file comes from the local file repository.
1826 function isLocal() {
1827 return $this->repo
&& $this->repo
->isLocal();
1831 * Returns the name of the repository.
1835 function getRepoName() {
1836 return $this->repo ?
$this->repo
->getName() : 'unknown';
1840 * Returns the repository
1842 * @return FileRepo|LocalRepo|bool
1844 function getRepo() {
1849 * Returns true if the image is an old version
1859 * Is this file a "deleted" file in a private archive?
1862 * @param int $field One of DELETED_* bitfield constants
1865 function isDeleted( $field ) {
1870 * Return the deletion bitfield
1874 function getVisibility() {
1879 * Was this file ever deleted from the wiki?
1883 function wasDeleted() {
1884 $title = $this->getTitle();
1886 return $title && $title->isDeletedQuick();
1890 * Move file to the new title
1892 * Move current, old version and all thumbnails
1893 * to the new filename. Old file is deleted.
1895 * Cache purging is done; checks for validity
1896 * and logging are caller's responsibility
1898 * @param Title $target New file name
1899 * @return FileRepoStatus
1901 function move( $target ) {
1902 $this->readOnlyError();
1906 * Delete all versions of the file.
1908 * Moves the files into an archive directory (or deletes them)
1909 * and removes the database rows.
1911 * Cache purging is done; logging is caller's responsibility.
1913 * @param string $reason
1914 * @param bool $suppress Hide content from sysops?
1915 * @param User|null $user
1916 * @return FileRepoStatus
1918 * Overridden by LocalFile
1920 function delete( $reason, $suppress = false, $user = null ) {
1921 $this->readOnlyError();
1925 * Restore all or specified deleted revisions to the given file.
1926 * Permissions and logging are left to the caller.
1928 * May throw database exceptions on error.
1930 * @param array $versions Set of record ids of deleted items to restore,
1931 * or empty to restore all revisions.
1932 * @param bool $unsuppress Remove restrictions on content upon restoration?
1933 * @return int|bool The number of file revisions restored if successful,
1934 * or false on failure
1936 * Overridden by LocalFile
1938 function restore( $versions = array(), $unsuppress = false ) {
1939 $this->readOnlyError();
1943 * Returns 'true' if this file is a type which supports multiple pages,
1944 * e.g. DJVU or PDF. Note that this may be true even if the file in
1945 * question only has a single page.
1949 function isMultipage() {
1950 return $this->getHandler() && $this->handler
->isMultiPage( $this );
1954 * Returns the number of pages of a multipage document, or false for
1955 * documents which aren't multipage documents
1959 function pageCount() {
1960 if ( !isset( $this->pageCount
) ) {
1961 if ( $this->getHandler() && $this->handler
->isMultiPage( $this ) ) {
1962 $this->pageCount
= $this->handler
->pageCount( $this );
1964 $this->pageCount
= false;
1968 return $this->pageCount
;
1972 * Calculate the height of a thumbnail using the source and destination width
1974 * @param int $srcWidth
1975 * @param int $srcHeight
1976 * @param int $dstWidth
1980 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1981 // Exact integer multiply followed by division
1982 if ( $srcWidth == 0 ) {
1985 return round( $srcHeight * $dstWidth / $srcWidth );
1990 * Get an image size array like that returned by getImageSize(), or false if it
1991 * can't be determined. Loads the image size directly from the file ignoring caches.
1993 * @note Use getWidth()/getHeight() instead of this method unless you have a
1994 * a good reason. This method skips all caches.
1996 * @param string $filePath The path to the file (e.g. From getLocalPathRef() )
1997 * @return array The width, followed by height, with optionally more things after
1999 function getImageSize( $filePath ) {
2000 if ( !$this->getHandler() ) {
2004 return $this->getHandler()->getImageSize( $this, $filePath );
2008 * Get the URL of the image description page. May return false if it is
2009 * unknown or not applicable.
2013 function getDescriptionUrl() {
2014 if ( $this->repo
) {
2015 return $this->repo
->getDescriptionUrl( $this->getName() );
2022 * Get the HTML text of the description page, if available
2024 * @param bool|Language $lang Optional language to fetch description in
2027 function getDescriptionText( $lang = false ) {
2030 if ( !$this->repo ||
!$this->repo
->fetchDescription
) {
2034 $lang = $lang ?
: $wgLang;
2036 $renderUrl = $this->repo
->getDescriptionRenderUrl( $this->getName(), $lang->getCode() );
2038 $cache = ObjectCache
::getMainWANInstance();
2041 if ( $this->repo
->descriptionCacheExpiry
> 0 ) {
2042 wfDebug( "Attempting to get the description from cache..." );
2043 $key = $this->repo
->getLocalCacheKey(
2044 'RemoteFileDescription',
2049 $obj = $cache->get( $key );
2051 wfDebug( "success!\n" );
2055 wfDebug( "miss\n" );
2057 wfDebug( "Fetching shared description from $renderUrl\n" );
2058 $res = Http
::get( $renderUrl, array(), __METHOD__
);
2059 if ( $res && $key ) {
2060 $cache->set( $key, $res, $this->repo
->descriptionCacheExpiry
);
2070 * Get description of file revision
2073 * @param int $audience One of:
2074 * File::FOR_PUBLIC to be displayed to all users
2075 * File::FOR_THIS_USER to be displayed to the given user
2076 * File::RAW get the description regardless of permissions
2077 * @param User $user User object to check for, only if FOR_THIS_USER is
2078 * passed to the $audience parameter
2081 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
2086 * Get the 14-character timestamp of the file upload
2088 * @return string|bool TS_MW timestamp or false on failure
2090 function getTimestamp() {
2091 $this->assertRepoDefined();
2093 return $this->repo
->getFileTimestamp( $this->getPath() );
2097 * Returns the timestamp (in TS_MW format) of the last change of the description page.
2098 * Returns false if the file does not have a description page, or retrieving the timestamp
2099 * would be expensive.
2101 * @return string|bool
2103 public function getDescriptionTouched() {
2108 * Get the SHA-1 base 36 hash of the file
2112 function getSha1() {
2113 $this->assertRepoDefined();
2115 return $this->repo
->getFileSha1( $this->getPath() );
2119 * Get the deletion archive key, "<sha1>.<ext>"
2123 function getStorageKey() {
2124 $hash = $this->getSha1();
2128 $ext = $this->getExtension();
2129 $dotExt = $ext === '' ?
'' : ".$ext";
2131 return $hash . $dotExt;
2135 * Determine if the current user is allowed to view a particular
2136 * field of this file, if it's marked as deleted.
2139 * @param User $user User object to check, or null to use $wgUser
2142 function userCan( $field, User
$user = null ) {
2147 * @return array HTTP header name/value map to use for HEAD/GET request responses
2149 function getStreamHeaders() {
2150 $handler = $this->getHandler();
2152 return $handler->getStreamHeaders( $this->getMetadata() );
2161 function getLongDesc() {
2162 $handler = $this->getHandler();
2164 return $handler->getLongDesc( $this );
2166 return MediaHandler
::getGeneralLongDesc( $this );
2173 function getShortDesc() {
2174 $handler = $this->getHandler();
2176 return $handler->getShortDesc( $this );
2178 return MediaHandler
::getGeneralShortDesc( $this );
2185 function getDimensionsString() {
2186 $handler = $this->getHandler();
2188 return $handler->getDimensionsString( $this );
2197 function getRedirected() {
2198 return $this->redirected
;
2202 * @return Title|null
2204 function getRedirectedTitle() {
2205 if ( $this->redirected
) {
2206 if ( !$this->redirectTitle
) {
2207 $this->redirectTitle
= Title
::makeTitle( NS_FILE
, $this->redirected
);
2210 return $this->redirectTitle
;
2217 * @param string $from
2220 function redirectedFrom( $from ) {
2221 $this->redirected
= $from;
2227 function isMissing() {
2232 * Check if this file object is small and can be cached
2235 public function isCacheable() {
2240 * Assert that $this->repo is set to a valid FileRepo instance
2241 * @throws MWException
2243 protected function assertRepoDefined() {
2244 if ( !( $this->repo
instanceof $this->repoClass
) ) {
2245 throw new MWException( "A {$this->repoClass} object is not set for this File.\n" );
2250 * Assert that $this->title is set to a Title
2251 * @throws MWException
2253 protected function assertTitleDefined() {
2254 if ( !( $this->title
instanceof Title
) ) {
2255 throw new MWException( "A Title object is not set for this File.\n" );
2260 * True if creating thumbnails from the file is large or otherwise resource-intensive.
2263 public function isExpensiveToThumbnail() {
2264 $handler = $this->getHandler();
2265 return $handler ?
$handler->isExpensiveToThumbnail( $this ) : false;
2269 * Whether the thumbnails created on the same server as this code is running.
2273 public function isTransformedLocally() {