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
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 if ( $title !== false ) { // subclasses may not use MW titles
167 $title = self
::normalizeTitle( $title, 'exception' );
169 $this->title
= $title;
174 * Given a string or Title object return either a
175 * valid Title object with namespace NS_FILE or null
177 * @param Title|string $title
178 * @param string|bool $exception Use 'exception' to throw an error on bad titles
179 * @throws MWException
182 static function normalizeTitle( $title, $exception = false ) {
184 if ( $ret instanceof Title
) {
185 # Normalize NS_MEDIA -> NS_FILE
186 if ( $ret->getNamespace() == NS_MEDIA
) {
187 $ret = Title
::makeTitleSafe( NS_FILE
, $ret->getDBkey() );
188 # Sanity check the title namespace
189 } elseif ( $ret->getNamespace() !== NS_FILE
) {
193 # Convert strings to Title objects
194 $ret = Title
::makeTitleSafe( NS_FILE
, (string)$ret );
196 if ( !$ret && $exception !== false ) {
197 throw new MWException( "`$title` is not a valid file title." );
203 function __get( $name ) {
204 $function = array( $this, 'get' . ucfirst( $name ) );
205 if ( !is_callable( $function ) ) {
208 $this->$name = call_user_func( $function );
215 * Normalize a file extension to the common form, and ensure it's clean.
216 * Extensions with non-alphanumeric characters will be discarded.
218 * @param string $ext (without the .)
221 static function normalizeExtension( $ext ) {
222 $lower = strtolower( $ext );
229 if ( isset( $squish[$lower] ) ) {
230 return $squish[$lower];
231 } elseif ( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
239 * Checks if file extensions are compatible
241 * @param File $old Old file
242 * @param string $new New name
246 static function checkExtensionCompatibility( File
$old, $new ) {
247 $oldMime = $old->getMimeType();
248 $n = strrpos( $new, '.' );
249 $newExt = self
::normalizeExtension( $n ?
substr( $new, $n +
1 ) : '' );
250 $mimeMagic = MimeMagic
::singleton();
252 return $mimeMagic->isMatchingExtension( $newExt, $oldMime );
256 * Upgrade the database row if there is one
257 * Called by ImagePage
260 function upgradeRow() {
264 * Split an internet media type into its two components; if not
265 * a two-part name, set the minor type to 'unknown'.
267 * @param string $mime "text/html" etc
268 * @return array ("text", "html") etc
270 public static function splitMime( $mime ) {
271 if ( strpos( $mime, '/' ) !== false ) {
272 return explode( '/', $mime, 2 );
274 return array( $mime, 'unknown' );
279 * Callback for usort() to do file sorts by name
283 * @return int Result of name comparison
285 public static function compare( File
$a, File
$b ) {
286 return strcmp( $a->getName(), $b->getName() );
290 * Return the name of this file
294 public function getName() {
295 if ( !isset( $this->name
) ) {
296 $this->assertRepoDefined();
297 $this->name
= $this->repo
->getNameFromTitle( $this->title
);
304 * Get the file extension, e.g. "svg"
308 function getExtension() {
309 if ( !isset( $this->extension
) ) {
310 $n = strrpos( $this->getName(), '.' );
311 $this->extension
= self
::normalizeExtension(
312 $n ?
substr( $this->getName(), $n +
1 ) : '' );
315 return $this->extension
;
319 * Return the associated title object
323 public function getTitle() {
328 * Return the title used to find this file
332 public function getOriginalTitle() {
333 if ( $this->redirected
) {
334 return $this->getRedirectedTitle();
341 * Return the URL of the file
345 public function getUrl() {
346 if ( !isset( $this->url
) ) {
347 $this->assertRepoDefined();
348 $ext = $this->getExtension();
349 $this->url
= $this->repo
->getZoneUrl( 'public', $ext ) . '/' . $this->getUrlRel();
356 * Return a fully-qualified URL to the file.
357 * Upload URL paths _may or may not_ be fully qualified, so
358 * we check. Local paths are assumed to belong on $wgServer.
362 public function getFullUrl() {
363 return wfExpandUrl( $this->getUrl(), PROTO_RELATIVE
);
369 public function getCanonicalUrl() {
370 return wfExpandUrl( $this->getUrl(), PROTO_CANONICAL
);
376 function getViewURL() {
377 if ( $this->mustRender() ) {
378 if ( $this->canRender() ) {
379 return $this->createThumb( $this->getWidth() );
381 wfDebug( __METHOD__
. ': supposed to render ' . $this->getName() .
382 ' (' . $this->getMimeType() . "), but can't!\n" );
384 return $this->getURL(); #hm... return NULL?
387 return $this->getURL();
392 * Return the storage path to the file. Note that this does
393 * not mean that a file actually exists under that location.
395 * This path depends on whether directory hashing is active or not,
396 * i.e. whether the files are all found in the same directory,
397 * or in hashed paths like /images/3/3c.
399 * Most callers don't check the return value, but ForeignAPIFile::getPath
402 * @return string|bool ForeignAPIFile::getPath can return false
404 public function getPath() {
405 if ( !isset( $this->path
) ) {
406 $this->assertRepoDefined();
407 $this->path
= $this->repo
->getZonePath( 'public' ) . '/' . $this->getRel();
414 * Get an FS copy or original of this file and return the path.
415 * Returns false on failure. Callers must not alter the file.
416 * Temporary files are cleared automatically.
418 * @return string|bool False on failure
420 public function getLocalRefPath() {
421 $this->assertRepoDefined();
422 if ( !isset( $this->fsFile
) ) {
423 $this->fsFile
= $this->repo
->getLocalReference( $this->getPath() );
424 if ( !$this->fsFile
) {
425 $this->fsFile
= false; // null => false; cache negative hits
429 return ( $this->fsFile
)
430 ?
$this->fsFile
->getPath()
435 * Return the width of the image. Returns false if the width is unknown
439 * Overridden by LocalFile, UnregisteredLocalFile
444 public function getWidth( $page = 1 ) {
449 * Return the height of the image. Returns false if the height is unknown
453 * Overridden by LocalFile, UnregisteredLocalFile
456 * @return bool|int False on failure
458 public function getHeight( $page = 1 ) {
463 * Return the smallest bucket from $wgThumbnailBuckets which is at least
464 * $wgThumbnailMinimumBucketDistance larger than $desiredWidth. The returned bucket, if any,
465 * will always be bigger than $desiredWidth.
467 * @param int $desiredWidth
471 public function getThumbnailBucket( $desiredWidth, $page = 1 ) {
472 global $wgThumbnailBuckets, $wgThumbnailMinimumBucketDistance;
474 wfDebugLog( 'thumbnail', 'thumbnail buckets ' . json_encode( $wgThumbnailBuckets ) );
476 $imageWidth = $this->getWidth( $page );
478 if ( $imageWidth === false ) {
482 if ( $desiredWidth > $imageWidth ) {
486 if ( !$wgThumbnailBuckets ) {
490 $sortedBuckets = $wgThumbnailBuckets;
492 sort( $sortedBuckets );
494 foreach ( $sortedBuckets as $bucket ) {
495 if ( $bucket >= $imageWidth ) {
499 if ( $bucket - $wgThumbnailMinimumBucketDistance > $desiredWidth ) {
504 // Image is bigger than any available bucket
509 * Returns ID or name of user who uploaded the file
512 * @param string $type 'text' or 'id'
515 public function getUser( $type = 'text' ) {
520 * Get the duration of a media file in seconds
524 public function getLength() {
525 $handler = $this->getHandler();
527 return $handler->getLength( $this );
534 * Return true if the file is vectorized
538 public function isVectorized() {
539 $handler = $this->getHandler();
541 return $handler->isVectorized( $this );
548 * Gives a (possibly empty) list of languages to render
551 * If the file doesn't have translations, or if the file
552 * format does not support that sort of thing, returns
558 public function getAvailableLanguages() {
559 $handler = $this->getHandler();
561 return $handler->getAvailableLanguages( $this );
568 * In files that support multiple language, what is the default language
569 * to use if none specified.
571 * @return string Lang code, or null if filetype doesn't support multiple languages.
574 public function getDefaultRenderLanguage() {
575 $handler = $this->getHandler();
577 return $handler->getDefaultRenderLanguage( $this );
584 * Will the thumbnail be animated if one would expect it to be.
586 * Currently used to add a warning to the image description page
588 * @return bool False if the main image is both animated
589 * and the thumbnail is not. In all other cases must return
590 * true. If image is not renderable whatsoever, should
593 public function canAnimateThumbIfAppropriate() {
594 $handler = $this->getHandler();
596 // We cannot handle image whatsoever, thus
597 // one would not expect it to be animated
601 if ( $this->allowInlineDisplay()
602 && $handler->isAnimatedImage( $this )
603 && !$handler->canAnimateThumbnail( $this )
605 // Image is animated, but thumbnail isn't.
606 // This is unexpected to the user.
609 // Image is not animated, so one would
610 // not expect thumb to be
617 * Get handler-specific metadata
618 * Overridden by LocalFile, UnregisteredLocalFile
622 public function getMetadata() {
627 * Like getMetadata but returns a handler independent array of common values.
628 * @see MediaHandler::getCommonMetaArray()
629 * @return array|bool Array or false if not supported
632 public function getCommonMetaArray() {
633 $handler = $this->getHandler();
639 return $handler->getCommonMetaArray( $this );
643 * get versioned metadata
645 * @param array|string $metadata Array or string of (serialized) metadata
646 * @param int $version Version number.
647 * @return array Array containing metadata, or what was passed to it on fail
648 * (unserializing if not array)
650 public function convertMetadataVersion( $metadata, $version ) {
651 $handler = $this->getHandler();
652 if ( !is_array( $metadata ) ) {
653 // Just to make the return type consistent
654 $metadata = unserialize( $metadata );
657 return $handler->convertMetadataVersion( $metadata, $version );
664 * Return the bit depth of the file
665 * Overridden by LocalFile
669 public function getBitDepth() {
674 * Return the size of the image file, in bytes
675 * Overridden by LocalFile, UnregisteredLocalFile
679 public function getSize() {
684 * Returns the MIME type of the file.
685 * Overridden by LocalFile, UnregisteredLocalFile
690 function getMimeType() {
691 return 'unknown/unknown';
695 * Return the type of the media in the file.
696 * Use the value returned by this function with the MEDIATYPE_xxx constants.
697 * Overridden by LocalFile,
701 function getMediaType() {
702 return MEDIATYPE_UNKNOWN
;
706 * Checks if the output of transform() for this file is likely
707 * to be valid. If this is false, various user elements will
708 * display a placeholder instead.
710 * Currently, this checks if the file is an image format
711 * that can be converted to a format
712 * supported by all browsers (namely GIF, PNG and JPEG),
713 * or if it is an SVG image and SVG conversion is enabled.
717 function canRender() {
718 if ( !isset( $this->canRender
) ) {
719 $this->canRender
= $this->getHandler() && $this->handler
->canRender( $this ) && $this->exists();
722 return $this->canRender
;
726 * Accessor for __get()
729 protected function getCanRender() {
730 return $this->canRender();
734 * Return true if the file is of a type that can't be directly
735 * rendered by typical browsers and needs to be re-rasterized.
737 * This returns true for everything but the bitmap types
738 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
739 * also return true for any non-image formats.
743 function mustRender() {
744 return $this->getHandler() && $this->handler
->mustRender( $this );
748 * Alias for canRender()
752 function allowInlineDisplay() {
753 return $this->canRender();
757 * Determines if this media file is in a format that is unlikely to
758 * contain viruses or malicious content. It uses the global
759 * $wgTrustedMediaFormats list to determine if the file is safe.
761 * This is used to show a warning on the description page of non-safe files.
762 * It may also be used to disallow direct [[media:...]] links to such files.
764 * Note that this function will always return true if allowInlineDisplay()
765 * or isTrustedFile() is true for this file.
769 function isSafeFile() {
770 if ( !isset( $this->isSafeFile
) ) {
771 $this->isSafeFile
= $this->getIsSafeFileUncached();
774 return $this->isSafeFile
;
778 * Accessor for __get()
782 protected function getIsSafeFile() {
783 return $this->isSafeFile();
791 protected function getIsSafeFileUncached() {
792 global $wgTrustedMediaFormats;
794 if ( $this->allowInlineDisplay() ) {
797 if ( $this->isTrustedFile() ) {
801 $type = $this->getMediaType();
802 $mime = $this->getMimeType();
803 #wfDebug( "LocalFile::isSafeFile: type= $type, mime= $mime\n" );
805 if ( !$type ||
$type === MEDIATYPE_UNKNOWN
) {
806 return false; #unknown type, not trusted
808 if ( in_array( $type, $wgTrustedMediaFormats ) ) {
812 if ( $mime === "unknown/unknown" ) {
813 return false; #unknown type, not trusted
815 if ( in_array( $mime, $wgTrustedMediaFormats ) ) {
823 * Returns true if the file is flagged as trusted. Files flagged that way
824 * can be linked to directly, even if that is not allowed for this type of
827 * This is a dummy function right now and always returns false. It could be
828 * implemented to extract a flag from the database. The trusted flag could be
829 * set on upload, if the user has sufficient privileges, to bypass script-
830 * and html-filters. It may even be coupled with cryptographics signatures
835 function isTrustedFile() {
836 #this could be implemented to check a flag in the database,
837 #look for signatures, etc
842 * Returns true if file exists in the repository.
844 * Overridden by LocalFile to avoid unnecessary stat calls.
846 * @return bool Whether file exists in the repository.
848 public function exists() {
849 return $this->getPath() && $this->repo
->fileExists( $this->path
);
853 * Returns true if file exists in the repository and can be included in a page.
854 * It would be unsafe to include private images, making public thumbnails inadvertently
856 * @return bool Whether file exists in the repository and is includable.
858 public function isVisible() {
859 return $this->exists();
865 function getTransformScript() {
866 if ( !isset( $this->transformScript
) ) {
867 $this->transformScript
= false;
869 $script = $this->repo
->getThumbScriptUrl();
871 $this->transformScript
= wfAppendQuery( $script, array( 'f' => $this->getName() ) );
876 return $this->transformScript
;
880 * Get a ThumbnailImage which is the same size as the source
882 * @param array $handlerParams
886 function getUnscaledThumb( $handlerParams = array() ) {
887 $hp =& $handlerParams;
888 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
889 $width = $this->getWidth( $page );
891 return $this->iconThumb();
893 $hp['width'] = $width;
894 // be sure to ignore any height specification as well (bug 62258)
895 unset( $hp['height'] );
897 return $this->transform( $hp );
901 * Return the file name of a thumbnail with the specified parameters.
902 * Use File::THUMB_FULL_NAME to always get a name like "<params>-<source>".
903 * Otherwise, the format may be "<params>-<source>" or "<params>-thumbnail.<ext>".
905 * @param array $params Handler-specific parameters
906 * @param int $flags Bitfield that supports THUMB_* constants
909 public function thumbName( $params, $flags = 0 ) {
910 $name = ( $this->repo
&& !( $flags & self
::THUMB_FULL_NAME
) )
911 ?
$this->repo
->nameForThumb( $this->getName() )
914 return $this->generateThumbName( $name, $params );
918 * Generate a thumbnail file name from a name and specified parameters
920 * @param string $name
921 * @param array $params Parameters which will be passed to MediaHandler::makeParamString
924 public function generateThumbName( $name, $params ) {
925 if ( !$this->getHandler() ) {
928 $extension = $this->getExtension();
929 list( $thumbExt, ) = $this->getHandler()->getThumbType(
930 $extension, $this->getMimeType(), $params );
931 $thumbName = $this->getHandler()->makeParamString( $params ) . '-' . $name;
932 if ( $thumbExt != $extension ) {
933 $thumbName .= ".$thumbExt";
940 * Create a thumbnail of the image having the specified width/height.
941 * The thumbnail will not be created if the width is larger than the
942 * image's width. Let the browser do the scaling in this case.
943 * The thumbnail is stored on disk and is only computed if the thumbnail
944 * file does not exist OR if it is older than the image.
947 * Keeps aspect ratio of original image. If both width and height are
948 * specified, the generated image will be no bigger than width x height,
949 * and will also have correct aspect ratio.
951 * @param int $width Maximum width of the generated thumbnail
952 * @param int $height Maximum height of the image (optional)
956 public function createThumb( $width, $height = -1 ) {
957 $params = array( 'width' => $width );
958 if ( $height != -1 ) {
959 $params['height'] = $height;
961 $thumb = $this->transform( $params );
962 if ( !$thumb ||
$thumb->isError() ) {
966 return $thumb->getUrl();
970 * Return either a MediaTransformError or placeholder thumbnail (if $wgIgnoreImageErrors)
972 * @param string $thumbPath Thumbnail storage path
973 * @param string $thumbUrl Thumbnail URL
974 * @param array $params
976 * @return MediaTransformOutput
978 protected function transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags ) {
979 global $wgIgnoreImageErrors;
981 $handler = $this->getHandler();
982 if ( $handler && $wgIgnoreImageErrors && !( $flags & self
::RENDER_NOW
) ) {
983 return $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
985 return new MediaTransformError( 'thumbnail_error',
986 $params['width'], 0, wfMessage( 'thumbnail-dest-create' )->text() );
991 * Transform a media file
993 * @param array $params An associative array of handler-specific parameters.
994 * Typical keys are width, height and page.
995 * @param int $flags A bitfield, may contain self::RENDER_NOW to force rendering
996 * @return MediaTransformOutput|bool False on failure
998 function transform( $params, $flags = 0 ) {
999 global $wgThumbnailEpoch;
1002 if ( !$this->canRender() ) {
1003 $thumb = $this->iconThumb();
1004 break; // not a bitmap or renderable image, don't try
1007 // Get the descriptionUrl to embed it as comment into the thumbnail. Bug 19791.
1008 $descriptionUrl = $this->getDescriptionUrl();
1009 if ( $descriptionUrl ) {
1010 $params['descriptionUrl'] = wfExpandUrl( $descriptionUrl, PROTO_CANONICAL
);
1013 $handler = $this->getHandler();
1014 $script = $this->getTransformScript();
1015 if ( $script && !( $flags & self
::RENDER_NOW
) ) {
1016 // Use a script to transform on client request, if possible
1017 $thumb = $handler->getScriptedTransform( $this, $script, $params );
1023 $normalisedParams = $params;
1024 $handler->normaliseParams( $this, $normalisedParams );
1026 $thumbName = $this->thumbName( $normalisedParams );
1027 $thumbUrl = $this->getThumbUrl( $thumbName );
1028 $thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
1030 if ( $this->repo
) {
1031 // Defer rendering if a 404 handler is set up...
1032 if ( $this->repo
->canTransformVia404() && !( $flags & self
::RENDER_NOW
) ) {
1033 wfDebug( __METHOD__
. " transformation deferred.\n" );
1034 // XXX: Pass in the storage path even though we are not rendering anything
1035 // and the path is supposed to be an FS path. This is due to getScalerType()
1036 // getting called on the path and clobbering $thumb->getUrl() if it's false.
1037 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
1040 // Check if an up-to-date thumbnail already exists...
1041 wfDebug( __METHOD__
. ": Doing stat for $thumbPath\n" );
1042 if ( !( $flags & self
::RENDER_FORCE
) && $this->repo
->fileExists( $thumbPath ) ) {
1043 $timestamp = $this->repo
->getFileTimestamp( $thumbPath );
1044 if ( $timestamp !== false && $timestamp >= $wgThumbnailEpoch ) {
1045 // XXX: Pass in the storage path even though we are not rendering anything
1046 // and the path is supposed to be an FS path. This is due to getScalerType()
1047 // getting called on the path and clobbering $thumb->getUrl() if it's false.
1048 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
1049 $thumb->setStoragePath( $thumbPath );
1052 } elseif ( $flags & self
::RENDER_FORCE
) {
1053 wfDebug( __METHOD__
. " forcing rendering per flag File::RENDER_FORCE\n" );
1056 // If the backend is ready-only, don't keep generating thumbnails
1057 // only to return transformation errors, just return the error now.
1058 if ( $this->repo
->getReadOnlyReason() !== false ) {
1059 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
1064 $tmpFile = $this->makeTransformTmpFile( $thumbPath );
1067 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
1069 $thumb = $this->generateAndSaveThumb( $tmpFile, $params, $flags );
1074 return is_object( $thumb ) ?
$thumb : false;
1078 * Generates a thumbnail according to the given parameters and saves it to storage
1079 * @param TempFSFile $tmpFile Temporary file where the rendered thumbnail will be saved
1080 * @param array $transformParams
1082 * @return bool|MediaTransformOutput
1084 public function generateAndSaveThumb( $tmpFile, $transformParams, $flags ) {
1085 global $wgUseSquid, $wgIgnoreImageErrors;
1087 $handler = $this->getHandler();
1089 $normalisedParams = $transformParams;
1090 $handler->normaliseParams( $this, $normalisedParams );
1092 $thumbName = $this->thumbName( $normalisedParams );
1093 $thumbUrl = $this->getThumbUrl( $thumbName );
1094 $thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
1096 $tmpThumbPath = $tmpFile->getPath();
1098 if ( $handler->supportsBucketing() ) {
1099 $this->generateBucketsIfNeeded( $normalisedParams, $flags );
1102 // Actually render the thumbnail...
1103 wfProfileIn( __METHOD__
. '-doTransform' );
1104 $thumb = $handler->doTransform( $this, $tmpThumbPath, $thumbUrl, $transformParams );
1105 wfProfileOut( __METHOD__
. '-doTransform' );
1106 $tmpFile->bind( $thumb ); // keep alive with $thumb
1108 if ( !$thumb ) { // bad params?
1110 } elseif ( $thumb->isError() ) { // transform error
1111 $this->lastError
= $thumb->toText();
1112 // Ignore errors if requested
1113 if ( $wgIgnoreImageErrors && !( $flags & self
::RENDER_NOW
) ) {
1114 $thumb = $handler->getTransform( $this, $tmpThumbPath, $thumbUrl, $transformParams );
1116 } elseif ( $this->repo
&& $thumb->hasFile() && !$thumb->fileIsSource() ) {
1117 // Copy the thumbnail from the file system into storage...
1118 $disposition = $this->getThumbDisposition( $thumbName );
1119 $status = $this->repo
->quickImport( $tmpThumbPath, $thumbPath, $disposition );
1120 if ( $status->isOK() ) {
1121 $thumb->setStoragePath( $thumbPath );
1123 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $transformParams, $flags );
1125 // Give extensions a chance to do something with this thumbnail...
1126 Hooks
::run( 'FileTransformed', array( $this, $thumb, $tmpThumbPath, $thumbPath ) );
1129 // Purge. Useful in the event of Core -> Squid connection failure or squid
1130 // purge collisions from elsewhere during failure. Don't keep triggering for
1131 // "thumbs" which have the main image URL though (bug 13776)
1132 if ( $wgUseSquid ) {
1133 if ( !$thumb ||
$thumb->isError() ||
$thumb->getUrl() != $this->getURL() ) {
1134 SquidUpdate
::purge( array( $thumbUrl ) );
1142 * Generates chained bucketed thumbnails if needed
1143 * @param array $params
1145 * @return bool Whether at least one bucket was generated
1147 protected function generateBucketsIfNeeded( $params, $flags = 0 ) {
1149 ||
!isset( $params['physicalWidth'] )
1150 ||
!isset( $params['physicalHeight'] )
1151 ||
!( $bucket = $this->getThumbnailBucket( $params['physicalWidth'] ) )
1152 ||
$bucket == $params['physicalWidth'] ) {
1156 $bucketPath = $this->getBucketThumbPath( $bucket );
1158 if ( $this->repo
->fileExists( $bucketPath ) ) {
1162 $params['physicalWidth'] = $bucket;
1163 $params['width'] = $bucket;
1165 $params = $this->getHandler()->sanitizeParamsForBucketing( $params );
1167 $bucketName = $this->getBucketThumbName( $bucket );
1169 $tmpFile = $this->makeTransformTmpFile( $bucketPath );
1175 $thumb = $this->generateAndSaveThumb( $tmpFile, $params, $flags );
1177 if ( !$thumb ||
$thumb->isError() ) {
1181 $this->tmpBucketedThumbCache
[$bucket] = $tmpFile->getPath();
1182 // For the caching to work, we need to make the tmp file survive as long as
1183 // this object exists
1184 $tmpFile->bind( $this );
1190 * Returns the most appropriate source image for the thumbnail, given a target thumbnail size
1191 * @param array $params
1192 * @return array Source path and width/height of the source
1194 public function getThumbnailSource( $params ) {
1196 && $this->getHandler()->supportsBucketing()
1197 && isset( $params['physicalWidth'] )
1198 && $bucket = $this->getThumbnailBucket( $params['physicalWidth'] )
1200 if ( $this->getWidth() != 0 ) {
1201 $bucketHeight = round( $this->getHeight() * ( $bucket / $this->getWidth() ) );
1206 // Try to avoid reading from storage if the file was generated by this script
1207 if ( isset( $this->tmpBucketedThumbCache
[$bucket] ) ) {
1208 $tmpPath = $this->tmpBucketedThumbCache
[$bucket];
1210 if ( file_exists( $tmpPath ) ) {
1214 'height' => $bucketHeight
1219 $bucketPath = $this->getBucketThumbPath( $bucket );
1221 if ( $this->repo
->fileExists( $bucketPath ) ) {
1222 $fsFile = $this->repo
->getLocalReference( $bucketPath );
1226 'path' => $fsFile->getPath(),
1228 'height' => $bucketHeight
1234 // Thumbnailing a very large file could result in network saturation if
1235 // everyone does it at once.
1236 if ( $this->getSize() >= 1e7
) { // 10MB
1238 $work = new PoolCounterWorkViaCallback( 'GetLocalFileCopy', sha1( $this->getName() ),
1240 'doWork' => function () use ( $that ) {
1241 return $that->getLocalRefPath();
1245 $srcPath = $work->execute();
1247 $srcPath = $this->getLocalRefPath();
1253 'width' => $this->getWidth(),
1254 'height' => $this->getHeight()
1259 * Returns the repo path of the thumb for a given bucket
1260 * @param int $bucket
1263 protected function getBucketThumbPath( $bucket ) {
1264 $thumbName = $this->getBucketThumbName( $bucket );
1265 return $this->getThumbPath( $thumbName );
1269 * Returns the name of the thumb for a given bucket
1270 * @param int $bucket
1273 protected function getBucketThumbName( $bucket ) {
1274 return $this->thumbName( array( 'physicalWidth' => $bucket ) );
1278 * Creates a temp FS file with the same extension and the thumbnail
1279 * @param string $thumbPath Thumbnail path
1280 * @return TempFSFile
1282 protected function makeTransformTmpFile( $thumbPath ) {
1283 $thumbExt = FileBackend
::extensionFromPath( $thumbPath );
1284 return TempFSFile
::factory( 'transform_', $thumbExt );
1288 * @param string $thumbName Thumbnail name
1289 * @param string $dispositionType Type of disposition (either "attachment" or "inline")
1290 * @return string Content-Disposition header value
1292 function getThumbDisposition( $thumbName, $dispositionType = 'inline' ) {
1293 $fileName = $this->name
; // file name to suggest
1294 $thumbExt = FileBackend
::extensionFromPath( $thumbName );
1295 if ( $thumbExt != '' && $thumbExt !== $this->getExtension() ) {
1296 $fileName .= ".$thumbExt";
1299 return FileBackend
::makeContentDisposition( $dispositionType, $fileName );
1303 * Hook into transform() to allow migration of thumbnail files
1305 * Overridden by LocalFile
1306 * @param string $thumbName
1308 function migrateThumbFile( $thumbName ) {
1312 * Get a MediaHandler instance for this file
1314 * @return MediaHandler|bool Registered MediaHandler for file's MIME type
1315 * or false if none found
1317 function getHandler() {
1318 if ( !isset( $this->handler
) ) {
1319 $this->handler
= MediaHandler
::getHandler( $this->getMimeType() );
1322 return $this->handler
;
1326 * Get a ThumbnailImage representing a file type icon
1328 * @return ThumbnailImage
1330 function iconThumb() {
1331 global $wgResourceBasePath, $IP;
1332 $assetsPath = "$wgResourceBasePath/resources/assets/file-type-icons/";
1333 $assetsDirectory = "$IP/resources/assets/file-type-icons/";
1335 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
1336 foreach ( $try as $icon ) {
1337 if ( file_exists( $assetsDirectory . $icon ) ) { // always FS
1338 $params = array( 'width' => 120, 'height' => 120 );
1340 return new ThumbnailImage( $this, $assetsPath . $icon, false, $params );
1348 * Get last thumbnailing error.
1352 function getLastError() {
1353 return $this->lastError
;
1357 * Get all thumbnail names previously generated for this file
1359 * Overridden by LocalFile
1362 function getThumbnails() {
1367 * Purge shared caches such as thumbnails and DB data caching
1369 * Overridden by LocalFile
1370 * @param array $options Options, which include:
1371 * 'forThumbRefresh' : The purging is only to refresh thumbnails
1373 function purgeCache( $options = array() ) {
1377 * Purge the file description page, but don't go after
1378 * pages using the file. Use when modifying file history
1379 * but not the current data.
1381 function purgeDescription() {
1382 $title = $this->getTitle();
1384 $title->invalidateCache();
1385 $title->purgeSquid();
1390 * Purge metadata and all affected pages when the file is created,
1391 * deleted, or majorly updated.
1393 function purgeEverything() {
1394 // Delete thumbnails and refresh file metadata cache
1395 $this->purgeCache();
1396 $this->purgeDescription();
1398 // Purge cache of all pages using this file
1399 $title = $this->getTitle();
1401 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
1402 $update->doUpdate();
1407 * Return a fragment of the history of file.
1410 * @param int $limit Limit of rows to return
1411 * @param string $start Only revisions older than $start will be returned
1412 * @param string $end Only revisions newer than $end will be returned
1413 * @param bool $inc Include the endpoints of the time range
1417 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1422 * Return the history of this file, line by line. Starts with current version,
1423 * then old versions. Should return an object similar to an image/oldimage
1427 * Overridden in LocalFile
1430 public function nextHistoryLine() {
1435 * Reset the history pointer to the first element of the history.
1436 * Always call this function after using nextHistoryLine() to free db resources
1438 * Overridden in LocalFile.
1440 public function resetHistory() {
1444 * Get the filename hash component of the directory including trailing slash,
1446 * If the repository is not hashed, returns an empty string.
1450 function getHashPath() {
1451 if ( !isset( $this->hashPath
) ) {
1452 $this->assertRepoDefined();
1453 $this->hashPath
= $this->repo
->getHashPath( $this->getName() );
1456 return $this->hashPath
;
1460 * Get the path of the file relative to the public zone root.
1461 * This function is overridden in OldLocalFile to be like getArchiveRel().
1466 return $this->getHashPath() . $this->getName();
1470 * Get the path of an archived file relative to the public zone root
1472 * @param bool|string $suffix If not false, the name of an archived thumbnail file
1476 function getArchiveRel( $suffix = false ) {
1477 $path = 'archive/' . $this->getHashPath();
1478 if ( $suffix === false ) {
1479 $path = substr( $path, 0, -1 );
1488 * Get the path, relative to the thumbnail zone root, of the
1489 * thumbnail directory or a particular file if $suffix is specified
1491 * @param bool|string $suffix If not false, the name of a thumbnail file
1494 function getThumbRel( $suffix = false ) {
1495 $path = $this->getRel();
1496 if ( $suffix !== false ) {
1497 $path .= '/' . $suffix;
1504 * Get urlencoded path of the file relative to the public zone root.
1505 * This function is overridden in OldLocalFile to be like getArchiveUrl().
1509 function getUrlRel() {
1510 return $this->getHashPath() . rawurlencode( $this->getName() );
1514 * Get the path, relative to the thumbnail zone root, for an archived file's thumbs directory
1515 * or a specific thumb if the $suffix is given.
1517 * @param string $archiveName The timestamped name of an archived image
1518 * @param bool|string $suffix If not false, the name of a thumbnail file
1521 function getArchiveThumbRel( $archiveName, $suffix = false ) {
1522 $path = 'archive/' . $this->getHashPath() . $archiveName . "/";
1523 if ( $suffix === false ) {
1524 $path = substr( $path, 0, -1 );
1533 * Get the path of the archived file.
1535 * @param bool|string $suffix If not false, the name of an archived file.
1538 function getArchivePath( $suffix = false ) {
1539 $this->assertRepoDefined();
1541 return $this->repo
->getZonePath( 'public' ) . '/' . $this->getArchiveRel( $suffix );
1545 * Get the path of an archived file's thumbs, or a particular thumb if $suffix is specified
1547 * @param string $archiveName The timestamped name of an archived image
1548 * @param bool|string $suffix If not false, the name of a thumbnail file
1551 function getArchiveThumbPath( $archiveName, $suffix = false ) {
1552 $this->assertRepoDefined();
1554 return $this->repo
->getZonePath( 'thumb' ) . '/' .
1555 $this->getArchiveThumbRel( $archiveName, $suffix );
1559 * Get the path of the thumbnail directory, or a particular file if $suffix is specified
1561 * @param bool|string $suffix If not false, the name of a thumbnail file
1564 function getThumbPath( $suffix = false ) {
1565 $this->assertRepoDefined();
1567 return $this->repo
->getZonePath( 'thumb' ) . '/' . $this->getThumbRel( $suffix );
1571 * Get the path of the transcoded directory, or a particular file if $suffix is specified
1573 * @param bool|string $suffix If not false, the name of a media file
1576 function getTranscodedPath( $suffix = false ) {
1577 $this->assertRepoDefined();
1579 return $this->repo
->getZonePath( 'transcoded' ) . '/' . $this->getThumbRel( $suffix );
1583 * Get the URL of the archive directory, or a particular file if $suffix is specified
1585 * @param bool|string $suffix If not false, the name of an archived file
1588 function getArchiveUrl( $suffix = false ) {
1589 $this->assertRepoDefined();
1590 $ext = $this->getExtension();
1591 $path = $this->repo
->getZoneUrl( 'public', $ext ) . '/archive/' . $this->getHashPath();
1592 if ( $suffix === false ) {
1593 $path = substr( $path, 0, -1 );
1595 $path .= rawurlencode( $suffix );
1602 * Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified
1604 * @param string $archiveName The timestamped name of an archived image
1605 * @param bool|string $suffix If not false, the name of a thumbnail file
1608 function getArchiveThumbUrl( $archiveName, $suffix = false ) {
1609 $this->assertRepoDefined();
1610 $ext = $this->getExtension();
1611 $path = $this->repo
->getZoneUrl( 'thumb', $ext ) . '/archive/' .
1612 $this->getHashPath() . rawurlencode( $archiveName ) . "/";
1613 if ( $suffix === false ) {
1614 $path = substr( $path, 0, -1 );
1616 $path .= rawurlencode( $suffix );
1623 * Get the URL of the zone directory, or a particular file if $suffix is specified
1625 * @param string $zone Name of requested zone
1626 * @param bool|string $suffix If not false, the name of a file in zone
1627 * @return string Path
1629 function getZoneUrl( $zone, $suffix = false ) {
1630 $this->assertRepoDefined();
1631 $ext = $this->getExtension();
1632 $path = $this->repo
->getZoneUrl( $zone, $ext ) . '/' . $this->getUrlRel();
1633 if ( $suffix !== false ) {
1634 $path .= '/' . rawurlencode( $suffix );
1641 * Get the URL of the thumbnail directory, or a particular file if $suffix is specified
1643 * @param bool|string $suffix If not false, the name of a thumbnail file
1644 * @return string Path
1646 function getThumbUrl( $suffix = false ) {
1647 return $this->getZoneUrl( 'thumb', $suffix );
1651 * Get the URL of the transcoded directory, or a particular file if $suffix is specified
1653 * @param bool|string $suffix If not false, the name of a media file
1654 * @return string Path
1656 function getTranscodedUrl( $suffix = false ) {
1657 return $this->getZoneUrl( 'transcoded', $suffix );
1661 * Get the public zone virtual URL for a current version source file
1663 * @param bool|string $suffix If not false, the name of a thumbnail file
1666 function getVirtualUrl( $suffix = false ) {
1667 $this->assertRepoDefined();
1668 $path = $this->repo
->getVirtualUrl() . '/public/' . $this->getUrlRel();
1669 if ( $suffix !== false ) {
1670 $path .= '/' . rawurlencode( $suffix );
1677 * Get the public zone virtual URL for an archived version source file
1679 * @param bool|string $suffix If not false, the name of a thumbnail file
1682 function getArchiveVirtualUrl( $suffix = false ) {
1683 $this->assertRepoDefined();
1684 $path = $this->repo
->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
1685 if ( $suffix === false ) {
1686 $path = substr( $path, 0, -1 );
1688 $path .= rawurlencode( $suffix );
1695 * Get the virtual URL for a thumbnail file or directory
1697 * @param bool|string $suffix If not false, the name of a thumbnail file
1700 function getThumbVirtualUrl( $suffix = false ) {
1701 $this->assertRepoDefined();
1702 $path = $this->repo
->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
1703 if ( $suffix !== false ) {
1704 $path .= '/' . rawurlencode( $suffix );
1713 function isHashed() {
1714 $this->assertRepoDefined();
1716 return (bool)$this->repo
->getHashLevels();
1720 * @throws MWException
1722 function readOnlyError() {
1723 throw new MWException( get_class( $this ) . ': write operations are not supported' );
1727 * Record a file upload in the upload log and the image table
1729 * Overridden by LocalFile
1730 * @param string $oldver
1731 * @param string $desc
1732 * @param string $license
1733 * @param string $copyStatus
1734 * @param string $source
1735 * @param bool $watch
1736 * @param string|bool $timestamp
1737 * @param null|User $user User object or null to use $wgUser
1739 * @throws MWException
1741 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1742 $watch = false, $timestamp = false, User
$user = null
1744 $this->readOnlyError();
1748 * Move or copy a file to its public location. If a file exists at the
1749 * destination, move it to an archive. Returns a FileRepoStatus object with
1750 * the archive name in the "value" member on success.
1752 * The archive name should be passed through to recordUpload for database
1755 * Options to $options include:
1756 * - headers : name/value map of HTTP headers to use in response to GET/HEAD requests
1758 * @param string $srcPath Local filesystem path to the source image
1759 * @param int $flags A bitwise combination of:
1760 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1761 * @param array $options Optional additional parameters
1762 * @return FileRepoStatus On success, the value member contains the
1763 * archive name, or an empty string if it was a new file.
1766 * Overridden by LocalFile
1768 function publish( $srcPath, $flags = 0, array $options = array() ) {
1769 $this->readOnlyError();
1775 function formatMetadata() {
1776 if ( !$this->getHandler() ) {
1780 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
1784 * Returns true if the file comes from the local file repository.
1788 function isLocal() {
1789 return $this->repo
&& $this->repo
->isLocal();
1793 * Returns the name of the repository.
1797 function getRepoName() {
1798 return $this->repo ?
$this->repo
->getName() : 'unknown';
1802 * Returns the repository
1804 * @return FileRepo|LocalRepo|bool
1806 function getRepo() {
1811 * Returns true if the image is an old version
1821 * Is this file a "deleted" file in a private archive?
1824 * @param int $field One of DELETED_* bitfield constants
1827 function isDeleted( $field ) {
1832 * Return the deletion bitfield
1836 function getVisibility() {
1841 * Was this file ever deleted from the wiki?
1845 function wasDeleted() {
1846 $title = $this->getTitle();
1848 return $title && $title->isDeletedQuick();
1852 * Move file to the new title
1854 * Move current, old version and all thumbnails
1855 * to the new filename. Old file is deleted.
1857 * Cache purging is done; checks for validity
1858 * and logging are caller's responsibility
1860 * @param Title $target New file name
1861 * @return FileRepoStatus
1863 function move( $target ) {
1864 $this->readOnlyError();
1868 * Delete all versions of the file.
1870 * Moves the files into an archive directory (or deletes them)
1871 * and removes the database rows.
1873 * Cache purging is done; logging is caller's responsibility.
1875 * @param string $reason
1876 * @param bool $suppress Hide content from sysops?
1877 * @param User|null $user
1878 * @return bool Boolean on success, false on some kind of failure
1880 * Overridden by LocalFile
1882 function delete( $reason, $suppress = false, $user = null ) {
1883 $this->readOnlyError();
1887 * Restore all or specified deleted revisions to the given file.
1888 * Permissions and logging are left to the caller.
1890 * May throw database exceptions on error.
1892 * @param array $versions Set of record ids of deleted items to restore,
1893 * or empty to restore all revisions.
1894 * @param bool $unsuppress Remove restrictions on content upon restoration?
1895 * @return int|bool The number of file revisions restored if successful,
1896 * or false on failure
1898 * Overridden by LocalFile
1900 function restore( $versions = array(), $unsuppress = false ) {
1901 $this->readOnlyError();
1905 * Returns 'true' if this file is a type which supports multiple pages,
1906 * e.g. DJVU or PDF. Note that this may be true even if the file in
1907 * question only has a single page.
1911 function isMultipage() {
1912 return $this->getHandler() && $this->handler
->isMultiPage( $this );
1916 * Returns the number of pages of a multipage document, or false for
1917 * documents which aren't multipage documents
1921 function pageCount() {
1922 if ( !isset( $this->pageCount
) ) {
1923 if ( $this->getHandler() && $this->handler
->isMultiPage( $this ) ) {
1924 $this->pageCount
= $this->handler
->pageCount( $this );
1926 $this->pageCount
= false;
1930 return $this->pageCount
;
1934 * Calculate the height of a thumbnail using the source and destination width
1936 * @param int $srcWidth
1937 * @param int $srcHeight
1938 * @param int $dstWidth
1942 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1943 // Exact integer multiply followed by division
1944 if ( $srcWidth == 0 ) {
1947 return round( $srcHeight * $dstWidth / $srcWidth );
1952 * Get an image size array like that returned by getImageSize(), or false if it
1953 * can't be determined. Loads the image size directly from the file ignoring caches.
1955 * @note Use getWidth()/getHeight() instead of this method unless you have a
1956 * a good reason. This method skips all caches.
1958 * @param string $filePath The path to the file (e.g. From getLocalPathRef() )
1959 * @return array The width, followed by height, with optionally more things after
1961 function getImageSize( $filePath ) {
1962 if ( !$this->getHandler() ) {
1966 return $this->getHandler()->getImageSize( $this, $filePath );
1970 * Get the URL of the image description page. May return false if it is
1971 * unknown or not applicable.
1975 function getDescriptionUrl() {
1976 if ( $this->repo
) {
1977 return $this->repo
->getDescriptionUrl( $this->getName() );
1984 * Get the HTML text of the description page, if available
1986 * @param bool|Language $lang Optional language to fetch description in
1989 function getDescriptionText( $lang = false ) {
1990 global $wgMemc, $wgLang;
1991 if ( !$this->repo ||
!$this->repo
->fetchDescription
) {
1997 $renderUrl = $this->repo
->getDescriptionRenderUrl( $this->getName(), $lang->getCode() );
1999 if ( $this->repo
->descriptionCacheExpiry
> 0 ) {
2000 wfDebug( "Attempting to get the description from cache..." );
2001 $key = $this->repo
->getLocalCacheKey(
2002 'RemoteFileDescription',
2007 $obj = $wgMemc->get( $key );
2009 wfDebug( "success!\n" );
2013 wfDebug( "miss\n" );
2015 wfDebug( "Fetching shared description from $renderUrl\n" );
2016 $res = Http
::get( $renderUrl );
2017 if ( $res && $this->repo
->descriptionCacheExpiry
> 0 ) {
2018 $wgMemc->set( $key, $res, $this->repo
->descriptionCacheExpiry
);
2028 * Get description of file revision
2031 * @param int $audience One of:
2032 * File::FOR_PUBLIC to be displayed to all users
2033 * File::FOR_THIS_USER to be displayed to the given user
2034 * File::RAW get the description regardless of permissions
2035 * @param User $user User object to check for, only if FOR_THIS_USER is
2036 * passed to the $audience parameter
2039 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
2044 * Get the 14-character timestamp of the file upload
2046 * @return string|bool TS_MW timestamp or false on failure
2048 function getTimestamp() {
2049 $this->assertRepoDefined();
2051 return $this->repo
->getFileTimestamp( $this->getPath() );
2055 * Get the SHA-1 base 36 hash of the file
2059 function getSha1() {
2060 $this->assertRepoDefined();
2062 return $this->repo
->getFileSha1( $this->getPath() );
2066 * Get the deletion archive key, "<sha1>.<ext>"
2070 function getStorageKey() {
2071 $hash = $this->getSha1();
2075 $ext = $this->getExtension();
2076 $dotExt = $ext === '' ?
'' : ".$ext";
2078 return $hash . $dotExt;
2082 * Determine if the current user is allowed to view a particular
2083 * field of this file, if it's marked as deleted.
2086 * @param User $user User object to check, or null to use $wgUser
2089 function userCan( $field, User
$user = null ) {
2094 * @return array HTTP header name/value map to use for HEAD/GET request responses
2096 function getStreamHeaders() {
2097 $handler = $this->getHandler();
2099 return $handler->getStreamHeaders( $this->getMetadata() );
2108 function getLongDesc() {
2109 $handler = $this->getHandler();
2111 return $handler->getLongDesc( $this );
2113 return MediaHandler
::getGeneralLongDesc( $this );
2120 function getShortDesc() {
2121 $handler = $this->getHandler();
2123 return $handler->getShortDesc( $this );
2125 return MediaHandler
::getGeneralShortDesc( $this );
2132 function getDimensionsString() {
2133 $handler = $this->getHandler();
2135 return $handler->getDimensionsString( $this );
2144 function getRedirected() {
2145 return $this->redirected
;
2149 * @return Title|null
2151 function getRedirectedTitle() {
2152 if ( $this->redirected
) {
2153 if ( !$this->redirectTitle
) {
2154 $this->redirectTitle
= Title
::makeTitle( NS_FILE
, $this->redirected
);
2157 return $this->redirectTitle
;
2164 * @param string $from
2167 function redirectedFrom( $from ) {
2168 $this->redirected
= $from;
2174 function isMissing() {
2179 * Check if this file object is small and can be cached
2182 public function isCacheable() {
2187 * Assert that $this->repo is set to a valid FileRepo instance
2188 * @throws MWException
2190 protected function assertRepoDefined() {
2191 if ( !( $this->repo
instanceof $this->repoClass
) ) {
2192 throw new MWException( "A {$this->repoClass} object is not set for this File.\n" );
2197 * Assert that $this->title is set to a Title
2198 * @throws MWException
2200 protected function assertTitleDefined() {
2201 if ( !( $this->title
instanceof Title
) ) {
2202 throw new MWException( "A Title object is not set for this File.\n" );
2207 * True if creating thumbnails from the file is large or otherwise resource-intensive.
2210 public function isExpensiveToThumbnail() {
2211 $handler = $this->getHandler();
2212 return $handler ?
$handler->isExpensiveToThumbnail( $this ) : false;