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 const DELETED_FILE
= 1;
52 const DELETED_COMMENT
= 2;
53 const DELETED_USER
= 4;
54 const DELETED_RESTRICTED
= 8;
56 /** Force rendering in the current process */
59 * Force rendering even if thumbnail already exist and using RENDER_NOW
60 * I.e. you have to pass both flags: File::RENDER_NOW | File::RENDER_FORCE
62 const RENDER_FORCE
= 2;
64 const DELETE_SOURCE
= 1;
66 // Audience options for File::getDescription()
68 const FOR_THIS_USER
= 2;
71 // Options for File::thumbName()
72 const THUMB_FULL_NAME
= 1;
75 * Some member variables can be lazy-initialised using __get(). The
76 * initialisation function for these variables is always a function named
77 * like getVar(), where Var is the variable name with upper-case first
80 * The following variables are initialised in this way in this base class:
81 * name, extension, handler, path, canRender, isSafeFile,
82 * transformScript, hashPath, pageCount, url
84 * Code within this class should generally use the accessor function
85 * directly, since __get() isn't re-entrant and therefore causes bugs that
86 * depend on initialisation order.
90 * The following member variables are not lazy-initialised
103 var $lastError, $redirected, $redirectedTitle;
106 * @var FSFile|bool False if undefined
118 protected $url, $extension, $name, $path, $hashPath, $pageCount, $transformScript;
120 protected $redirectTitle;
125 protected $canRender, $isSafeFile;
128 * @var string Required Repository class type
130 protected $repoClass = 'FileRepo';
133 * Call this constructor from child classes.
135 * Both $title and $repo are optional, though some functions
136 * may return false or throw exceptions if they are not set.
137 * Most subclasses will want to call assertRepoDefined() here.
139 * @param $title Title|string|bool
140 * @param $repo FileRepo|bool
142 function __construct( $title, $repo ) {
143 if ( $title !== false ) { // subclasses may not use MW titles
144 $title = self
::normalizeTitle( $title, 'exception' );
146 $this->title
= $title;
151 * Given a string or Title object return either a
152 * valid Title object with namespace NS_FILE or null
154 * @param $title Title|string
155 * @param $exception string|bool Use 'exception' to throw an error on bad titles
156 * @throws MWException
159 static function normalizeTitle( $title, $exception = false ) {
161 if ( $ret instanceof Title
) {
162 # Normalize NS_MEDIA -> NS_FILE
163 if ( $ret->getNamespace() == NS_MEDIA
) {
164 $ret = Title
::makeTitleSafe( NS_FILE
, $ret->getDBkey() );
165 # Sanity check the title namespace
166 } elseif ( $ret->getNamespace() !== NS_FILE
) {
170 # Convert strings to Title objects
171 $ret = Title
::makeTitleSafe( NS_FILE
, (string)$ret );
173 if ( !$ret && $exception !== false ) {
174 throw new MWException( "`$title` is not a valid file title." );
179 function __get( $name ) {
180 $function = array( $this, 'get' . ucfirst( $name ) );
181 if ( !is_callable( $function ) ) {
184 $this->$name = call_user_func( $function );
190 * Normalize a file extension to the common form, and ensure it's clean.
191 * Extensions with non-alphanumeric characters will be discarded.
193 * @param $ext string (without the .)
196 static function normalizeExtension( $ext ) {
197 $lower = strtolower( $ext );
204 if( isset( $squish[$lower] ) ) {
205 return $squish[$lower];
206 } elseif( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
214 * Checks if file extensions are compatible
216 * @param $old File Old file
217 * @param $new string New name
221 static function checkExtensionCompatibility( File
$old, $new ) {
222 $oldMime = $old->getMimeType();
223 $n = strrpos( $new, '.' );
224 $newExt = self
::normalizeExtension( $n ?
substr( $new, $n +
1 ) : '' );
225 $mimeMagic = MimeMagic
::singleton();
226 return $mimeMagic->isMatchingExtension( $newExt, $oldMime );
230 * Upgrade the database row if there is one
231 * Called by ImagePage
234 function upgradeRow() {}
237 * Split an internet media type into its two components; if not
238 * a two-part name, set the minor type to 'unknown'.
240 * @param string $mime "text/html" etc
241 * @return array ("text", "html") etc
243 public static function splitMime( $mime ) {
244 if( strpos( $mime, '/' ) !== false ) {
245 return explode( '/', $mime, 2 );
247 return array( $mime, 'unknown' );
252 * Callback for usort() to do file sorts by name
257 * @return Integer: result of name comparison
259 public static function compare( File
$a, File
$b ) {
260 return strcmp( $a->getName(), $b->getName() );
264 * Return the name of this file
268 public function getName() {
269 if ( !isset( $this->name
) ) {
270 $this->assertRepoDefined();
271 $this->name
= $this->repo
->getNameFromTitle( $this->title
);
277 * Get the file extension, e.g. "svg"
281 function getExtension() {
282 if ( !isset( $this->extension
) ) {
283 $n = strrpos( $this->getName(), '.' );
284 $this->extension
= self
::normalizeExtension(
285 $n ?
substr( $this->getName(), $n +
1 ) : '' );
287 return $this->extension
;
291 * Return the associated title object
295 public function getTitle() {
300 * Return the title used to find this file
304 public function getOriginalTitle() {
305 if ( $this->redirected
) {
306 return $this->getRedirectedTitle();
312 * Return the URL of the file
316 public function getUrl() {
317 if ( !isset( $this->url
) ) {
318 $this->assertRepoDefined();
319 $ext = $this->getExtension();
320 $this->url
= $this->repo
->getZoneUrl( 'public', $ext ) . '/' . $this->getUrlRel();
326 * Return a fully-qualified URL to the file.
327 * Upload URL paths _may or may not_ be fully qualified, so
328 * we check. Local paths are assumed to belong on $wgServer.
332 public function getFullUrl() {
333 return wfExpandUrl( $this->getUrl(), PROTO_RELATIVE
);
339 public function getCanonicalUrl() {
340 return wfExpandUrl( $this->getUrl(), PROTO_CANONICAL
);
346 function getViewURL() {
347 if ( $this->mustRender() ) {
348 if ( $this->canRender() ) {
349 return $this->createThumb( $this->getWidth() );
351 wfDebug( __METHOD__
.': supposed to render ' . $this->getName() .
352 ' (' . $this->getMimeType() . "), but can't!\n" );
353 return $this->getURL(); #hm... return NULL?
356 return $this->getURL();
361 * Return the storage path to the file. Note that this does
362 * not mean that a file actually exists under that location.
364 * This path depends on whether directory hashing is active or not,
365 * i.e. whether the files are all found in the same directory,
366 * or in hashed paths like /images/3/3c.
368 * Most callers don't check the return value, but ForeignAPIFile::getPath
371 * @return string|bool ForeignAPIFile::getPath can return false
373 public function getPath() {
374 if ( !isset( $this->path
) ) {
375 $this->assertRepoDefined();
376 $this->path
= $this->repo
->getZonePath( 'public' ) . '/' . $this->getRel();
382 * Get an FS copy or original of this file and return the path.
383 * Returns false on failure. Callers must not alter the file.
384 * Temporary files are cleared automatically.
386 * @return string|bool False on failure
388 public function getLocalRefPath() {
389 $this->assertRepoDefined();
390 if ( !isset( $this->fsFile
) ) {
391 $this->fsFile
= $this->repo
->getLocalReference( $this->getPath() );
392 if ( !$this->fsFile
) {
393 $this->fsFile
= false; // null => false; cache negative hits
396 return ( $this->fsFile
)
397 ?
$this->fsFile
->getPath()
402 * Return the width of the image. Returns false if the width is unknown
406 * Overridden by LocalFile, UnregisteredLocalFile
412 public function getWidth( $page = 1 ) {
417 * Return the height of the image. Returns false if the height is unknown
421 * Overridden by LocalFile, UnregisteredLocalFile
425 * @return bool|number False on failure
427 public function getHeight( $page = 1 ) {
432 * Returns ID or name of user who uploaded the file
435 * @param $type string 'text' or 'id'
439 public function getUser( $type = 'text' ) {
444 * Get the duration of a media file in seconds
448 public function getLength() {
449 $handler = $this->getHandler();
451 return $handler->getLength( $this );
458 * Return true if the file is vectorized
462 public function isVectorized() {
463 $handler = $this->getHandler();
465 return $handler->isVectorized( $this );
472 * Will the thumbnail be animated if one would expect it to be.
474 * Currently used to add a warning to the image description page
476 * @return bool false if the main image is both animated
477 * and the thumbnail is not. In all other cases must return
478 * true. If image is not renderable whatsoever, should
481 public function canAnimateThumbIfAppropriate() {
482 $handler = $this->getHandler();
484 // We cannot handle image whatsoever, thus
485 // one would not expect it to be animated
489 if ( $this->allowInlineDisplay()
490 && $handler->isAnimatedImage( $this )
491 && !$handler->canAnimateThumbnail( $this )
493 // Image is animated, but thumbnail isn't.
494 // This is unexpected to the user.
497 // Image is not animated, so one would
498 // not expect thumb to be
505 * Get handler-specific metadata
506 * Overridden by LocalFile, UnregisteredLocalFile
510 public function getMetadata() {
515 * get versioned metadata
517 * @param $metadata Mixed Array or String of (serialized) metadata
518 * @param $version integer version number.
519 * @return Array containing metadata, or what was passed to it on fail (unserializing if not array)
521 public function convertMetadataVersion($metadata, $version) {
522 $handler = $this->getHandler();
523 if ( !is_array( $metadata ) ) {
524 // Just to make the return type consistent
525 $metadata = unserialize( $metadata );
528 return $handler->convertMetadataVersion( $metadata, $version );
535 * Return the bit depth of the file
536 * Overridden by LocalFile
540 public function getBitDepth() {
545 * Return the size of the image file, in bytes
546 * Overridden by LocalFile, UnregisteredLocalFile
550 public function getSize() {
555 * Returns the mime type of the file.
556 * Overridden by LocalFile, UnregisteredLocalFile
561 function getMimeType() {
562 return 'unknown/unknown';
566 * Return the type of the media in the file.
567 * Use the value returned by this function with the MEDIATYPE_xxx constants.
568 * Overridden by LocalFile,
572 function getMediaType() {
573 return MEDIATYPE_UNKNOWN
;
577 * Checks if the output of transform() for this file is likely
578 * to be valid. If this is false, various user elements will
579 * display a placeholder instead.
581 * Currently, this checks if the file is an image format
582 * that can be converted to a format
583 * supported by all browsers (namely GIF, PNG and JPEG),
584 * or if it is an SVG image and SVG conversion is enabled.
588 function canRender() {
589 if ( !isset( $this->canRender
) ) {
590 $this->canRender
= $this->getHandler() && $this->handler
->canRender( $this );
592 return $this->canRender
;
596 * Accessor for __get()
599 protected function getCanRender() {
600 return $this->canRender();
604 * Return true if the file is of a type that can't be directly
605 * rendered by typical browsers and needs to be re-rasterized.
607 * This returns true for everything but the bitmap types
608 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
609 * also return true for any non-image formats.
613 function mustRender() {
614 return $this->getHandler() && $this->handler
->mustRender( $this );
618 * Alias for canRender()
622 function allowInlineDisplay() {
623 return $this->canRender();
627 * Determines if this media file is in a format that is unlikely to
628 * contain viruses or malicious content. It uses the global
629 * $wgTrustedMediaFormats list to determine if the file is safe.
631 * This is used to show a warning on the description page of non-safe files.
632 * It may also be used to disallow direct [[media:...]] links to such files.
634 * Note that this function will always return true if allowInlineDisplay()
635 * or isTrustedFile() is true for this file.
639 function isSafeFile() {
640 if ( !isset( $this->isSafeFile
) ) {
641 $this->isSafeFile
= $this->_getIsSafeFile();
643 return $this->isSafeFile
;
647 * Accessor for __get()
651 protected function getIsSafeFile() {
652 return $this->isSafeFile();
660 protected function _getIsSafeFile() {
661 global $wgTrustedMediaFormats;
663 if ( $this->allowInlineDisplay() ) {
666 if ($this->isTrustedFile()) {
670 $type = $this->getMediaType();
671 $mime = $this->getMimeType();
672 #wfDebug("LocalFile::isSafeFile: type= $type, mime= $mime\n");
674 if ( !$type ||
$type === MEDIATYPE_UNKNOWN
) {
675 return false; #unknown type, not trusted
677 if ( in_array( $type, $wgTrustedMediaFormats ) ) {
681 if ( $mime === "unknown/unknown" ) {
682 return false; #unknown type, not trusted
684 if ( in_array( $mime, $wgTrustedMediaFormats) ) {
692 * Returns true if the file is flagged as trusted. Files flagged that way
693 * can be linked to directly, even if that is not allowed for this type of
696 * This is a dummy function right now and always returns false. It could be
697 * implemented to extract a flag from the database. The trusted flag could be
698 * set on upload, if the user has sufficient privileges, to bypass script-
699 * and html-filters. It may even be coupled with cryptographics signatures
704 function isTrustedFile() {
705 #this could be implemented to check a flag in the database,
706 #look for signatures, etc
711 * Returns true if file exists in the repository.
713 * Overridden by LocalFile to avoid unnecessary stat calls.
715 * @return boolean Whether file exists in the repository.
717 public function exists() {
718 return $this->getPath() && $this->repo
->fileExists( $this->path
);
722 * Returns true if file exists in the repository and can be included in a page.
723 * It would be unsafe to include private images, making public thumbnails inadvertently
725 * @return boolean Whether file exists in the repository and is includable.
727 public function isVisible() {
728 return $this->exists();
734 function getTransformScript() {
735 if ( !isset( $this->transformScript
) ) {
736 $this->transformScript
= false;
738 $script = $this->repo
->getThumbScriptUrl();
740 $this->transformScript
= "$script?f=" . urlencode( $this->getName() );
744 return $this->transformScript
;
748 * Get a ThumbnailImage which is the same size as the source
750 * @param $handlerParams array
754 function getUnscaledThumb( $handlerParams = array() ) {
755 $hp =& $handlerParams;
756 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
757 $width = $this->getWidth( $page );
759 return $this->iconThumb();
761 $hp['width'] = $width;
762 return $this->transform( $hp );
766 * Return the file name of a thumbnail with the specified parameters.
767 * Use File::THUMB_FULL_NAME to always get a name like "<params>-<source>".
768 * Otherwise, the format may be "<params>-<source>" or "<params>-thumbnail.<ext>".
770 * @param $params Array: handler-specific parameters
771 * @param $flags integer Bitfield that supports THUMB_* constants
774 public function thumbName( $params, $flags = 0 ) {
775 $name = ( $this->repo
&& !( $flags & self
::THUMB_FULL_NAME
) )
776 ?
$this->repo
->nameForThumb( $this->getName() )
778 return $this->generateThumbName( $name, $params );
782 * Generate a thumbnail file name from a name and specified parameters
784 * @param string $name
785 * @param array $params Parameters which will be passed to MediaHandler::makeParamString
789 public function generateThumbName( $name, $params ) {
790 if ( !$this->getHandler() ) {
793 $extension = $this->getExtension();
794 list( $thumbExt, $thumbMime ) = $this->handler
->getThumbType(
795 $extension, $this->getMimeType(), $params );
796 $thumbName = $this->handler
->makeParamString( $params ) . '-' . $name;
797 if ( $thumbExt != $extension ) {
798 $thumbName .= ".$thumbExt";
804 * Create a thumbnail of the image having the specified width/height.
805 * The thumbnail will not be created if the width is larger than the
806 * image's width. Let the browser do the scaling in this case.
807 * The thumbnail is stored on disk and is only computed if the thumbnail
808 * file does not exist OR if it is older than the image.
811 * Keeps aspect ratio of original image. If both width and height are
812 * specified, the generated image will be no bigger than width x height,
813 * and will also have correct aspect ratio.
815 * @param $width Integer: maximum width of the generated thumbnail
816 * @param $height Integer: maximum height of the image (optional)
820 public function createThumb( $width, $height = -1 ) {
821 $params = array( 'width' => $width );
822 if ( $height != -1 ) {
823 $params['height'] = $height;
825 $thumb = $this->transform( $params );
826 if ( is_null( $thumb ) ||
$thumb->isError() ) {
829 return $thumb->getUrl();
833 * Return either a MediaTransformError or placeholder thumbnail (if $wgIgnoreImageErrors)
835 * @param $thumbPath string Thumbnail storage path
836 * @param $thumbUrl string Thumbnail URL
837 * @param $params Array
838 * @param $flags integer
839 * @return MediaTransformOutput
841 protected function transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags ) {
842 global $wgIgnoreImageErrors;
844 if ( $wgIgnoreImageErrors && !( $flags & self
::RENDER_NOW
) ) {
845 return $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
847 return new MediaTransformError( 'thumbnail_error',
848 $params['width'], 0, wfMessage( 'thumbnail-dest-create' )->text() );
853 * Transform a media file
855 * @param $params Array: an associative array of handler-specific parameters.
856 * Typical keys are width, height and page.
857 * @param $flags Integer: a bitfield, may contain self::RENDER_NOW to force rendering
858 * @return MediaTransformOutput|bool False on failure
860 function transform( $params, $flags = 0 ) {
861 global $wgUseSquid, $wgIgnoreImageErrors, $wgThumbnailEpoch;
863 wfProfileIn( __METHOD__
);
865 if ( !$this->canRender() ) {
866 $thumb = $this->iconThumb();
867 break; // not a bitmap or renderable image, don't try
870 // Get the descriptionUrl to embed it as comment into the thumbnail. Bug 19791.
871 $descriptionUrl = $this->getDescriptionUrl();
872 if ( $descriptionUrl ) {
873 $params['descriptionUrl'] = wfExpandUrl( $descriptionUrl, PROTO_CANONICAL
);
876 $script = $this->getTransformScript();
877 if ( $script && !( $flags & self
::RENDER_NOW
) ) {
878 // Use a script to transform on client request, if possible
879 $thumb = $this->handler
->getScriptedTransform( $this, $script, $params );
885 $normalisedParams = $params;
886 $this->handler
->normaliseParams( $this, $normalisedParams );
888 $thumbName = $this->thumbName( $normalisedParams );
889 $thumbUrl = $this->getThumbUrl( $thumbName );
890 $thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
893 // Defer rendering if a 404 handler is set up...
894 if ( $this->repo
->canTransformVia404() && !( $flags & self
::RENDER_NOW
) ) {
895 wfDebug( __METHOD__
. " transformation deferred." );
896 // XXX: Pass in the storage path even though we are not rendering anything
897 // and the path is supposed to be an FS path. This is due to getScalerType()
898 // getting called on the path and clobbering $thumb->getUrl() if it's false.
899 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
902 // Clean up broken thumbnails as needed
903 $this->migrateThumbFile( $thumbName );
904 // Check if an up-to-date thumbnail already exists...
905 wfDebug( __METHOD__
.": Doing stat for $thumbPath\n" );
906 if ( !( $flags & self
::RENDER_FORCE
) && $this->repo
->fileExists( $thumbPath ) ) {
907 $timestamp = $this->repo
->getFileTimestamp( $thumbPath );
908 if ( $timestamp !== false && $timestamp >= $wgThumbnailEpoch ) {
909 // XXX: Pass in the storage path even though we are not rendering anything
910 // and the path is supposed to be an FS path. This is due to getScalerType()
911 // getting called on the path and clobbering $thumb->getUrl() if it's false.
912 $thumb = $this->handler
->getTransform(
913 $this, $thumbPath, $thumbUrl, $params );
914 $thumb->setStoragePath( $thumbPath );
917 } elseif ( $flags & self
::RENDER_FORCE
) {
918 wfDebug( __METHOD__
. " forcing rendering per flag File::RENDER_FORCE\n" );
922 // If the backend is ready-only, don't keep generating thumbnails
923 // only to return transformation errors, just return the error now.
924 if ( $this->repo
->getReadOnlyReason() !== false ) {
925 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
929 // Create a temp FS file with the same extension and the thumbnail
930 $thumbExt = FileBackend
::extensionFromPath( $thumbPath );
931 $tmpFile = TempFSFile
::factory( 'transform_', $thumbExt );
933 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
936 $tmpThumbPath = $tmpFile->getPath(); // path of 0-byte temp file
938 // Actually render the thumbnail...
939 wfProfileIn( __METHOD__
. '-doTransform' );
940 $thumb = $this->handler
->doTransform( $this, $tmpThumbPath, $thumbUrl, $params );
941 wfProfileOut( __METHOD__
. '-doTransform' );
942 $tmpFile->bind( $thumb ); // keep alive with $thumb
944 if ( !$thumb ) { // bad params?
946 } elseif ( $thumb->isError() ) { // transform error
947 $this->lastError
= $thumb->toText();
948 // Ignore errors if requested
949 if ( $wgIgnoreImageErrors && !( $flags & self
::RENDER_NOW
) ) {
950 $thumb = $this->handler
->getTransform( $this, $tmpThumbPath, $thumbUrl, $params );
952 } elseif ( $this->repo
&& $thumb->hasFile() && !$thumb->fileIsSource() ) {
953 // Copy the thumbnail from the file system into storage...
954 $disposition = $this->getThumbDisposition( $thumbName );
955 $status = $this->repo
->quickImport( $tmpThumbPath, $thumbPath, $disposition );
956 if ( $status->isOK() ) {
957 $thumb->setStoragePath( $thumbPath );
959 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
961 // Give extensions a chance to do something with this thumbnail...
962 wfRunHooks( 'FileTransformed', array( $this, $thumb, $tmpThumbPath, $thumbPath ) );
965 // Purge. Useful in the event of Core -> Squid connection failure or squid
966 // purge collisions from elsewhere during failure. Don't keep triggering for
967 // "thumbs" which have the main image URL though (bug 13776)
969 if ( !$thumb ||
$thumb->isError() ||
$thumb->getUrl() != $this->getURL() ) {
970 SquidUpdate
::purge( array( $thumbUrl ) );
975 wfProfileOut( __METHOD__
);
976 return is_object( $thumb ) ?
$thumb : false;
980 * @param $thumbName string Thumbnail name
981 * @return string Content-Disposition header value
983 function getThumbDisposition( $thumbName ) {
984 $fileName = $this->name
; // file name to suggest
985 $thumbExt = FileBackend
::extensionFromPath( $thumbName );
986 if ( $thumbExt != '' && $thumbExt !== $this->getExtension() ) {
987 $fileName .= ".$thumbExt";
989 return FileBackend
::makeContentDisposition( 'inline', $fileName );
993 * Hook into transform() to allow migration of thumbnail files
995 * Overridden by LocalFile
997 function migrateThumbFile( $thumbName ) {}
1000 * Get a MediaHandler instance for this file
1002 * @return MediaHandler
1004 function getHandler() {
1005 if ( !isset( $this->handler
) ) {
1006 $this->handler
= MediaHandler
::getHandler( $this->getMimeType() );
1008 return $this->handler
;
1012 * Get a ThumbnailImage representing a file type icon
1014 * @return ThumbnailImage
1016 function iconThumb() {
1017 global $wgStylePath, $wgStyleDirectory;
1019 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
1020 foreach ( $try as $icon ) {
1021 $path = '/common/images/icons/' . $icon;
1022 $filepath = $wgStyleDirectory . $path;
1023 if ( file_exists( $filepath ) ) { // always FS
1024 $params = array( 'width' => 120, 'height' => 120 );
1025 return new ThumbnailImage( $this, $wgStylePath . $path, false, $params );
1032 * Get last thumbnailing error.
1035 function getLastError() {
1036 return $this->lastError
;
1040 * Get all thumbnail names previously generated for this file
1042 * Overridden by LocalFile
1045 function getThumbnails() {
1050 * Purge shared caches such as thumbnails and DB data caching
1052 * Overridden by LocalFile
1053 * @param $options Array Options, which include:
1054 * 'forThumbRefresh' : The purging is only to refresh thumbnails
1056 function purgeCache( $options = array() ) {}
1059 * Purge the file description page, but don't go after
1060 * pages using the file. Use when modifying file history
1061 * but not the current data.
1063 function purgeDescription() {
1064 $title = $this->getTitle();
1066 $title->invalidateCache();
1067 $title->purgeSquid();
1072 * Purge metadata and all affected pages when the file is created,
1073 * deleted, or majorly updated.
1075 function purgeEverything() {
1076 // Delete thumbnails and refresh file metadata cache
1077 $this->purgeCache();
1078 $this->purgeDescription();
1080 // Purge cache of all pages using this file
1081 $title = $this->getTitle();
1083 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
1084 $update->doUpdate();
1089 * Return a fragment of the history of file.
1092 * @param $limit integer Limit of rows to return
1093 * @param $start string timestamp Only revisions older than $start will be returned
1094 * @param $end string timestamp Only revisions newer than $end will be returned
1095 * @param $inc bool Include the endpoints of the time range
1099 function getHistory( $limit = null, $start = null, $end = null, $inc=true ) {
1104 * Return the history of this file, line by line. Starts with current version,
1105 * then old versions. Should return an object similar to an image/oldimage
1109 * Overridden in LocalFile
1112 public function nextHistoryLine() {
1117 * Reset the history pointer to the first element of the history.
1118 * Always call this function after using nextHistoryLine() to free db resources
1120 * Overridden in LocalFile.
1122 public function resetHistory() {}
1125 * Get the filename hash component of the directory including trailing slash,
1127 * If the repository is not hashed, returns an empty string.
1131 function getHashPath() {
1132 if ( !isset( $this->hashPath
) ) {
1133 $this->assertRepoDefined();
1134 $this->hashPath
= $this->repo
->getHashPath( $this->getName() );
1136 return $this->hashPath
;
1140 * Get the path of the file relative to the public zone root.
1141 * This function is overriden in OldLocalFile to be like getArchiveRel().
1146 return $this->getHashPath() . $this->getName();
1150 * Get the path of an archived file relative to the public zone root
1152 * @param $suffix bool|string if not false, the name of an archived thumbnail file
1156 function getArchiveRel( $suffix = false ) {
1157 $path = 'archive/' . $this->getHashPath();
1158 if ( $suffix === false ) {
1159 $path = substr( $path, 0, -1 );
1167 * Get the path, relative to the thumbnail zone root, of the
1168 * thumbnail directory or a particular file if $suffix is specified
1170 * @param $suffix bool|string if not false, the name of a thumbnail file
1174 function getThumbRel( $suffix = false ) {
1175 $path = $this->getRel();
1176 if ( $suffix !== false ) {
1177 $path .= '/' . $suffix;
1183 * Get urlencoded path of the file relative to the public zone root.
1184 * This function is overriden in OldLocalFile to be like getArchiveUrl().
1188 function getUrlRel() {
1189 return $this->getHashPath() . rawurlencode( $this->getName() );
1193 * Get the path, relative to the thumbnail zone root, for an archived file's thumbs directory
1194 * or a specific thumb if the $suffix is given.
1196 * @param $archiveName string the timestamped name of an archived image
1197 * @param $suffix bool|string if not false, the name of a thumbnail file
1201 function getArchiveThumbRel( $archiveName, $suffix = false ) {
1202 $path = 'archive/' . $this->getHashPath() . $archiveName . "/";
1203 if ( $suffix === false ) {
1204 $path = substr( $path, 0, -1 );
1212 * Get the path of the archived file.
1214 * @param $suffix bool|string if not false, the name of an archived file.
1218 function getArchivePath( $suffix = false ) {
1219 $this->assertRepoDefined();
1220 return $this->repo
->getZonePath( 'public' ) . '/' . $this->getArchiveRel( $suffix );
1224 * Get the path of an archived file's thumbs, or a particular thumb if $suffix is specified
1226 * @param $archiveName string the timestamped name of an archived image
1227 * @param $suffix bool|string if not false, the name of a thumbnail file
1231 function getArchiveThumbPath( $archiveName, $suffix = false ) {
1232 $this->assertRepoDefined();
1233 return $this->repo
->getZonePath( 'thumb' ) . '/' .
1234 $this->getArchiveThumbRel( $archiveName, $suffix );
1238 * Get the path of the thumbnail directory, or a particular file if $suffix is specified
1240 * @param $suffix bool|string if not false, the name of a thumbnail file
1244 function getThumbPath( $suffix = false ) {
1245 $this->assertRepoDefined();
1246 return $this->repo
->getZonePath( 'thumb' ) . '/' . $this->getThumbRel( $suffix );
1250 * Get the URL of the archive directory, or a particular file if $suffix is specified
1252 * @param $suffix bool|string if not false, the name of an archived file
1256 function getArchiveUrl( $suffix = false ) {
1257 $this->assertRepoDefined();
1258 $ext = $this->getExtension();
1259 $path = $this->repo
->getZoneUrl( 'public', $ext ) . '/archive/' . $this->getHashPath();
1260 if ( $suffix === false ) {
1261 $path = substr( $path, 0, -1 );
1263 $path .= rawurlencode( $suffix );
1269 * Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified
1271 * @param $archiveName string the timestamped name of an archived image
1272 * @param $suffix bool|string if not false, the name of a thumbnail file
1276 function getArchiveThumbUrl( $archiveName, $suffix = false ) {
1277 $this->assertRepoDefined();
1278 $ext = $this->getExtension();
1279 $path = $this->repo
->getZoneUrl( 'thumb', $ext ) . '/archive/' .
1280 $this->getHashPath() . rawurlencode( $archiveName ) . "/";
1281 if ( $suffix === false ) {
1282 $path = substr( $path, 0, -1 );
1284 $path .= rawurlencode( $suffix );
1290 * Get the URL of the thumbnail directory, or a particular file if $suffix is specified
1292 * @param $suffix bool|string if not false, the name of a thumbnail file
1294 * @return string path
1296 function getThumbUrl( $suffix = false ) {
1297 $this->assertRepoDefined();
1298 $ext = $this->getExtension();
1299 $path = $this->repo
->getZoneUrl( 'thumb', $ext ) . '/' . $this->getUrlRel();
1300 if ( $suffix !== false ) {
1301 $path .= '/' . rawurlencode( $suffix );
1307 * Get the public zone virtual URL for a current version source file
1309 * @param $suffix bool|string if not false, the name of a thumbnail file
1313 function getVirtualUrl( $suffix = false ) {
1314 $this->assertRepoDefined();
1315 $path = $this->repo
->getVirtualUrl() . '/public/' . $this->getUrlRel();
1316 if ( $suffix !== false ) {
1317 $path .= '/' . rawurlencode( $suffix );
1323 * Get the public zone virtual URL for an archived version source file
1325 * @param $suffix bool|string if not false, the name of a thumbnail file
1329 function getArchiveVirtualUrl( $suffix = false ) {
1330 $this->assertRepoDefined();
1331 $path = $this->repo
->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
1332 if ( $suffix === false ) {
1333 $path = substr( $path, 0, -1 );
1335 $path .= rawurlencode( $suffix );
1341 * Get the virtual URL for a thumbnail file or directory
1343 * @param $suffix bool|string if not false, the name of a thumbnail file
1347 function getThumbVirtualUrl( $suffix = false ) {
1348 $this->assertRepoDefined();
1349 $path = $this->repo
->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
1350 if ( $suffix !== false ) {
1351 $path .= '/' . rawurlencode( $suffix );
1359 function isHashed() {
1360 $this->assertRepoDefined();
1361 return (bool)$this->repo
->getHashLevels();
1365 * @throws MWException
1367 function readOnlyError() {
1368 throw new MWException( get_class($this) . ': write operations are not supported' );
1372 * Record a file upload in the upload log and the image table
1374 * Overridden by LocalFile
1377 * @param $license string
1378 * @param $copyStatus string
1379 * @param $source string
1380 * @param $watch bool
1382 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1383 $this->readOnlyError();
1387 * Move or copy a file to its public location. If a file exists at the
1388 * destination, move it to an archive. Returns a FileRepoStatus object with
1389 * the archive name in the "value" member on success.
1391 * The archive name should be passed through to recordUpload for database
1394 * Options to $options include:
1395 * - headers : name/value map of HTTP headers to use in response to GET/HEAD requests
1397 * @param $srcPath String: local filesystem path to the source image
1398 * @param $flags Integer: a bitwise combination of:
1399 * File::DELETE_SOURCE Delete the source file, i.e. move
1401 * @param $options Array Optional additional parameters
1402 * @return FileRepoStatus object. On success, the value member contains the
1403 * archive name, or an empty string if it was a new file.
1406 * Overridden by LocalFile
1408 function publish( $srcPath, $flags = 0, array $options = array() ) {
1409 $this->readOnlyError();
1415 function formatMetadata() {
1416 if ( !$this->getHandler() ) {
1419 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
1423 * Returns true if the file comes from the local file repository.
1427 function isLocal() {
1428 return $this->repo
&& $this->repo
->isLocal();
1432 * Returns the name of the repository.
1436 function getRepoName() {
1437 return $this->repo ?
$this->repo
->getName() : 'unknown';
1441 * Returns the repository
1443 * @return FileRepo|bool
1445 function getRepo() {
1450 * Returns true if the image is an old version
1460 * Is this file a "deleted" file in a private archive?
1467 function isDeleted( $field ) {
1472 * Return the deletion bitfield
1476 function getVisibility() {
1481 * Was this file ever deleted from the wiki?
1485 function wasDeleted() {
1486 $title = $this->getTitle();
1487 return $title && $title->isDeletedQuick();
1491 * Move file to the new title
1493 * Move current, old version and all thumbnails
1494 * to the new filename. Old file is deleted.
1496 * Cache purging is done; checks for validity
1497 * and logging are caller's responsibility
1499 * @param $target Title New file name
1500 * @return FileRepoStatus object.
1502 function move( $target ) {
1503 $this->readOnlyError();
1507 * Delete all versions of the file.
1509 * Moves the files into an archive directory (or deletes them)
1510 * and removes the database rows.
1512 * Cache purging is done; logging is caller's responsibility.
1514 * @param $reason String
1515 * @param $suppress Boolean: hide content from sysops?
1516 * @return bool on success, false on some kind of failure
1518 * Overridden by LocalFile
1520 function delete( $reason, $suppress = false ) {
1521 $this->readOnlyError();
1525 * Restore all or specified deleted revisions to the given file.
1526 * Permissions and logging are left to the caller.
1528 * May throw database exceptions on error.
1530 * @param $versions array set of record ids of deleted items to restore,
1531 * or empty to restore all revisions.
1532 * @param $unsuppress bool remove restrictions on content upon restoration?
1533 * @return int|bool the number of file revisions restored if successful,
1534 * or false on failure
1536 * Overridden by LocalFile
1538 function restore( $versions = array(), $unsuppress = false ) {
1539 $this->readOnlyError();
1543 * Returns 'true' if this file is a type which supports multiple pages,
1544 * e.g. DJVU or PDF. Note that this may be true even if the file in
1545 * question only has a single page.
1549 function isMultipage() {
1550 return $this->getHandler() && $this->handler
->isMultiPage( $this );
1554 * Returns the number of pages of a multipage document, or false for
1555 * documents which aren't multipage documents
1559 function pageCount() {
1560 if ( !isset( $this->pageCount
) ) {
1561 if ( $this->getHandler() && $this->handler
->isMultiPage( $this ) ) {
1562 $this->pageCount
= $this->handler
->pageCount( $this );
1564 $this->pageCount
= false;
1567 return $this->pageCount
;
1571 * Calculate the height of a thumbnail using the source and destination width
1579 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1580 // Exact integer multiply followed by division
1581 if ( $srcWidth == 0 ) {
1584 return round( $srcHeight * $dstWidth / $srcWidth );
1589 * Get an image size array like that returned by getImageSize(), or false if it
1590 * can't be determined.
1592 * @param $fileName String: The filename
1595 function getImageSize( $fileName ) {
1596 if ( !$this->getHandler() ) {
1599 return $this->handler
->getImageSize( $this, $fileName );
1603 * Get the URL of the image description page. May return false if it is
1604 * unknown or not applicable.
1608 function getDescriptionUrl() {
1609 if ( $this->repo
) {
1610 return $this->repo
->getDescriptionUrl( $this->getName() );
1617 * Get the HTML text of the description page, if available
1621 function getDescriptionText() {
1622 global $wgMemc, $wgLang;
1623 if ( !$this->repo ||
!$this->repo
->fetchDescription
) {
1626 $renderUrl = $this->repo
->getDescriptionRenderUrl( $this->getName(), $wgLang->getCode() );
1628 if ( $this->repo
->descriptionCacheExpiry
> 0 ) {
1629 wfDebug("Attempting to get the description from cache...");
1630 $key = $this->repo
->getLocalCacheKey( 'RemoteFileDescription', 'url', $wgLang->getCode(),
1632 $obj = $wgMemc->get($key);
1634 wfDebug("success!\n");
1639 wfDebug( "Fetching shared description from $renderUrl\n" );
1640 $res = Http
::get( $renderUrl );
1641 if ( $res && $this->repo
->descriptionCacheExpiry
> 0 ) {
1642 $wgMemc->set( $key, $res, $this->repo
->descriptionCacheExpiry
);
1651 * Get description of file revision
1654 * @param $audience Integer: one of:
1655 * File::FOR_PUBLIC to be displayed to all users
1656 * File::FOR_THIS_USER to be displayed to the given user
1657 * File::RAW get the description regardless of permissions
1658 * @param $user User object to check for, only if FOR_THIS_USER is passed
1659 * to the $audience parameter
1662 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1667 * Get the 14-character timestamp of the file upload
1669 * @return string|bool TS_MW timestamp or false on failure
1671 function getTimestamp() {
1672 $this->assertRepoDefined();
1673 return $this->repo
->getFileTimestamp( $this->getPath() );
1677 * Get the SHA-1 base 36 hash of the file
1681 function getSha1() {
1682 $this->assertRepoDefined();
1683 return $this->repo
->getFileSha1( $this->getPath() );
1687 * Get the deletion archive key, "<sha1>.<ext>"
1691 function getStorageKey() {
1692 $hash = $this->getSha1();
1696 $ext = $this->getExtension();
1697 $dotExt = $ext === '' ?
'' : ".$ext";
1698 return $hash . $dotExt;
1702 * Determine if the current user is allowed to view a particular
1703 * field of this file, if it's marked as deleted.
1705 * @param $field Integer
1706 * @param $user User object to check, or null to use $wgUser
1709 function userCan( $field, User
$user = null ) {
1714 * Get an associative array containing information about a file in the local filesystem.
1716 * @param $path String: absolute local filesystem path
1717 * @param $ext Mixed: the file extension, or true to extract it from the filename.
1718 * Set it to false to ignore the extension.
1722 static function getPropsFromPath( $path, $ext = true ) {
1723 wfDebug( __METHOD__
.": Getting file info for $path\n" );
1724 wfDeprecated( __METHOD__
, '1.19' );
1726 $fsFile = new FSFile( $path );
1727 return $fsFile->getProps();
1731 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1732 * encoding, zero padded to 31 digits.
1734 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1737 * @param $path string
1739 * @return bool|string False on failure
1741 static function sha1Base36( $path ) {
1742 wfDeprecated( __METHOD__
, '1.19' );
1744 $fsFile = new FSFile( $path );
1745 return $fsFile->getSha1Base36();
1749 * @return Array HTTP header name/value map to use for HEAD/GET request responses
1751 function getStreamHeaders() {
1752 $handler = $this->getHandler();
1754 return $handler->getStreamHeaders( $this->getMetadata() );
1763 function getLongDesc() {
1764 $handler = $this->getHandler();
1766 return $handler->getLongDesc( $this );
1768 return MediaHandler
::getGeneralLongDesc( $this );
1775 function getShortDesc() {
1776 $handler = $this->getHandler();
1778 return $handler->getShortDesc( $this );
1780 return MediaHandler
::getGeneralShortDesc( $this );
1787 function getDimensionsString() {
1788 $handler = $this->getHandler();
1790 return $handler->getDimensionsString( $this );
1799 function getRedirected() {
1800 return $this->redirected
;
1804 * @return Title|null
1806 function getRedirectedTitle() {
1807 if ( $this->redirected
) {
1808 if ( !$this->redirectTitle
) {
1809 $this->redirectTitle
= Title
::makeTitle( NS_FILE
, $this->redirected
);
1811 return $this->redirectTitle
;
1820 function redirectedFrom( $from ) {
1821 $this->redirected
= $from;
1827 function isMissing() {
1832 * Check if this file object is small and can be cached
1835 public function isCacheable() {
1840 * Assert that $this->repo is set to a valid FileRepo instance
1841 * @throws MWException
1843 protected function assertRepoDefined() {
1844 if ( !( $this->repo
instanceof $this->repoClass
) ) {
1845 throw new MWException( "A {$this->repoClass} object is not set for this File.\n" );
1850 * Assert that $this->title is set to a Title
1851 * @throws MWException
1853 protected function assertTitleDefined() {
1854 if ( !( $this->title
instanceof Title
) ) {
1855 throw new MWException( "A Title object is not set for this File.\n" );