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 Wether the output of transform() for this file is likely to be valid. */
142 protected $canRender;
144 /** @var bool Wether 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';
153 * Call this constructor from child classes.
155 * Both $title and $repo are optional, though some functions
156 * may return false or throw exceptions if they are not set.
157 * Most subclasses will want to call assertRepoDefined() here.
159 * @param Title|string|bool $title
160 * @param FileRepo|bool $repo
162 function __construct( $title, $repo ) {
163 if ( $title !== false ) { // subclasses may not use MW titles
164 $title = self
::normalizeTitle( $title, 'exception' );
166 $this->title
= $title;
171 * Given a string or Title object return either a
172 * valid Title object with namespace NS_FILE or null
174 * @param Title|string $title
175 * @param string|bool $exception Use 'exception' to throw an error on bad titles
176 * @throws MWException
179 static function normalizeTitle( $title, $exception = false ) {
181 if ( $ret instanceof Title
) {
182 # Normalize NS_MEDIA -> NS_FILE
183 if ( $ret->getNamespace() == NS_MEDIA
) {
184 $ret = Title
::makeTitleSafe( NS_FILE
, $ret->getDBkey() );
185 # Sanity check the title namespace
186 } elseif ( $ret->getNamespace() !== NS_FILE
) {
190 # Convert strings to Title objects
191 $ret = Title
::makeTitleSafe( NS_FILE
, (string)$ret );
193 if ( !$ret && $exception !== false ) {
194 throw new MWException( "`$title` is not a valid file title." );
200 function __get( $name ) {
201 $function = array( $this, 'get' . ucfirst( $name ) );
202 if ( !is_callable( $function ) ) {
205 $this->$name = call_user_func( $function );
212 * Normalize a file extension to the common form, and ensure it's clean.
213 * Extensions with non-alphanumeric characters will be discarded.
215 * @param string $ext (without the .)
218 static function normalizeExtension( $ext ) {
219 $lower = strtolower( $ext );
226 if ( isset( $squish[$lower] ) ) {
227 return $squish[$lower];
228 } elseif ( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
236 * Checks if file extensions are compatible
238 * @param File $old Old file
239 * @param string $new New name
243 static function checkExtensionCompatibility( File
$old, $new ) {
244 $oldMime = $old->getMimeType();
245 $n = strrpos( $new, '.' );
246 $newExt = self
::normalizeExtension( $n ?
substr( $new, $n +
1 ) : '' );
247 $mimeMagic = MimeMagic
::singleton();
249 return $mimeMagic->isMatchingExtension( $newExt, $oldMime );
253 * Upgrade the database row if there is one
254 * Called by ImagePage
257 function upgradeRow() {
261 * Split an internet media type into its two components; if not
262 * a two-part name, set the minor type to 'unknown'.
264 * @param string $mime "text/html" etc
265 * @return array ("text", "html") etc
267 public static function splitMime( $mime ) {
268 if ( strpos( $mime, '/' ) !== false ) {
269 return explode( '/', $mime, 2 );
271 return array( $mime, 'unknown' );
276 * Callback for usort() to do file sorts by name
280 * @return int Result of name comparison
282 public static function compare( File
$a, File
$b ) {
283 return strcmp( $a->getName(), $b->getName() );
287 * Return the name of this file
291 public function getName() {
292 if ( !isset( $this->name
) ) {
293 $this->assertRepoDefined();
294 $this->name
= $this->repo
->getNameFromTitle( $this->title
);
301 * Get the file extension, e.g. "svg"
305 function getExtension() {
306 if ( !isset( $this->extension
) ) {
307 $n = strrpos( $this->getName(), '.' );
308 $this->extension
= self
::normalizeExtension(
309 $n ?
substr( $this->getName(), $n +
1 ) : '' );
312 return $this->extension
;
316 * Return the associated title object
320 public function getTitle() {
325 * Return the title used to find this file
329 public function getOriginalTitle() {
330 if ( $this->redirected
) {
331 return $this->getRedirectedTitle();
338 * Return the URL of the file
342 public function getUrl() {
343 if ( !isset( $this->url
) ) {
344 $this->assertRepoDefined();
345 $ext = $this->getExtension();
346 $this->url
= $this->repo
->getZoneUrl( 'public', $ext ) . '/' . $this->getUrlRel();
353 * Return a fully-qualified URL to the file.
354 * Upload URL paths _may or may not_ be fully qualified, so
355 * we check. Local paths are assumed to belong on $wgServer.
359 public function getFullUrl() {
360 return wfExpandUrl( $this->getUrl(), PROTO_RELATIVE
);
366 public function getCanonicalUrl() {
367 return wfExpandUrl( $this->getUrl(), PROTO_CANONICAL
);
373 function getViewURL() {
374 if ( $this->mustRender() ) {
375 if ( $this->canRender() ) {
376 return $this->createThumb( $this->getWidth() );
378 wfDebug( __METHOD__
. ': supposed to render ' . $this->getName() .
379 ' (' . $this->getMimeType() . "), but can't!\n" );
381 return $this->getURL(); #hm... return NULL?
384 return $this->getURL();
389 * Return the storage path to the file. Note that this does
390 * not mean that a file actually exists under that location.
392 * This path depends on whether directory hashing is active or not,
393 * i.e. whether the files are all found in the same directory,
394 * or in hashed paths like /images/3/3c.
396 * Most callers don't check the return value, but ForeignAPIFile::getPath
399 * @return string|bool ForeignAPIFile::getPath can return false
401 public function getPath() {
402 if ( !isset( $this->path
) ) {
403 $this->assertRepoDefined();
404 $this->path
= $this->repo
->getZonePath( 'public' ) . '/' . $this->getRel();
411 * Get an FS copy or original of this file and return the path.
412 * Returns false on failure. Callers must not alter the file.
413 * Temporary files are cleared automatically.
415 * @return string|bool False on failure
417 public function getLocalRefPath() {
418 $this->assertRepoDefined();
419 if ( !isset( $this->fsFile
) ) {
420 $this->fsFile
= $this->repo
->getLocalReference( $this->getPath() );
421 if ( !$this->fsFile
) {
422 $this->fsFile
= false; // null => false; cache negative hits
426 return ( $this->fsFile
)
427 ?
$this->fsFile
->getPath()
432 * Return the width of the image. Returns false if the width is unknown
436 * Overridden by LocalFile, UnregisteredLocalFile
441 public function getWidth( $page = 1 ) {
446 * Return the height of the image. Returns false if the height is unknown
450 * Overridden by LocalFile, UnregisteredLocalFile
453 * @return bool|int False on failure
455 public function getHeight( $page = 1 ) {
460 * Returns ID or name of user who uploaded the file
463 * @param string $type 'text' or 'id'
466 public function getUser( $type = 'text' ) {
471 * Get the duration of a media file in seconds
475 public function getLength() {
476 $handler = $this->getHandler();
478 return $handler->getLength( $this );
485 * Return true if the file is vectorized
489 public function isVectorized() {
490 $handler = $this->getHandler();
492 return $handler->isVectorized( $this );
499 * Gives a (possibly empty) list of languages to render
502 * If the file doesn't have translations, or if the file
503 * format does not support that sort of thing, returns
509 public function getAvailableLanguages() {
510 $handler = $this->getHandler();
512 return $handler->getAvailableLanguages( $this );
519 * In files that support multiple language, what is the default language
520 * to use if none specified.
522 * @return string Lang code, or null if filetype doesn't support multiple languages.
525 public function getDefaultRenderLanguage() {
526 $handler = $this->getHandler();
528 return $handler->getDefaultRenderLanguage( $this );
535 * Will the thumbnail be animated if one would expect it to be.
537 * Currently used to add a warning to the image description page
539 * @return bool false if the main image is both animated
540 * and the thumbnail is not. In all other cases must return
541 * true. If image is not renderable whatsoever, should
544 public function canAnimateThumbIfAppropriate() {
545 $handler = $this->getHandler();
547 // We cannot handle image whatsoever, thus
548 // one would not expect it to be animated
552 if ( $this->allowInlineDisplay()
553 && $handler->isAnimatedImage( $this )
554 && !$handler->canAnimateThumbnail( $this )
556 // Image is animated, but thumbnail isn't.
557 // This is unexpected to the user.
560 // Image is not animated, so one would
561 // not expect thumb to be
568 * Get handler-specific metadata
569 * Overridden by LocalFile, UnregisteredLocalFile
573 public function getMetadata() {
578 * Like getMetadata but returns a handler independent array of common values.
579 * @see MediaHandler::getCommonMetaArray()
580 * @return array|bool Array or false if not supported
583 public function getCommonMetaArray() {
584 $handler = $this->getHandler();
590 return $handler->getCommonMetaArray( $this );
594 * get versioned metadata
596 * @param array|string $metadata Array or string of (serialized) metadata
597 * @param int $version Version number.
598 * @return array Array containing metadata, or what was passed to it on fail
599 * (unserializing if not array)
601 public function convertMetadataVersion( $metadata, $version ) {
602 $handler = $this->getHandler();
603 if ( !is_array( $metadata ) ) {
604 // Just to make the return type consistent
605 $metadata = unserialize( $metadata );
608 return $handler->convertMetadataVersion( $metadata, $version );
615 * Return the bit depth of the file
616 * Overridden by LocalFile
620 public function getBitDepth() {
625 * Return the size of the image file, in bytes
626 * Overridden by LocalFile, UnregisteredLocalFile
630 public function getSize() {
635 * Returns the mime type of the file.
636 * Overridden by LocalFile, UnregisteredLocalFile
641 function getMimeType() {
642 return 'unknown/unknown';
646 * Return the type of the media in the file.
647 * Use the value returned by this function with the MEDIATYPE_xxx constants.
648 * Overridden by LocalFile,
652 function getMediaType() {
653 return MEDIATYPE_UNKNOWN
;
657 * Checks if the output of transform() for this file is likely
658 * to be valid. If this is false, various user elements will
659 * display a placeholder instead.
661 * Currently, this checks if the file is an image format
662 * that can be converted to a format
663 * supported by all browsers (namely GIF, PNG and JPEG),
664 * or if it is an SVG image and SVG conversion is enabled.
668 function canRender() {
669 if ( !isset( $this->canRender
) ) {
670 $this->canRender
= $this->getHandler() && $this->handler
->canRender( $this );
673 return $this->canRender
;
677 * Accessor for __get()
680 protected function getCanRender() {
681 return $this->canRender();
685 * Return true if the file is of a type that can't be directly
686 * rendered by typical browsers and needs to be re-rasterized.
688 * This returns true for everything but the bitmap types
689 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
690 * also return true for any non-image formats.
694 function mustRender() {
695 return $this->getHandler() && $this->handler
->mustRender( $this );
699 * Alias for canRender()
703 function allowInlineDisplay() {
704 return $this->canRender();
708 * Determines if this media file is in a format that is unlikely to
709 * contain viruses or malicious content. It uses the global
710 * $wgTrustedMediaFormats list to determine if the file is safe.
712 * This is used to show a warning on the description page of non-safe files.
713 * It may also be used to disallow direct [[media:...]] links to such files.
715 * Note that this function will always return true if allowInlineDisplay()
716 * or isTrustedFile() is true for this file.
720 function isSafeFile() {
721 if ( !isset( $this->isSafeFile
) ) {
722 $this->isSafeFile
= $this->getIsSafeFileUncached();
725 return $this->isSafeFile
;
729 * Accessor for __get()
733 protected function getIsSafeFile() {
734 return $this->isSafeFile();
742 protected function getIsSafeFileUncached() {
743 global $wgTrustedMediaFormats;
745 if ( $this->allowInlineDisplay() ) {
748 if ( $this->isTrustedFile() ) {
752 $type = $this->getMediaType();
753 $mime = $this->getMimeType();
754 #wfDebug( "LocalFile::isSafeFile: type= $type, mime= $mime\n" );
756 if ( !$type ||
$type === MEDIATYPE_UNKNOWN
) {
757 return false; #unknown type, not trusted
759 if ( in_array( $type, $wgTrustedMediaFormats ) ) {
763 if ( $mime === "unknown/unknown" ) {
764 return false; #unknown type, not trusted
766 if ( in_array( $mime, $wgTrustedMediaFormats ) ) {
774 * Returns true if the file is flagged as trusted. Files flagged that way
775 * can be linked to directly, even if that is not allowed for this type of
778 * This is a dummy function right now and always returns false. It could be
779 * implemented to extract a flag from the database. The trusted flag could be
780 * set on upload, if the user has sufficient privileges, to bypass script-
781 * and html-filters. It may even be coupled with cryptographics signatures
786 function isTrustedFile() {
787 #this could be implemented to check a flag in the database,
788 #look for signatures, etc
793 * Returns true if file exists in the repository.
795 * Overridden by LocalFile to avoid unnecessary stat calls.
797 * @return bool Whether file exists in the repository.
799 public function exists() {
800 return $this->getPath() && $this->repo
->fileExists( $this->path
);
804 * Returns true if file exists in the repository and can be included in a page.
805 * It would be unsafe to include private images, making public thumbnails inadvertently
807 * @return bool Whether file exists in the repository and is includable.
809 public function isVisible() {
810 return $this->exists();
816 function getTransformScript() {
817 if ( !isset( $this->transformScript
) ) {
818 $this->transformScript
= false;
820 $script = $this->repo
->getThumbScriptUrl();
822 $this->transformScript
= wfAppendQuery( $script, array( 'f' => $this->getName() ) );
827 return $this->transformScript
;
831 * Get a ThumbnailImage which is the same size as the source
833 * @param array $handlerParams
837 function getUnscaledThumb( $handlerParams = array() ) {
838 $hp =& $handlerParams;
839 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
840 $width = $this->getWidth( $page );
842 return $this->iconThumb();
844 $hp['width'] = $width;
845 // be sure to ignore any height specification as well (bug 62258)
846 unset( $hp['height'] );
848 return $this->transform( $hp );
852 * Return the file name of a thumbnail with the specified parameters.
853 * Use File::THUMB_FULL_NAME to always get a name like "<params>-<source>".
854 * Otherwise, the format may be "<params>-<source>" or "<params>-thumbnail.<ext>".
856 * @param array $params Handler-specific parameters
857 * @param int $flags Bitfield that supports THUMB_* constants
860 public function thumbName( $params, $flags = 0 ) {
861 $name = ( $this->repo
&& !( $flags & self
::THUMB_FULL_NAME
) )
862 ?
$this->repo
->nameForThumb( $this->getName() )
865 return $this->generateThumbName( $name, $params );
869 * Generate a thumbnail file name from a name and specified parameters
871 * @param string $name
872 * @param array $params Parameters which will be passed to MediaHandler::makeParamString
875 public function generateThumbName( $name, $params ) {
876 if ( !$this->getHandler() ) {
879 $extension = $this->getExtension();
880 list( $thumbExt, ) = $this->handler
->getThumbType(
881 $extension, $this->getMimeType(), $params );
882 $thumbName = $this->handler
->makeParamString( $params ) . '-' . $name;
883 if ( $thumbExt != $extension ) {
884 $thumbName .= ".$thumbExt";
891 * Create a thumbnail of the image having the specified width/height.
892 * The thumbnail will not be created if the width is larger than the
893 * image's width. Let the browser do the scaling in this case.
894 * The thumbnail is stored on disk and is only computed if the thumbnail
895 * file does not exist OR if it is older than the image.
898 * Keeps aspect ratio of original image. If both width and height are
899 * specified, the generated image will be no bigger than width x height,
900 * and will also have correct aspect ratio.
902 * @param int $width Maximum width of the generated thumbnail
903 * @param int $height Maximum height of the image (optional)
907 public function createThumb( $width, $height = -1 ) {
908 $params = array( 'width' => $width );
909 if ( $height != -1 ) {
910 $params['height'] = $height;
912 $thumb = $this->transform( $params );
913 if ( !$thumb ||
$thumb->isError() ) {
917 return $thumb->getUrl();
921 * Return either a MediaTransformError or placeholder thumbnail (if $wgIgnoreImageErrors)
923 * @param string $thumbPath Thumbnail storage path
924 * @param string $thumbUrl Thumbnail URL
925 * @param array $params
927 * @return MediaTransformOutput
929 protected function transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags ) {
930 global $wgIgnoreImageErrors;
932 $handler = $this->getHandler();
933 if ( $handler && $wgIgnoreImageErrors && !( $flags & self
::RENDER_NOW
) ) {
934 return $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
936 return new MediaTransformError( 'thumbnail_error',
937 $params['width'], 0, wfMessage( 'thumbnail-dest-create' )->text() );
942 * Transform a media file
944 * @param array $params An associative array of handler-specific parameters.
945 * Typical keys are width, height and page.
946 * @param int $flags A bitfield, may contain self::RENDER_NOW to force rendering
947 * @return MediaTransformOutput|bool False on failure
949 function transform( $params, $flags = 0 ) {
950 global $wgUseSquid, $wgIgnoreImageErrors, $wgThumbnailEpoch;
952 wfProfileIn( __METHOD__
);
954 if ( !$this->canRender() ) {
955 $thumb = $this->iconThumb();
956 break; // not a bitmap or renderable image, don't try
959 // Get the descriptionUrl to embed it as comment into the thumbnail. Bug 19791.
960 $descriptionUrl = $this->getDescriptionUrl();
961 if ( $descriptionUrl ) {
962 $params['descriptionUrl'] = wfExpandUrl( $descriptionUrl, PROTO_CANONICAL
);
965 $handler = $this->getHandler();
966 $script = $this->getTransformScript();
967 if ( $script && !( $flags & self
::RENDER_NOW
) ) {
968 // Use a script to transform on client request, if possible
969 $thumb = $handler->getScriptedTransform( $this, $script, $params );
975 $normalisedParams = $params;
976 $handler->normaliseParams( $this, $normalisedParams );
978 $thumbName = $this->thumbName( $normalisedParams );
979 $thumbUrl = $this->getThumbUrl( $thumbName );
980 $thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
983 // Defer rendering if a 404 handler is set up...
984 if ( $this->repo
->canTransformVia404() && !( $flags & self
::RENDER_NOW
) ) {
985 wfDebug( __METHOD__
. " transformation deferred.\n" );
986 // XXX: Pass in the storage path even though we are not rendering anything
987 // and the path is supposed to be an FS path. This is due to getScalerType()
988 // getting called on the path and clobbering $thumb->getUrl() if it's false.
989 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
992 // Clean up broken thumbnails as needed
993 $this->migrateThumbFile( $thumbName );
994 // Check if an up-to-date thumbnail already exists...
995 wfDebug( __METHOD__
. ": Doing stat for $thumbPath\n" );
996 if ( !( $flags & self
::RENDER_FORCE
) && $this->repo
->fileExists( $thumbPath ) ) {
997 $timestamp = $this->repo
->getFileTimestamp( $thumbPath );
998 if ( $timestamp !== false && $timestamp >= $wgThumbnailEpoch ) {
999 // XXX: Pass in the storage path even though we are not rendering anything
1000 // and the path is supposed to be an FS path. This is due to getScalerType()
1001 // getting called on the path and clobbering $thumb->getUrl() if it's false.
1002 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
1003 $thumb->setStoragePath( $thumbPath );
1006 } elseif ( $flags & self
::RENDER_FORCE
) {
1007 wfDebug( __METHOD__
. " forcing rendering per flag File::RENDER_FORCE\n" );
1011 // If the backend is ready-only, don't keep generating thumbnails
1012 // only to return transformation errors, just return the error now.
1013 if ( $this->repo
->getReadOnlyReason() !== false ) {
1014 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
1018 // Create a temp FS file with the same extension and the thumbnail
1019 $thumbExt = FileBackend
::extensionFromPath( $thumbPath );
1020 $tmpFile = TempFSFile
::factory( 'transform_', $thumbExt );
1022 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
1025 $tmpThumbPath = $tmpFile->getPath(); // path of 0-byte temp file
1027 // Actually render the thumbnail...
1028 wfProfileIn( __METHOD__
. '-doTransform' );
1029 $thumb = $handler->doTransform( $this, $tmpThumbPath, $thumbUrl, $params );
1030 wfProfileOut( __METHOD__
. '-doTransform' );
1031 $tmpFile->bind( $thumb ); // keep alive with $thumb
1033 if ( !$thumb ) { // bad params?
1035 } elseif ( $thumb->isError() ) { // transform error
1036 $this->lastError
= $thumb->toText();
1037 // Ignore errors if requested
1038 if ( $wgIgnoreImageErrors && !( $flags & self
::RENDER_NOW
) ) {
1039 $thumb = $handler->getTransform( $this, $tmpThumbPath, $thumbUrl, $params );
1041 } elseif ( $this->repo
&& $thumb->hasFile() && !$thumb->fileIsSource() ) {
1042 // Copy the thumbnail from the file system into storage...
1043 $disposition = $this->getThumbDisposition( $thumbName );
1044 $status = $this->repo
->quickImport( $tmpThumbPath, $thumbPath, $disposition );
1045 if ( $status->isOK() ) {
1046 $thumb->setStoragePath( $thumbPath );
1048 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
1050 // Give extensions a chance to do something with this thumbnail...
1051 wfRunHooks( 'FileTransformed', array( $this, $thumb, $tmpThumbPath, $thumbPath ) );
1054 // Purge. Useful in the event of Core -> Squid connection failure or squid
1055 // purge collisions from elsewhere during failure. Don't keep triggering for
1056 // "thumbs" which have the main image URL though (bug 13776)
1057 if ( $wgUseSquid ) {
1058 if ( !$thumb ||
$thumb->isError() ||
$thumb->getUrl() != $this->getURL() ) {
1059 SquidUpdate
::purge( array( $thumbUrl ) );
1064 wfProfileOut( __METHOD__
);
1066 return is_object( $thumb ) ?
$thumb : false;
1070 * @param string $thumbName Thumbnail name
1071 * @param string $dispositionType Type of disposition (either "attachment" or "inline")
1072 * @return string Content-Disposition header value
1074 function getThumbDisposition( $thumbName, $dispositionType = 'inline' ) {
1075 $fileName = $this->name
; // file name to suggest
1076 $thumbExt = FileBackend
::extensionFromPath( $thumbName );
1077 if ( $thumbExt != '' && $thumbExt !== $this->getExtension() ) {
1078 $fileName .= ".$thumbExt";
1081 return FileBackend
::makeContentDisposition( $dispositionType, $fileName );
1085 * Hook into transform() to allow migration of thumbnail files
1087 * Overridden by LocalFile
1089 function migrateThumbFile( $thumbName ) {
1093 * Get a MediaHandler instance for this file
1095 * @return MediaHandler|bool Registered MediaHandler for file's MIME type
1096 * or false if none found
1098 function getHandler() {
1099 if ( !isset( $this->handler
) ) {
1100 $this->handler
= MediaHandler
::getHandler( $this->getMimeType() );
1103 return $this->handler
;
1107 * Get a ThumbnailImage representing a file type icon
1109 * @return ThumbnailImage
1111 function iconThumb() {
1112 global $wgStylePath, $wgStyleDirectory;
1114 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
1115 foreach ( $try as $icon ) {
1116 $path = '/common/images/icons/' . $icon;
1117 $filepath = $wgStyleDirectory . $path;
1118 if ( file_exists( $filepath ) ) { // always FS
1119 $params = array( 'width' => 120, 'height' => 120 );
1121 return new ThumbnailImage( $this, $wgStylePath . $path, false, $params );
1129 * Get last thumbnailing error.
1132 function getLastError() {
1133 return $this->lastError
;
1137 * Get all thumbnail names previously generated for this file
1139 * Overridden by LocalFile
1142 function getThumbnails() {
1147 * Purge shared caches such as thumbnails and DB data caching
1149 * Overridden by LocalFile
1150 * @param array $options Options, which include:
1151 * 'forThumbRefresh' : The purging is only to refresh thumbnails
1153 function purgeCache( $options = array() ) {
1157 * Purge the file description page, but don't go after
1158 * pages using the file. Use when modifying file history
1159 * but not the current data.
1161 function purgeDescription() {
1162 $title = $this->getTitle();
1164 $title->invalidateCache();
1165 $title->purgeSquid();
1170 * Purge metadata and all affected pages when the file is created,
1171 * deleted, or majorly updated.
1173 function purgeEverything() {
1174 // Delete thumbnails and refresh file metadata cache
1175 $this->purgeCache();
1176 $this->purgeDescription();
1178 // Purge cache of all pages using this file
1179 $title = $this->getTitle();
1181 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
1182 $update->doUpdate();
1187 * Return a fragment of the history of file.
1190 * @param int $limit Limit of rows to return
1191 * @param string $start Only revisions older than $start will be returned
1192 * @param string $end Only revisions newer than $end will be returned
1193 * @param bool $inc Include the endpoints of the time range
1197 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1202 * Return the history of this file, line by line. Starts with current version,
1203 * then old versions. Should return an object similar to an image/oldimage
1207 * Overridden in LocalFile
1210 public function nextHistoryLine() {
1215 * Reset the history pointer to the first element of the history.
1216 * Always call this function after using nextHistoryLine() to free db resources
1218 * Overridden in LocalFile.
1220 public function resetHistory() {
1224 * Get the filename hash component of the directory including trailing slash,
1226 * If the repository is not hashed, returns an empty string.
1230 function getHashPath() {
1231 if ( !isset( $this->hashPath
) ) {
1232 $this->assertRepoDefined();
1233 $this->hashPath
= $this->repo
->getHashPath( $this->getName() );
1236 return $this->hashPath
;
1240 * Get the path of the file relative to the public zone root.
1241 * This function is overriden in OldLocalFile to be like getArchiveRel().
1246 return $this->getHashPath() . $this->getName();
1250 * Get the path of an archived file relative to the public zone root
1252 * @param bool|string $suffix If not false, the name of an archived thumbnail file
1256 function getArchiveRel( $suffix = false ) {
1257 $path = 'archive/' . $this->getHashPath();
1258 if ( $suffix === false ) {
1259 $path = substr( $path, 0, -1 );
1268 * Get the path, relative to the thumbnail zone root, of the
1269 * thumbnail directory or a particular file if $suffix is specified
1271 * @param bool|string $suffix If not false, the name of a thumbnail file
1274 function getThumbRel( $suffix = false ) {
1275 $path = $this->getRel();
1276 if ( $suffix !== false ) {
1277 $path .= '/' . $suffix;
1284 * Get urlencoded path of the file relative to the public zone root.
1285 * This function is overriden in OldLocalFile to be like getArchiveUrl().
1289 function getUrlRel() {
1290 return $this->getHashPath() . rawurlencode( $this->getName() );
1294 * Get the path, relative to the thumbnail zone root, for an archived file's thumbs directory
1295 * or a specific thumb if the $suffix is given.
1297 * @param string $archiveName The timestamped name of an archived image
1298 * @param bool|string $suffix If not false, the name of a thumbnail file
1301 function getArchiveThumbRel( $archiveName, $suffix = false ) {
1302 $path = 'archive/' . $this->getHashPath() . $archiveName . "/";
1303 if ( $suffix === false ) {
1304 $path = substr( $path, 0, -1 );
1313 * Get the path of the archived file.
1315 * @param bool|string $suffix If not false, the name of an archived file.
1318 function getArchivePath( $suffix = false ) {
1319 $this->assertRepoDefined();
1321 return $this->repo
->getZonePath( 'public' ) . '/' . $this->getArchiveRel( $suffix );
1325 * Get the path of an archived file's thumbs, or a particular thumb if $suffix is specified
1327 * @param string $archiveName The timestamped name of an archived image
1328 * @param bool|string $suffix If not false, the name of a thumbnail file
1331 function getArchiveThumbPath( $archiveName, $suffix = false ) {
1332 $this->assertRepoDefined();
1334 return $this->repo
->getZonePath( 'thumb' ) . '/' .
1335 $this->getArchiveThumbRel( $archiveName, $suffix );
1339 * Get the path of the thumbnail directory, or a particular file if $suffix is specified
1341 * @param bool|string $suffix If not false, the name of a thumbnail file
1344 function getThumbPath( $suffix = false ) {
1345 $this->assertRepoDefined();
1347 return $this->repo
->getZonePath( 'thumb' ) . '/' . $this->getThumbRel( $suffix );
1351 * Get the path of the transcoded directory, or a particular file if $suffix is specified
1353 * @param bool|string $suffix If not false, the name of a media file
1356 function getTranscodedPath( $suffix = false ) {
1357 $this->assertRepoDefined();
1359 return $this->repo
->getZonePath( 'transcoded' ) . '/' . $this->getThumbRel( $suffix );
1363 * Get the URL of the archive directory, or a particular file if $suffix is specified
1365 * @param bool|string $suffix If not false, the name of an archived file
1368 function getArchiveUrl( $suffix = false ) {
1369 $this->assertRepoDefined();
1370 $ext = $this->getExtension();
1371 $path = $this->repo
->getZoneUrl( 'public', $ext ) . '/archive/' . $this->getHashPath();
1372 if ( $suffix === false ) {
1373 $path = substr( $path, 0, -1 );
1375 $path .= rawurlencode( $suffix );
1382 * Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified
1384 * @param string $archiveName The timestamped name of an archived image
1385 * @param bool|string $suffix If not false, the name of a thumbnail file
1388 function getArchiveThumbUrl( $archiveName, $suffix = false ) {
1389 $this->assertRepoDefined();
1390 $ext = $this->getExtension();
1391 $path = $this->repo
->getZoneUrl( 'thumb', $ext ) . '/archive/' .
1392 $this->getHashPath() . rawurlencode( $archiveName ) . "/";
1393 if ( $suffix === false ) {
1394 $path = substr( $path, 0, -1 );
1396 $path .= rawurlencode( $suffix );
1403 * Get the URL of the zone directory, or a particular file if $suffix is specified
1405 * @param string $zone Name of requested zone
1406 * @param bool|string $suffix If not false, the name of a file in zone
1407 * @return string path
1409 function getZoneUrl( $zone, $suffix = false ) {
1410 $this->assertRepoDefined();
1411 $ext = $this->getExtension();
1412 $path = $this->repo
->getZoneUrl( $zone, $ext ) . '/' . $this->getUrlRel();
1413 if ( $suffix !== false ) {
1414 $path .= '/' . rawurlencode( $suffix );
1421 * Get the URL of the thumbnail directory, or a particular file if $suffix is specified
1423 * @param bool|string $suffix If not false, the name of a thumbnail file
1424 * @return string path
1426 function getThumbUrl( $suffix = false ) {
1427 return $this->getZoneUrl( 'thumb', $suffix );
1431 * Get the URL of the transcoded directory, or a particular file if $suffix is specified
1433 * @param bool|string $suffix If not false, the name of a media file
1434 * @return string path
1436 function getTranscodedUrl( $suffix = false ) {
1437 return $this->getZoneUrl( 'transcoded', $suffix );
1441 * Get the public zone virtual URL for a current version source file
1443 * @param bool|string $suffix If not false, the name of a thumbnail file
1446 function getVirtualUrl( $suffix = false ) {
1447 $this->assertRepoDefined();
1448 $path = $this->repo
->getVirtualUrl() . '/public/' . $this->getUrlRel();
1449 if ( $suffix !== false ) {
1450 $path .= '/' . rawurlencode( $suffix );
1457 * Get the public zone virtual URL for an archived version source file
1459 * @param bool|string $suffix If not false, the name of a thumbnail file
1462 function getArchiveVirtualUrl( $suffix = false ) {
1463 $this->assertRepoDefined();
1464 $path = $this->repo
->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
1465 if ( $suffix === false ) {
1466 $path = substr( $path, 0, -1 );
1468 $path .= rawurlencode( $suffix );
1475 * Get the virtual URL for a thumbnail file or directory
1477 * @param bool|string $suffix If not false, the name of a thumbnail file
1480 function getThumbVirtualUrl( $suffix = false ) {
1481 $this->assertRepoDefined();
1482 $path = $this->repo
->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
1483 if ( $suffix !== false ) {
1484 $path .= '/' . rawurlencode( $suffix );
1493 function isHashed() {
1494 $this->assertRepoDefined();
1496 return (bool)$this->repo
->getHashLevels();
1500 * @throws MWException
1502 function readOnlyError() {
1503 throw new MWException( get_class( $this ) . ': write operations are not supported' );
1507 * Record a file upload in the upload log and the image table
1509 * Overridden by LocalFile
1510 * @param string $oldver
1511 * @param string $desc
1512 * @param string $license
1513 * @param string $copyStatus
1514 * @param string $source
1515 * @param bool $watch
1516 * @param string|bool $timestamp
1517 * @param null|User $user User object or null to use $wgUser
1519 * @throws MWException
1521 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1522 $watch = false, $timestamp = false, User
$user = null
1524 $this->readOnlyError();
1528 * Move or copy a file to its public location. If a file exists at the
1529 * destination, move it to an archive. Returns a FileRepoStatus object with
1530 * the archive name in the "value" member on success.
1532 * The archive name should be passed through to recordUpload for database
1535 * Options to $options include:
1536 * - headers : name/value map of HTTP headers to use in response to GET/HEAD requests
1538 * @param string $srcPath Local filesystem path to the source image
1539 * @param int $flags A bitwise combination of:
1540 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1541 * @param array $options Optional additional parameters
1542 * @return FileRepoStatus object. On success, the value member contains the
1543 * archive name, or an empty string if it was a new file.
1546 * Overridden by LocalFile
1548 function publish( $srcPath, $flags = 0, array $options = array() ) {
1549 $this->readOnlyError();
1555 function formatMetadata() {
1556 if ( !$this->getHandler() ) {
1560 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
1564 * Returns true if the file comes from the local file repository.
1568 function isLocal() {
1569 return $this->repo
&& $this->repo
->isLocal();
1573 * Returns the name of the repository.
1577 function getRepoName() {
1578 return $this->repo ?
$this->repo
->getName() : 'unknown';
1582 * Returns the repository
1584 * @return FileRepo|LocalRepo|bool
1586 function getRepo() {
1591 * Returns true if the image is an old version
1601 * Is this file a "deleted" file in a private archive?
1604 * @param int $field One of DELETED_* bitfield constants
1607 function isDeleted( $field ) {
1612 * Return the deletion bitfield
1616 function getVisibility() {
1621 * Was this file ever deleted from the wiki?
1625 function wasDeleted() {
1626 $title = $this->getTitle();
1628 return $title && $title->isDeletedQuick();
1632 * Move file to the new title
1634 * Move current, old version and all thumbnails
1635 * to the new filename. Old file is deleted.
1637 * Cache purging is done; checks for validity
1638 * and logging are caller's responsibility
1640 * @param Title $target New file name
1641 * @return FileRepoStatus
1643 function move( $target ) {
1644 $this->readOnlyError();
1648 * Delete all versions of the file.
1650 * Moves the files into an archive directory (or deletes them)
1651 * and removes the database rows.
1653 * Cache purging is done; logging is caller's responsibility.
1655 * @param string $reason
1656 * @param bool $suppress Hide content from sysops?
1657 * @return bool Boolean on success, false on some kind of failure
1659 * Overridden by LocalFile
1661 function delete( $reason, $suppress = false ) {
1662 $this->readOnlyError();
1666 * Restore all or specified deleted revisions to the given file.
1667 * Permissions and logging are left to the caller.
1669 * May throw database exceptions on error.
1671 * @param array $versions Set of record ids of deleted items to restore,
1672 * or empty to restore all revisions.
1673 * @param bool $unsuppress Remove restrictions on content upon restoration?
1674 * @return int|bool The number of file revisions restored if successful,
1675 * or false on failure
1677 * Overridden by LocalFile
1679 function restore( $versions = array(), $unsuppress = false ) {
1680 $this->readOnlyError();
1684 * Returns 'true' if this file is a type which supports multiple pages,
1685 * e.g. DJVU or PDF. Note that this may be true even if the file in
1686 * question only has a single page.
1690 function isMultipage() {
1691 return $this->getHandler() && $this->handler
->isMultiPage( $this );
1695 * Returns the number of pages of a multipage document, or false for
1696 * documents which aren't multipage documents
1700 function pageCount() {
1701 if ( !isset( $this->pageCount
) ) {
1702 if ( $this->getHandler() && $this->handler
->isMultiPage( $this ) ) {
1703 $this->pageCount
= $this->handler
->pageCount( $this );
1705 $this->pageCount
= false;
1709 return $this->pageCount
;
1713 * Calculate the height of a thumbnail using the source and destination width
1715 * @param int $srcWidth
1716 * @param int $srcHeight
1717 * @param int $dstWidth
1721 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1722 // Exact integer multiply followed by division
1723 if ( $srcWidth == 0 ) {
1726 return round( $srcHeight * $dstWidth / $srcWidth );
1731 * Get an image size array like that returned by getImageSize(), or false if it
1732 * can't be determined.
1734 * @param string $fileName The filename
1737 function getImageSize( $fileName ) {
1738 if ( !$this->getHandler() ) {
1742 return $this->handler
->getImageSize( $this, $fileName );
1746 * Get the URL of the image description page. May return false if it is
1747 * unknown or not applicable.
1751 function getDescriptionUrl() {
1752 if ( $this->repo
) {
1753 return $this->repo
->getDescriptionUrl( $this->getName() );
1760 * Get the HTML text of the description page, if available
1762 * @param bool|Language $lang Optional language to fetch description in
1765 function getDescriptionText( $lang = false ) {
1766 global $wgMemc, $wgLang;
1767 if ( !$this->repo ||
!$this->repo
->fetchDescription
) {
1773 $renderUrl = $this->repo
->getDescriptionRenderUrl( $this->getName(), $lang->getCode() );
1775 if ( $this->repo
->descriptionCacheExpiry
> 0 ) {
1776 wfDebug( "Attempting to get the description from cache..." );
1777 $key = $this->repo
->getLocalCacheKey(
1778 'RemoteFileDescription',
1783 $obj = $wgMemc->get( $key );
1785 wfDebug( "success!\n" );
1789 wfDebug( "miss\n" );
1791 wfDebug( "Fetching shared description from $renderUrl\n" );
1792 $res = Http
::get( $renderUrl );
1793 if ( $res && $this->repo
->descriptionCacheExpiry
> 0 ) {
1794 $wgMemc->set( $key, $res, $this->repo
->descriptionCacheExpiry
);
1804 * Get description of file revision
1807 * @param int $audience One of:
1808 * File::FOR_PUBLIC to be displayed to all users
1809 * File::FOR_THIS_USER to be displayed to the given user
1810 * File::RAW get the description regardless of permissions
1811 * @param User $user User object to check for, only if FOR_THIS_USER is
1812 * passed to the $audience parameter
1815 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1820 * Get the 14-character timestamp of the file upload
1822 * @return string|bool TS_MW timestamp or false on failure
1824 function getTimestamp() {
1825 $this->assertRepoDefined();
1827 return $this->repo
->getFileTimestamp( $this->getPath() );
1831 * Get the SHA-1 base 36 hash of the file
1835 function getSha1() {
1836 $this->assertRepoDefined();
1838 return $this->repo
->getFileSha1( $this->getPath() );
1842 * Get the deletion archive key, "<sha1>.<ext>"
1846 function getStorageKey() {
1847 $hash = $this->getSha1();
1851 $ext = $this->getExtension();
1852 $dotExt = $ext === '' ?
'' : ".$ext";
1854 return $hash . $dotExt;
1858 * Determine if the current user is allowed to view a particular
1859 * field of this file, if it's marked as deleted.
1862 * @param User $user User object to check, or null to use $wgUser
1865 function userCan( $field, User
$user = null ) {
1870 * Get an associative array containing information about a file in the local filesystem.
1872 * @param string $path Absolute local filesystem path
1873 * @param string|bool $ext The file extension, or true to extract it from
1874 * the filename. Set it to false to ignore the extension.
1877 * @deprecated since 1.19
1879 static function getPropsFromPath( $path, $ext = true ) {
1880 wfDebug( __METHOD__
. ": Getting file info for $path\n" );
1881 wfDeprecated( __METHOD__
, '1.19' );
1883 $fsFile = new FSFile( $path );
1885 return $fsFile->getProps();
1889 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1890 * encoding, zero padded to 31 digits.
1892 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1895 * @param string $path
1896 * @return bool|string False on failure
1897 * @deprecated since 1.19
1899 static function sha1Base36( $path ) {
1900 wfDeprecated( __METHOD__
, '1.19' );
1902 $fsFile = new FSFile( $path );
1904 return $fsFile->getSha1Base36();
1908 * @return array HTTP header name/value map to use for HEAD/GET request responses
1910 function getStreamHeaders() {
1911 $handler = $this->getHandler();
1913 return $handler->getStreamHeaders( $this->getMetadata() );
1922 function getLongDesc() {
1923 $handler = $this->getHandler();
1925 return $handler->getLongDesc( $this );
1927 return MediaHandler
::getGeneralLongDesc( $this );
1934 function getShortDesc() {
1935 $handler = $this->getHandler();
1937 return $handler->getShortDesc( $this );
1939 return MediaHandler
::getGeneralShortDesc( $this );
1946 function getDimensionsString() {
1947 $handler = $this->getHandler();
1949 return $handler->getDimensionsString( $this );
1958 function getRedirected() {
1959 return $this->redirected
;
1963 * @return Title|null
1965 function getRedirectedTitle() {
1966 if ( $this->redirected
) {
1967 if ( !$this->redirectTitle
) {
1968 $this->redirectTitle
= Title
::makeTitle( NS_FILE
, $this->redirected
);
1971 return $this->redirectTitle
;
1978 * @param string $from
1981 function redirectedFrom( $from ) {
1982 $this->redirected
= $from;
1988 function isMissing() {
1993 * Check if this file object is small and can be cached
1996 public function isCacheable() {
2001 * Assert that $this->repo is set to a valid FileRepo instance
2002 * @throws MWException
2004 protected function assertRepoDefined() {
2005 if ( !( $this->repo
instanceof $this->repoClass
) ) {
2006 throw new MWException( "A {$this->repoClass} object is not set for this File.\n" );
2011 * Assert that $this->title is set to a Title
2012 * @throws MWException
2014 protected function assertTitleDefined() {
2015 if ( !( $this->title
instanceof Title
) ) {
2016 throw new MWException( "A Title object is not set for this File.\n" );