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();
589 return $handler->getCommonMetaArray( $this );
593 * get versioned metadata
595 * @param array|string $metadata Array or string of (serialized) metadata
596 * @param int $version Version number.
597 * @return array Array containing metadata, or what was passed to it on fail
598 * (unserializing if not array)
600 public function convertMetadataVersion( $metadata, $version ) {
601 $handler = $this->getHandler();
602 if ( !is_array( $metadata ) ) {
603 // Just to make the return type consistent
604 $metadata = unserialize( $metadata );
607 return $handler->convertMetadataVersion( $metadata, $version );
614 * Return the bit depth of the file
615 * Overridden by LocalFile
619 public function getBitDepth() {
624 * Return the size of the image file, in bytes
625 * Overridden by LocalFile, UnregisteredLocalFile
629 public function getSize() {
634 * Returns the mime type of the file.
635 * Overridden by LocalFile, UnregisteredLocalFile
640 function getMimeType() {
641 return 'unknown/unknown';
645 * Return the type of the media in the file.
646 * Use the value returned by this function with the MEDIATYPE_xxx constants.
647 * Overridden by LocalFile,
651 function getMediaType() {
652 return MEDIATYPE_UNKNOWN
;
656 * Checks if the output of transform() for this file is likely
657 * to be valid. If this is false, various user elements will
658 * display a placeholder instead.
660 * Currently, this checks if the file is an image format
661 * that can be converted to a format
662 * supported by all browsers (namely GIF, PNG and JPEG),
663 * or if it is an SVG image and SVG conversion is enabled.
667 function canRender() {
668 if ( !isset( $this->canRender
) ) {
669 $this->canRender
= $this->getHandler() && $this->handler
->canRender( $this );
672 return $this->canRender
;
676 * Accessor for __get()
679 protected function getCanRender() {
680 return $this->canRender();
684 * Return true if the file is of a type that can't be directly
685 * rendered by typical browsers and needs to be re-rasterized.
687 * This returns true for everything but the bitmap types
688 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
689 * also return true for any non-image formats.
693 function mustRender() {
694 return $this->getHandler() && $this->handler
->mustRender( $this );
698 * Alias for canRender()
702 function allowInlineDisplay() {
703 return $this->canRender();
707 * Determines if this media file is in a format that is unlikely to
708 * contain viruses or malicious content. It uses the global
709 * $wgTrustedMediaFormats list to determine if the file is safe.
711 * This is used to show a warning on the description page of non-safe files.
712 * It may also be used to disallow direct [[media:...]] links to such files.
714 * Note that this function will always return true if allowInlineDisplay()
715 * or isTrustedFile() is true for this file.
719 function isSafeFile() {
720 if ( !isset( $this->isSafeFile
) ) {
721 $this->isSafeFile
= $this->getIsSafeFileUncached();
724 return $this->isSafeFile
;
728 * Accessor for __get()
732 protected function getIsSafeFile() {
733 return $this->isSafeFile();
741 protected function getIsSafeFileUncached() {
742 global $wgTrustedMediaFormats;
744 if ( $this->allowInlineDisplay() ) {
747 if ( $this->isTrustedFile() ) {
751 $type = $this->getMediaType();
752 $mime = $this->getMimeType();
753 #wfDebug( "LocalFile::isSafeFile: type= $type, mime= $mime\n" );
755 if ( !$type ||
$type === MEDIATYPE_UNKNOWN
) {
756 return false; #unknown type, not trusted
758 if ( in_array( $type, $wgTrustedMediaFormats ) ) {
762 if ( $mime === "unknown/unknown" ) {
763 return false; #unknown type, not trusted
765 if ( in_array( $mime, $wgTrustedMediaFormats ) ) {
773 * Returns true if the file is flagged as trusted. Files flagged that way
774 * can be linked to directly, even if that is not allowed for this type of
777 * This is a dummy function right now and always returns false. It could be
778 * implemented to extract a flag from the database. The trusted flag could be
779 * set on upload, if the user has sufficient privileges, to bypass script-
780 * and html-filters. It may even be coupled with cryptographics signatures
785 function isTrustedFile() {
786 #this could be implemented to check a flag in the database,
787 #look for signatures, etc
792 * Returns true if file exists in the repository.
794 * Overridden by LocalFile to avoid unnecessary stat calls.
796 * @return bool Whether file exists in the repository.
798 public function exists() {
799 return $this->getPath() && $this->repo
->fileExists( $this->path
);
803 * Returns true if file exists in the repository and can be included in a page.
804 * It would be unsafe to include private images, making public thumbnails inadvertently
806 * @return bool Whether file exists in the repository and is includable.
808 public function isVisible() {
809 return $this->exists();
815 function getTransformScript() {
816 if ( !isset( $this->transformScript
) ) {
817 $this->transformScript
= false;
819 $script = $this->repo
->getThumbScriptUrl();
821 $this->transformScript
= wfAppendQuery( $script, array( 'f' => $this->getName() ) );
826 return $this->transformScript
;
830 * Get a ThumbnailImage which is the same size as the source
832 * @param array $handlerParams
836 function getUnscaledThumb( $handlerParams = array() ) {
837 $hp =& $handlerParams;
838 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
839 $width = $this->getWidth( $page );
841 return $this->iconThumb();
843 $hp['width'] = $width;
845 return $this->transform( $hp );
849 * Return the file name of a thumbnail with the specified parameters.
850 * Use File::THUMB_FULL_NAME to always get a name like "<params>-<source>".
851 * Otherwise, the format may be "<params>-<source>" or "<params>-thumbnail.<ext>".
853 * @param array $params handler-specific parameters
854 * @param int $flags Bitfield that supports THUMB_* constants
857 public function thumbName( $params, $flags = 0 ) {
858 $name = ( $this->repo
&& !( $flags & self
::THUMB_FULL_NAME
) )
859 ?
$this->repo
->nameForThumb( $this->getName() )
862 return $this->generateThumbName( $name, $params );
866 * Generate a thumbnail file name from a name and specified parameters
868 * @param string $name
869 * @param array $params Parameters which will be passed to MediaHandler::makeParamString
872 public function generateThumbName( $name, $params ) {
873 if ( !$this->getHandler() ) {
876 $extension = $this->getExtension();
877 list( $thumbExt, ) = $this->handler
->getThumbType(
878 $extension, $this->getMimeType(), $params );
879 $thumbName = $this->handler
->makeParamString( $params ) . '-' . $name;
880 if ( $thumbExt != $extension ) {
881 $thumbName .= ".$thumbExt";
888 * Create a thumbnail of the image having the specified width/height.
889 * The thumbnail will not be created if the width is larger than the
890 * image's width. Let the browser do the scaling in this case.
891 * The thumbnail is stored on disk and is only computed if the thumbnail
892 * file does not exist OR if it is older than the image.
895 * Keeps aspect ratio of original image. If both width and height are
896 * specified, the generated image will be no bigger than width x height,
897 * and will also have correct aspect ratio.
899 * @param int $width Maximum width of the generated thumbnail
900 * @param int $height Maximum height of the image (optional)
904 public function createThumb( $width, $height = -1 ) {
905 $params = array( 'width' => $width );
906 if ( $height != -1 ) {
907 $params['height'] = $height;
909 $thumb = $this->transform( $params );
910 if ( !$thumb ||
$thumb->isError() ) {
914 return $thumb->getUrl();
918 * Return either a MediaTransformError or placeholder thumbnail (if $wgIgnoreImageErrors)
920 * @param string $thumbPath Thumbnail storage path
921 * @param string $thumbUrl Thumbnail URL
922 * @param array $params
924 * @return MediaTransformOutput
926 protected function transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags ) {
927 global $wgIgnoreImageErrors;
929 $handler = $this->getHandler();
930 if ( $handler && $wgIgnoreImageErrors && !( $flags & self
::RENDER_NOW
) ) {
931 return $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
933 return new MediaTransformError( 'thumbnail_error',
934 $params['width'], 0, wfMessage( 'thumbnail-dest-create' )->text() );
939 * Transform a media file
941 * @param array $params an associative array of handler-specific parameters.
942 * Typical keys are width, height and page.
943 * @param int $flags A bitfield, may contain self::RENDER_NOW to force rendering
944 * @return MediaTransformOutput|bool False on failure
946 function transform( $params, $flags = 0 ) {
947 global $wgUseSquid, $wgIgnoreImageErrors, $wgThumbnailEpoch;
949 wfProfileIn( __METHOD__
);
951 if ( !$this->canRender() ) {
952 $thumb = $this->iconThumb();
953 break; // not a bitmap or renderable image, don't try
956 // Get the descriptionUrl to embed it as comment into the thumbnail. Bug 19791.
957 $descriptionUrl = $this->getDescriptionUrl();
958 if ( $descriptionUrl ) {
959 $params['descriptionUrl'] = wfExpandUrl( $descriptionUrl, PROTO_CANONICAL
);
962 $handler = $this->getHandler();
963 $script = $this->getTransformScript();
964 if ( $script && !( $flags & self
::RENDER_NOW
) ) {
965 // Use a script to transform on client request, if possible
966 $thumb = $handler->getScriptedTransform( $this, $script, $params );
972 $normalisedParams = $params;
973 $handler->normaliseParams( $this, $normalisedParams );
975 $thumbName = $this->thumbName( $normalisedParams );
976 $thumbUrl = $this->getThumbUrl( $thumbName );
977 $thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
980 // Defer rendering if a 404 handler is set up...
981 if ( $this->repo
->canTransformVia404() && !( $flags & self
::RENDER_NOW
) ) {
982 wfDebug( __METHOD__
. " transformation deferred." );
983 // XXX: Pass in the storage path even though we are not rendering anything
984 // and the path is supposed to be an FS path. This is due to getScalerType()
985 // getting called on the path and clobbering $thumb->getUrl() if it's false.
986 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
989 // Clean up broken thumbnails as needed
990 $this->migrateThumbFile( $thumbName );
991 // Check if an up-to-date thumbnail already exists...
992 wfDebug( __METHOD__
. ": Doing stat for $thumbPath\n" );
993 if ( !( $flags & self
::RENDER_FORCE
) && $this->repo
->fileExists( $thumbPath ) ) {
994 $timestamp = $this->repo
->getFileTimestamp( $thumbPath );
995 if ( $timestamp !== false && $timestamp >= $wgThumbnailEpoch ) {
996 // XXX: Pass in the storage path even though we are not rendering anything
997 // and the path is supposed to be an FS path. This is due to getScalerType()
998 // getting called on the path and clobbering $thumb->getUrl() if it's false.
999 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
1000 $thumb->setStoragePath( $thumbPath );
1003 } elseif ( $flags & self
::RENDER_FORCE
) {
1004 wfDebug( __METHOD__
. " forcing rendering per flag File::RENDER_FORCE\n" );
1008 // If the backend is ready-only, don't keep generating thumbnails
1009 // only to return transformation errors, just return the error now.
1010 if ( $this->repo
->getReadOnlyReason() !== false ) {
1011 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
1015 // Create a temp FS file with the same extension and the thumbnail
1016 $thumbExt = FileBackend
::extensionFromPath( $thumbPath );
1017 $tmpFile = TempFSFile
::factory( 'transform_', $thumbExt );
1019 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
1022 $tmpThumbPath = $tmpFile->getPath(); // path of 0-byte temp file
1024 // Actually render the thumbnail...
1025 wfProfileIn( __METHOD__
. '-doTransform' );
1026 $thumb = $handler->doTransform( $this, $tmpThumbPath, $thumbUrl, $params );
1027 wfProfileOut( __METHOD__
. '-doTransform' );
1028 $tmpFile->bind( $thumb ); // keep alive with $thumb
1030 if ( !$thumb ) { // bad params?
1032 } elseif ( $thumb->isError() ) { // transform error
1033 $this->lastError
= $thumb->toText();
1034 // Ignore errors if requested
1035 if ( $wgIgnoreImageErrors && !( $flags & self
::RENDER_NOW
) ) {
1036 $thumb = $handler->getTransform( $this, $tmpThumbPath, $thumbUrl, $params );
1038 } elseif ( $this->repo
&& $thumb->hasFile() && !$thumb->fileIsSource() ) {
1039 // Copy the thumbnail from the file system into storage...
1040 $disposition = $this->getThumbDisposition( $thumbName );
1041 $status = $this->repo
->quickImport( $tmpThumbPath, $thumbPath, $disposition );
1042 if ( $status->isOK() ) {
1043 $thumb->setStoragePath( $thumbPath );
1045 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
1047 // Give extensions a chance to do something with this thumbnail...
1048 wfRunHooks( 'FileTransformed', array( $this, $thumb, $tmpThumbPath, $thumbPath ) );
1051 // Purge. Useful in the event of Core -> Squid connection failure or squid
1052 // purge collisions from elsewhere during failure. Don't keep triggering for
1053 // "thumbs" which have the main image URL though (bug 13776)
1054 if ( $wgUseSquid ) {
1055 if ( !$thumb ||
$thumb->isError() ||
$thumb->getUrl() != $this->getURL() ) {
1056 SquidUpdate
::purge( array( $thumbUrl ) );
1061 wfProfileOut( __METHOD__
);
1063 return is_object( $thumb ) ?
$thumb : false;
1067 * @param string $thumbName Thumbnail name
1068 * @return string Content-Disposition header value
1070 function getThumbDisposition( $thumbName ) {
1071 $fileName = $this->name
; // file name to suggest
1072 $thumbExt = FileBackend
::extensionFromPath( $thumbName );
1073 if ( $thumbExt != '' && $thumbExt !== $this->getExtension() ) {
1074 $fileName .= ".$thumbExt";
1077 return FileBackend
::makeContentDisposition( 'inline', $fileName );
1081 * Hook into transform() to allow migration of thumbnail files
1083 * Overridden by LocalFile
1085 function migrateThumbFile( $thumbName ) {
1089 * Get a MediaHandler instance for this file
1091 * @return MediaHandler|bool Registered MediaHandler for file's MIME type
1092 * or false if none found
1094 function getHandler() {
1095 if ( !isset( $this->handler
) ) {
1096 $this->handler
= MediaHandler
::getHandler( $this->getMimeType() );
1099 return $this->handler
;
1103 * Get a ThumbnailImage representing a file type icon
1105 * @return ThumbnailImage
1107 function iconThumb() {
1108 global $wgStylePath, $wgStyleDirectory;
1110 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
1111 foreach ( $try as $icon ) {
1112 $path = '/common/images/icons/' . $icon;
1113 $filepath = $wgStyleDirectory . $path;
1114 if ( file_exists( $filepath ) ) { // always FS
1115 $params = array( 'width' => 120, 'height' => 120 );
1117 return new ThumbnailImage( $this, $wgStylePath . $path, false, $params );
1125 * Get last thumbnailing error.
1128 function getLastError() {
1129 return $this->lastError
;
1133 * Get all thumbnail names previously generated for this file
1135 * Overridden by LocalFile
1138 function getThumbnails() {
1143 * Purge shared caches such as thumbnails and DB data caching
1145 * Overridden by LocalFile
1146 * @param array $options Options, which include:
1147 * 'forThumbRefresh' : The purging is only to refresh thumbnails
1149 function purgeCache( $options = array() ) {
1153 * Purge the file description page, but don't go after
1154 * pages using the file. Use when modifying file history
1155 * but not the current data.
1157 function purgeDescription() {
1158 $title = $this->getTitle();
1160 $title->invalidateCache();
1161 $title->purgeSquid();
1166 * Purge metadata and all affected pages when the file is created,
1167 * deleted, or majorly updated.
1169 function purgeEverything() {
1170 // Delete thumbnails and refresh file metadata cache
1171 $this->purgeCache();
1172 $this->purgeDescription();
1174 // Purge cache of all pages using this file
1175 $title = $this->getTitle();
1177 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
1178 $update->doUpdate();
1183 * Return a fragment of the history of file.
1186 * @param int $limit Limit of rows to return
1187 * @param string $start timestamp Only revisions older than $start will be returned
1188 * @param string $end timestamp Only revisions newer than $end will be returned
1189 * @param bool $inc Include the endpoints of the time range
1193 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1198 * Return the history of this file, line by line. Starts with current version,
1199 * then old versions. Should return an object similar to an image/oldimage
1203 * Overridden in LocalFile
1206 public function nextHistoryLine() {
1211 * Reset the history pointer to the first element of the history.
1212 * Always call this function after using nextHistoryLine() to free db resources
1214 * Overridden in LocalFile.
1216 public function resetHistory() {
1220 * Get the filename hash component of the directory including trailing slash,
1222 * If the repository is not hashed, returns an empty string.
1226 function getHashPath() {
1227 if ( !isset( $this->hashPath
) ) {
1228 $this->assertRepoDefined();
1229 $this->hashPath
= $this->repo
->getHashPath( $this->getName() );
1232 return $this->hashPath
;
1236 * Get the path of the file relative to the public zone root.
1237 * This function is overriden in OldLocalFile to be like getArchiveRel().
1242 return $this->getHashPath() . $this->getName();
1246 * Get the path of an archived file relative to the public zone root
1248 * @param bool|string $suffix if not false, the name of an archived thumbnail file
1252 function getArchiveRel( $suffix = false ) {
1253 $path = 'archive/' . $this->getHashPath();
1254 if ( $suffix === false ) {
1255 $path = substr( $path, 0, -1 );
1264 * Get the path, relative to the thumbnail zone root, of the
1265 * thumbnail directory or a particular file if $suffix is specified
1267 * @param bool|string $suffix if not false, the name of a thumbnail file
1270 function getThumbRel( $suffix = false ) {
1271 $path = $this->getRel();
1272 if ( $suffix !== false ) {
1273 $path .= '/' . $suffix;
1280 * Get urlencoded path of the file relative to the public zone root.
1281 * This function is overriden in OldLocalFile to be like getArchiveUrl().
1285 function getUrlRel() {
1286 return $this->getHashPath() . rawurlencode( $this->getName() );
1290 * Get the path, relative to the thumbnail zone root, for an archived file's thumbs directory
1291 * or a specific thumb if the $suffix is given.
1293 * @param string $archiveName the timestamped name of an archived image
1294 * @param bool|string $suffix if not false, the name of a thumbnail file
1297 function getArchiveThumbRel( $archiveName, $suffix = false ) {
1298 $path = 'archive/' . $this->getHashPath() . $archiveName . "/";
1299 if ( $suffix === false ) {
1300 $path = substr( $path, 0, -1 );
1309 * Get the path of the archived file.
1311 * @param bool|string $suffix if not false, the name of an archived file.
1314 function getArchivePath( $suffix = false ) {
1315 $this->assertRepoDefined();
1317 return $this->repo
->getZonePath( 'public' ) . '/' . $this->getArchiveRel( $suffix );
1321 * Get the path of an archived file's thumbs, or a particular thumb if $suffix is specified
1323 * @param string $archiveName the timestamped name of an archived image
1324 * @param bool|string $suffix if not false, the name of a thumbnail file
1327 function getArchiveThumbPath( $archiveName, $suffix = false ) {
1328 $this->assertRepoDefined();
1330 return $this->repo
->getZonePath( 'thumb' ) . '/' .
1331 $this->getArchiveThumbRel( $archiveName, $suffix );
1335 * Get the path of the thumbnail directory, or a particular file if $suffix is specified
1337 * @param bool|string $suffix If not false, the name of a thumbnail file
1340 function getThumbPath( $suffix = false ) {
1341 $this->assertRepoDefined();
1343 return $this->repo
->getZonePath( 'thumb' ) . '/' . $this->getThumbRel( $suffix );
1347 * Get the path of the transcoded directory, or a particular file if $suffix is specified
1349 * @param bool|string $suffix If not false, the name of a media file
1352 function getTranscodedPath( $suffix = false ) {
1353 $this->assertRepoDefined();
1355 return $this->repo
->getZonePath( 'transcoded' ) . '/' . $this->getThumbRel( $suffix );
1359 * Get the URL of the archive directory, or a particular file if $suffix is specified
1361 * @param bool|string $suffix If not false, the name of an archived file
1364 function getArchiveUrl( $suffix = false ) {
1365 $this->assertRepoDefined();
1366 $ext = $this->getExtension();
1367 $path = $this->repo
->getZoneUrl( 'public', $ext ) . '/archive/' . $this->getHashPath();
1368 if ( $suffix === false ) {
1369 $path = substr( $path, 0, -1 );
1371 $path .= rawurlencode( $suffix );
1378 * Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified
1380 * @param string $archiveName the timestamped name of an archived image
1381 * @param bool|string $suffix If not false, the name of a thumbnail file
1384 function getArchiveThumbUrl( $archiveName, $suffix = false ) {
1385 $this->assertRepoDefined();
1386 $ext = $this->getExtension();
1387 $path = $this->repo
->getZoneUrl( 'thumb', $ext ) . '/archive/' .
1388 $this->getHashPath() . rawurlencode( $archiveName ) . "/";
1389 if ( $suffix === false ) {
1390 $path = substr( $path, 0, -1 );
1392 $path .= rawurlencode( $suffix );
1399 * Get the URL of the zone directory, or a particular file if $suffix is specified
1401 * @param string $zone name of requested zone
1402 * @param bool|string $suffix If not false, the name of a file in zone
1403 * @return string path
1405 function getZoneUrl( $zone, $suffix = false ) {
1406 $this->assertRepoDefined();
1407 $ext = $this->getExtension();
1408 $path = $this->repo
->getZoneUrl( $zone, $ext ) . '/' . $this->getUrlRel();
1409 if ( $suffix !== false ) {
1410 $path .= '/' . rawurlencode( $suffix );
1417 * Get the URL of the thumbnail directory, or a particular file if $suffix is specified
1419 * @param bool|string $suffix if not false, the name of a thumbnail file
1420 * @return string path
1422 function getThumbUrl( $suffix = false ) {
1423 return $this->getZoneUrl( 'thumb', $suffix );
1427 * Get the URL of the transcoded directory, or a particular file if $suffix is specified
1429 * @param bool|string $suffix If not false, the name of a media file
1430 * @return string path
1432 function getTranscodedUrl( $suffix = false ) {
1433 return $this->getZoneUrl( 'transcoded', $suffix );
1437 * Get the public zone virtual URL for a current version source file
1439 * @param bool|string $suffix If not false, the name of a thumbnail file
1442 function getVirtualUrl( $suffix = false ) {
1443 $this->assertRepoDefined();
1444 $path = $this->repo
->getVirtualUrl() . '/public/' . $this->getUrlRel();
1445 if ( $suffix !== false ) {
1446 $path .= '/' . rawurlencode( $suffix );
1453 * Get the public zone virtual URL for an archived version source file
1455 * @param bool|string $suffix If not false, the name of a thumbnail file
1458 function getArchiveVirtualUrl( $suffix = false ) {
1459 $this->assertRepoDefined();
1460 $path = $this->repo
->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
1461 if ( $suffix === false ) {
1462 $path = substr( $path, 0, -1 );
1464 $path .= rawurlencode( $suffix );
1471 * Get the virtual URL for a thumbnail file or directory
1473 * @param bool|string $suffix If not false, the name of a thumbnail file
1476 function getThumbVirtualUrl( $suffix = false ) {
1477 $this->assertRepoDefined();
1478 $path = $this->repo
->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
1479 if ( $suffix !== false ) {
1480 $path .= '/' . rawurlencode( $suffix );
1489 function isHashed() {
1490 $this->assertRepoDefined();
1492 return (bool)$this->repo
->getHashLevels();
1496 * @throws MWException
1498 function readOnlyError() {
1499 throw new MWException( get_class( $this ) . ': write operations are not supported' );
1503 * Record a file upload in the upload log and the image table
1505 * Overridden by LocalFile
1508 * @param string $license
1509 * @param string $copyStatus
1510 * @param string $source
1511 * @param bool $watch
1512 * @param string|bool $timestamp
1513 * @param null|User $user User object or null to use $wgUser
1515 * @throws MWException
1517 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1518 $watch = false, $timestamp = false, User
$user = null
1520 $this->readOnlyError();
1524 * Move or copy a file to its public location. If a file exists at the
1525 * destination, move it to an archive. Returns a FileRepoStatus object with
1526 * the archive name in the "value" member on success.
1528 * The archive name should be passed through to recordUpload for database
1531 * Options to $options include:
1532 * - headers : name/value map of HTTP headers to use in response to GET/HEAD requests
1534 * @param string $srcPath local filesystem path to the source image
1535 * @param int $flags A bitwise combination of:
1536 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1537 * @param array $options Optional additional parameters
1538 * @return FileRepoStatus object. On success, the value member contains the
1539 * archive name, or an empty string if it was a new file.
1542 * Overridden by LocalFile
1544 function publish( $srcPath, $flags = 0, array $options = array() ) {
1545 $this->readOnlyError();
1551 function formatMetadata() {
1552 if ( !$this->getHandler() ) {
1556 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
1560 * Returns true if the file comes from the local file repository.
1564 function isLocal() {
1565 return $this->repo
&& $this->repo
->isLocal();
1569 * Returns the name of the repository.
1573 function getRepoName() {
1574 return $this->repo ?
$this->repo
->getName() : 'unknown';
1578 * Returns the repository
1580 * @return FileRepo|LocalRepo|bool
1582 function getRepo() {
1587 * Returns true if the image is an old version
1597 * Is this file a "deleted" file in a private archive?
1600 * @param int $field one of DELETED_* bitfield constants
1603 function isDeleted( $field ) {
1608 * Return the deletion bitfield
1612 function getVisibility() {
1617 * Was this file ever deleted from the wiki?
1621 function wasDeleted() {
1622 $title = $this->getTitle();
1624 return $title && $title->isDeletedQuick();
1628 * Move file to the new title
1630 * Move current, old version and all thumbnails
1631 * to the new filename. Old file is deleted.
1633 * Cache purging is done; checks for validity
1634 * and logging are caller's responsibility
1636 * @param Title $target New file name
1637 * @return FileRepoStatus object.
1639 function move( $target ) {
1640 $this->readOnlyError();
1644 * Delete all versions of the file.
1646 * Moves the files into an archive directory (or deletes them)
1647 * and removes the database rows.
1649 * Cache purging is done; logging is caller's responsibility.
1651 * @param string $reason
1652 * @param bool $suppress Hide content from sysops?
1653 * @return bool on success, false on some kind of failure
1655 * Overridden by LocalFile
1657 function delete( $reason, $suppress = false ) {
1658 $this->readOnlyError();
1662 * Restore all or specified deleted revisions to the given file.
1663 * Permissions and logging are left to the caller.
1665 * May throw database exceptions on error.
1667 * @param array $versions set of record ids of deleted items to restore,
1668 * or empty to restore all revisions.
1669 * @param bool $unsuppress remove restrictions on content upon restoration?
1670 * @return int|bool the number of file revisions restored if successful,
1671 * or false on failure
1673 * Overridden by LocalFile
1675 function restore( $versions = array(), $unsuppress = false ) {
1676 $this->readOnlyError();
1680 * Returns 'true' if this file is a type which supports multiple pages,
1681 * e.g. DJVU or PDF. Note that this may be true even if the file in
1682 * question only has a single page.
1686 function isMultipage() {
1687 return $this->getHandler() && $this->handler
->isMultiPage( $this );
1691 * Returns the number of pages of a multipage document, or false for
1692 * documents which aren't multipage documents
1696 function pageCount() {
1697 if ( !isset( $this->pageCount
) ) {
1698 if ( $this->getHandler() && $this->handler
->isMultiPage( $this ) ) {
1699 $this->pageCount
= $this->handler
->pageCount( $this );
1701 $this->pageCount
= false;
1705 return $this->pageCount
;
1709 * Calculate the height of a thumbnail using the source and destination width
1711 * @param int $srcWidth
1712 * @param int $srcHeight
1713 * @param int $dstWidth
1717 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1718 // Exact integer multiply followed by division
1719 if ( $srcWidth == 0 ) {
1722 return round( $srcHeight * $dstWidth / $srcWidth );
1727 * Get an image size array like that returned by getImageSize(), or false if it
1728 * can't be determined.
1730 * @param string $fileName The filename
1733 function getImageSize( $fileName ) {
1734 if ( !$this->getHandler() ) {
1738 return $this->handler
->getImageSize( $this, $fileName );
1742 * Get the URL of the image description page. May return false if it is
1743 * unknown or not applicable.
1747 function getDescriptionUrl() {
1748 if ( $this->repo
) {
1749 return $this->repo
->getDescriptionUrl( $this->getName() );
1756 * Get the HTML text of the description page, if available
1758 * @param bool|Language $lang Optional language to fetch description in
1761 function getDescriptionText( $lang = false ) {
1762 global $wgMemc, $wgLang;
1763 if ( !$this->repo ||
!$this->repo
->fetchDescription
) {
1769 $renderUrl = $this->repo
->getDescriptionRenderUrl( $this->getName(), $lang->getCode() );
1771 if ( $this->repo
->descriptionCacheExpiry
> 0 ) {
1772 wfDebug( "Attempting to get the description from cache..." );
1773 $key = $this->repo
->getLocalCacheKey(
1774 'RemoteFileDescription',
1779 $obj = $wgMemc->get( $key );
1781 wfDebug( "success!\n" );
1785 wfDebug( "miss\n" );
1787 wfDebug( "Fetching shared description from $renderUrl\n" );
1788 $res = Http
::get( $renderUrl );
1789 if ( $res && $this->repo
->descriptionCacheExpiry
> 0 ) {
1790 $wgMemc->set( $key, $res, $this->repo
->descriptionCacheExpiry
);
1800 * Get description of file revision
1803 * @param int $audience One of:
1804 * File::FOR_PUBLIC to be displayed to all users
1805 * File::FOR_THIS_USER to be displayed to the given user
1806 * File::RAW get the description regardless of permissions
1807 * @param User $user User object to check for, only if FOR_THIS_USER is
1808 * passed to the $audience parameter
1811 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1816 * Get the 14-character timestamp of the file upload
1818 * @return string|bool TS_MW timestamp or false on failure
1820 function getTimestamp() {
1821 $this->assertRepoDefined();
1823 return $this->repo
->getFileTimestamp( $this->getPath() );
1827 * Get the SHA-1 base 36 hash of the file
1831 function getSha1() {
1832 $this->assertRepoDefined();
1834 return $this->repo
->getFileSha1( $this->getPath() );
1838 * Get the deletion archive key, "<sha1>.<ext>"
1842 function getStorageKey() {
1843 $hash = $this->getSha1();
1847 $ext = $this->getExtension();
1848 $dotExt = $ext === '' ?
'' : ".$ext";
1850 return $hash . $dotExt;
1854 * Determine if the current user is allowed to view a particular
1855 * field of this file, if it's marked as deleted.
1858 * @param User $user User object to check, or null to use $wgUser
1861 function userCan( $field, User
$user = null ) {
1866 * Get an associative array containing information about a file in the local filesystem.
1868 * @param string $path absolute local filesystem path
1869 * @param string|bool $ext The file extension, or true to extract it from
1870 * the filename. Set it to false to ignore the extension.
1873 * @deprecated since 1.19
1875 static function getPropsFromPath( $path, $ext = true ) {
1876 wfDebug( __METHOD__
. ": Getting file info for $path\n" );
1877 wfDeprecated( __METHOD__
, '1.19' );
1879 $fsFile = new FSFile( $path );
1881 return $fsFile->getProps();
1885 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1886 * encoding, zero padded to 31 digits.
1888 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1891 * @param $path string
1892 * @return bool|string False on failure
1893 * @deprecated since 1.19
1895 static function sha1Base36( $path ) {
1896 wfDeprecated( __METHOD__
, '1.19' );
1898 $fsFile = new FSFile( $path );
1900 return $fsFile->getSha1Base36();
1904 * @return array HTTP header name/value map to use for HEAD/GET request responses
1906 function getStreamHeaders() {
1907 $handler = $this->getHandler();
1909 return $handler->getStreamHeaders( $this->getMetadata() );
1918 function getLongDesc() {
1919 $handler = $this->getHandler();
1921 return $handler->getLongDesc( $this );
1923 return MediaHandler
::getGeneralLongDesc( $this );
1930 function getShortDesc() {
1931 $handler = $this->getHandler();
1933 return $handler->getShortDesc( $this );
1935 return MediaHandler
::getGeneralShortDesc( $this );
1942 function getDimensionsString() {
1943 $handler = $this->getHandler();
1945 return $handler->getDimensionsString( $this );
1954 function getRedirected() {
1955 return $this->redirected
;
1959 * @return Title|null
1961 function getRedirectedTitle() {
1962 if ( $this->redirected
) {
1963 if ( !$this->redirectTitle
) {
1964 $this->redirectTitle
= Title
::makeTitle( NS_FILE
, $this->redirected
);
1967 return $this->redirectTitle
;
1974 * @param string $from
1977 function redirectedFrom( $from ) {
1978 $this->redirected
= $from;
1984 function isMissing() {
1989 * Check if this file object is small and can be cached
1992 public function isCacheable() {
1997 * Assert that $this->repo is set to a valid FileRepo instance
1998 * @throws MWException
2000 protected function assertRepoDefined() {
2001 if ( !( $this->repo
instanceof $this->repoClass
) ) {
2002 throw new MWException( "A {$this->repoClass} object is not set for this File.\n" );
2007 * Assert that $this->title is set to a Title
2008 * @throws MWException
2010 protected function assertTitleDefined() {
2011 if ( !( $this->title
instanceof Title
) ) {
2012 throw new MWException( "A Title object is not set for this File.\n" );