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
104 var $lastError, $redirected, $redirectedTitle;
107 * @var FSFile|bool False if undefined
119 protected $url, $extension, $name, $path, $hashPath, $pageCount, $transformScript;
121 protected $redirectTitle;
126 protected $canRender, $isSafeFile;
129 * @var string Required Repository class type
131 protected $repoClass = 'FileRepo';
134 * Call this constructor from child classes.
136 * Both $title and $repo are optional, though some functions
137 * may return false or throw exceptions if they are not set.
138 * Most subclasses will want to call assertRepoDefined() here.
140 * @param $title Title|string|bool
141 * @param $repo FileRepo|bool
143 function __construct( $title, $repo ) {
144 if ( $title !== false ) { // subclasses may not use MW titles
145 $title = self
::normalizeTitle( $title, 'exception' );
147 $this->title
= $title;
152 * Given a string or Title object return either a
153 * valid Title object with namespace NS_FILE or null
155 * @param $title Title|string
156 * @param string|bool $exception Use 'exception' to throw an error on bad titles
157 * @throws MWException
160 static function normalizeTitle( $title, $exception = false ) {
162 if ( $ret instanceof Title
) {
163 # Normalize NS_MEDIA -> NS_FILE
164 if ( $ret->getNamespace() == NS_MEDIA
) {
165 $ret = Title
::makeTitleSafe( NS_FILE
, $ret->getDBkey() );
166 # Sanity check the title namespace
167 } elseif ( $ret->getNamespace() !== NS_FILE
) {
171 # Convert strings to Title objects
172 $ret = Title
::makeTitleSafe( NS_FILE
, (string)$ret );
174 if ( !$ret && $exception !== false ) {
175 throw new MWException( "`$title` is not a valid file title." );
180 function __get( $name ) {
181 $function = array( $this, 'get' . ucfirst( $name ) );
182 if ( !is_callable( $function ) ) {
185 $this->$name = call_user_func( $function );
191 * Normalize a file extension to the common form, and ensure it's clean.
192 * Extensions with non-alphanumeric characters will be discarded.
194 * @param string $ext (without the .)
197 static function normalizeExtension( $ext ) {
198 $lower = strtolower( $ext );
205 if ( isset( $squish[$lower] ) ) {
206 return $squish[$lower];
207 } elseif ( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
215 * Checks if file extensions are compatible
217 * @param $old File Old file
218 * @param string $new New name
222 static function checkExtensionCompatibility( File
$old, $new ) {
223 $oldMime = $old->getMimeType();
224 $n = strrpos( $new, '.' );
225 $newExt = self
::normalizeExtension( $n ?
substr( $new, $n +
1 ) : '' );
226 $mimeMagic = MimeMagic
::singleton();
227 return $mimeMagic->isMatchingExtension( $newExt, $oldMime );
231 * Upgrade the database row if there is one
232 * Called by ImagePage
235 function upgradeRow() {}
238 * Split an internet media type into its two components; if not
239 * a two-part name, set the minor type to 'unknown'.
241 * @param string $mime "text/html" etc
242 * @return array ("text", "html") etc
244 public static function splitMime( $mime ) {
245 if ( strpos( $mime, '/' ) !== false ) {
246 return explode( '/', $mime, 2 );
248 return array( $mime, 'unknown' );
253 * Callback for usort() to do file sorts by name
258 * @return Integer: result of name comparison
260 public static function compare( File
$a, File
$b ) {
261 return strcmp( $a->getName(), $b->getName() );
265 * Return the name of this file
269 public function getName() {
270 if ( !isset( $this->name
) ) {
271 $this->assertRepoDefined();
272 $this->name
= $this->repo
->getNameFromTitle( $this->title
);
278 * Get the file extension, e.g. "svg"
282 function getExtension() {
283 if ( !isset( $this->extension
) ) {
284 $n = strrpos( $this->getName(), '.' );
285 $this->extension
= self
::normalizeExtension(
286 $n ?
substr( $this->getName(), $n +
1 ) : '' );
288 return $this->extension
;
292 * Return the associated title object
296 public function getTitle() {
301 * Return the title used to find this file
305 public function getOriginalTitle() {
306 if ( $this->redirected
) {
307 return $this->getRedirectedTitle();
313 * Return the URL of the file
317 public function getUrl() {
318 if ( !isset( $this->url
) ) {
319 $this->assertRepoDefined();
320 $ext = $this->getExtension();
321 $this->url
= $this->repo
->getZoneUrl( 'public', $ext ) . '/' . $this->getUrlRel();
327 * Return a fully-qualified URL to the file.
328 * Upload URL paths _may or may not_ be fully qualified, so
329 * we check. Local paths are assumed to belong on $wgServer.
333 public function getFullUrl() {
334 return wfExpandUrl( $this->getUrl(), PROTO_RELATIVE
);
340 public function getCanonicalUrl() {
341 return wfExpandUrl( $this->getUrl(), PROTO_CANONICAL
);
347 function getViewURL() {
348 if ( $this->mustRender() ) {
349 if ( $this->canRender() ) {
350 return $this->createThumb( $this->getWidth() );
352 wfDebug( __METHOD__
. ': supposed to render ' . $this->getName() .
353 ' (' . $this->getMimeType() . "), but can't!\n" );
354 return $this->getURL(); #hm... return NULL?
357 return $this->getURL();
362 * Return the storage path to the file. Note that this does
363 * not mean that a file actually exists under that location.
365 * This path depends on whether directory hashing is active or not,
366 * i.e. whether the files are all found in the same directory,
367 * or in hashed paths like /images/3/3c.
369 * Most callers don't check the return value, but ForeignAPIFile::getPath
372 * @return string|bool ForeignAPIFile::getPath can return false
374 public function getPath() {
375 if ( !isset( $this->path
) ) {
376 $this->assertRepoDefined();
377 $this->path
= $this->repo
->getZonePath( 'public' ) . '/' . $this->getRel();
383 * Get an FS copy or original of this file and return the path.
384 * Returns false on failure. Callers must not alter the file.
385 * Temporary files are cleared automatically.
387 * @return string|bool False on failure
389 public function getLocalRefPath() {
390 $this->assertRepoDefined();
391 if ( !isset( $this->fsFile
) ) {
392 $this->fsFile
= $this->repo
->getLocalReference( $this->getPath() );
393 if ( !$this->fsFile
) {
394 $this->fsFile
= false; // null => false; cache negative hits
397 return ( $this->fsFile
)
398 ?
$this->fsFile
->getPath()
403 * Return the width of the image. Returns false if the width is unknown
407 * Overridden by LocalFile, UnregisteredLocalFile
413 public function getWidth( $page = 1 ) {
418 * Return the height of the image. Returns false if the height is unknown
422 * Overridden by LocalFile, UnregisteredLocalFile
426 * @return bool|number False on failure
428 public function getHeight( $page = 1 ) {
433 * Returns ID or name of user who uploaded the file
436 * @param string $type 'text' or 'id'
440 public function getUser( $type = 'text' ) {
445 * Get the duration of a media file in seconds
449 public function getLength() {
450 $handler = $this->getHandler();
452 return $handler->getLength( $this );
459 * Return true if the file is vectorized
463 public function isVectorized() {
464 $handler = $this->getHandler();
466 return $handler->isVectorized( $this );
473 * Will the thumbnail be animated if one would expect it to be.
475 * Currently used to add a warning to the image description page
477 * @return bool false if the main image is both animated
478 * and the thumbnail is not. In all other cases must return
479 * true. If image is not renderable whatsoever, should
482 public function canAnimateThumbIfAppropriate() {
483 $handler = $this->getHandler();
485 // We cannot handle image whatsoever, thus
486 // one would not expect it to be animated
490 if ( $this->allowInlineDisplay()
491 && $handler->isAnimatedImage( $this )
492 && !$handler->canAnimateThumbnail( $this )
494 // Image is animated, but thumbnail isn't.
495 // This is unexpected to the user.
498 // Image is not animated, so one would
499 // not expect thumb to be
506 * Get handler-specific metadata
507 * Overridden by LocalFile, UnregisteredLocalFile
511 public function getMetadata() {
516 * get versioned metadata
518 * @param $metadata Mixed Array or String of (serialized) metadata
519 * @param $version integer version number.
520 * @return Array containing metadata, or what was passed to it on fail (unserializing if not array)
522 public function convertMetadataVersion( $metadata, $version ) {
523 $handler = $this->getHandler();
524 if ( !is_array( $metadata ) ) {
525 // Just to make the return type consistent
526 $metadata = unserialize( $metadata );
529 return $handler->convertMetadataVersion( $metadata, $version );
536 * Return the bit depth of the file
537 * Overridden by LocalFile
541 public function getBitDepth() {
546 * Return the size of the image file, in bytes
547 * Overridden by LocalFile, UnregisteredLocalFile
551 public function getSize() {
556 * Returns the mime type of the file.
557 * Overridden by LocalFile, UnregisteredLocalFile
562 function getMimeType() {
563 return 'unknown/unknown';
567 * Return the type of the media in the file.
568 * Use the value returned by this function with the MEDIATYPE_xxx constants.
569 * Overridden by LocalFile,
573 function getMediaType() {
574 return MEDIATYPE_UNKNOWN
;
578 * Checks if the output of transform() for this file is likely
579 * to be valid. If this is false, various user elements will
580 * display a placeholder instead.
582 * Currently, this checks if the file is an image format
583 * that can be converted to a format
584 * supported by all browsers (namely GIF, PNG and JPEG),
585 * or if it is an SVG image and SVG conversion is enabled.
589 function canRender() {
590 if ( !isset( $this->canRender
) ) {
591 $this->canRender
= $this->getHandler() && $this->handler
->canRender( $this );
593 return $this->canRender
;
597 * Accessor for __get()
600 protected function getCanRender() {
601 return $this->canRender();
605 * Return true if the file is of a type that can't be directly
606 * rendered by typical browsers and needs to be re-rasterized.
608 * This returns true for everything but the bitmap types
609 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
610 * also return true for any non-image formats.
614 function mustRender() {
615 return $this->getHandler() && $this->handler
->mustRender( $this );
619 * Alias for canRender()
623 function allowInlineDisplay() {
624 return $this->canRender();
628 * Determines if this media file is in a format that is unlikely to
629 * contain viruses or malicious content. It uses the global
630 * $wgTrustedMediaFormats list to determine if the file is safe.
632 * This is used to show a warning on the description page of non-safe files.
633 * It may also be used to disallow direct [[media:...]] links to such files.
635 * Note that this function will always return true if allowInlineDisplay()
636 * or isTrustedFile() is true for this file.
640 function isSafeFile() {
641 if ( !isset( $this->isSafeFile
) ) {
642 $this->isSafeFile
= $this->_getIsSafeFile();
644 return $this->isSafeFile
;
648 * Accessor for __get()
652 protected function getIsSafeFile() {
653 return $this->isSafeFile();
661 protected function _getIsSafeFile() {
662 global $wgTrustedMediaFormats;
664 if ( $this->allowInlineDisplay() ) {
667 if ( $this->isTrustedFile() ) {
671 $type = $this->getMediaType();
672 $mime = $this->getMimeType();
673 #wfDebug( "LocalFile::isSafeFile: type= $type, mime= $mime\n" );
675 if ( !$type ||
$type === MEDIATYPE_UNKNOWN
) {
676 return false; #unknown type, not trusted
678 if ( in_array( $type, $wgTrustedMediaFormats ) ) {
682 if ( $mime === "unknown/unknown" ) {
683 return false; #unknown type, not trusted
685 if ( in_array( $mime, $wgTrustedMediaFormats ) ) {
693 * Returns true if the file is flagged as trusted. Files flagged that way
694 * can be linked to directly, even if that is not allowed for this type of
697 * This is a dummy function right now and always returns false. It could be
698 * implemented to extract a flag from the database. The trusted flag could be
699 * set on upload, if the user has sufficient privileges, to bypass script-
700 * and html-filters. It may even be coupled with cryptographics signatures
705 function isTrustedFile() {
706 #this could be implemented to check a flag in the database,
707 #look for signatures, etc
712 * Returns true if file exists in the repository.
714 * Overridden by LocalFile to avoid unnecessary stat calls.
716 * @return boolean Whether file exists in the repository.
718 public function exists() {
719 return $this->getPath() && $this->repo
->fileExists( $this->path
);
723 * Returns true if file exists in the repository and can be included in a page.
724 * It would be unsafe to include private images, making public thumbnails inadvertently
726 * @return boolean Whether file exists in the repository and is includable.
728 public function isVisible() {
729 return $this->exists();
735 function getTransformScript() {
736 if ( !isset( $this->transformScript
) ) {
737 $this->transformScript
= false;
739 $script = $this->repo
->getThumbScriptUrl();
741 $this->transformScript
= wfAppendQuery( $script, array( 'f' => $this->getName() ) );
745 return $this->transformScript
;
749 * Get a ThumbnailImage which is the same size as the source
751 * @param $handlerParams array
755 function getUnscaledThumb( $handlerParams = array() ) {
756 $hp =& $handlerParams;
757 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
758 $width = $this->getWidth( $page );
760 return $this->iconThumb();
762 $hp['width'] = $width;
763 return $this->transform( $hp );
767 * Return the file name of a thumbnail with the specified parameters.
768 * Use File::THUMB_FULL_NAME to always get a name like "<params>-<source>".
769 * Otherwise, the format may be "<params>-<source>" or "<params>-thumbnail.<ext>".
771 * @param array $params handler-specific parameters
772 * @param $flags integer Bitfield that supports THUMB_* constants
775 public function thumbName( $params, $flags = 0 ) {
776 $name = ( $this->repo
&& !( $flags & self
::THUMB_FULL_NAME
) )
777 ?
$this->repo
->nameForThumb( $this->getName() )
779 return $this->generateThumbName( $name, $params );
783 * Generate a thumbnail file name from a name and specified parameters
785 * @param string $name
786 * @param array $params Parameters which will be passed to MediaHandler::makeParamString
790 public function generateThumbName( $name, $params ) {
791 if ( !$this->getHandler() ) {
794 $extension = $this->getExtension();
795 list( $thumbExt, $thumbMime ) = $this->handler
->getThumbType(
796 $extension, $this->getMimeType(), $params );
797 $thumbName = $this->handler
->makeParamString( $params ) . '-' . $name;
798 if ( $thumbExt != $extension ) {
799 $thumbName .= ".$thumbExt";
805 * Create a thumbnail of the image having the specified width/height.
806 * The thumbnail will not be created if the width is larger than the
807 * image's width. Let the browser do the scaling in this case.
808 * The thumbnail is stored on disk and is only computed if the thumbnail
809 * file does not exist OR if it is older than the image.
812 * Keeps aspect ratio of original image. If both width and height are
813 * specified, the generated image will be no bigger than width x height,
814 * and will also have correct aspect ratio.
816 * @param $width Integer: maximum width of the generated thumbnail
817 * @param $height Integer: maximum height of the image (optional)
821 public function createThumb( $width, $height = -1 ) {
822 $params = array( 'width' => $width );
823 if ( $height != -1 ) {
824 $params['height'] = $height;
826 $thumb = $this->transform( $params );
827 if ( is_null( $thumb ) ||
$thumb->isError() ) {
830 return $thumb->getUrl();
834 * Return either a MediaTransformError or placeholder thumbnail (if $wgIgnoreImageErrors)
836 * @param string $thumbPath Thumbnail storage path
837 * @param string $thumbUrl Thumbnail URL
838 * @param $params Array
839 * @param $flags integer
840 * @return MediaTransformOutput
842 protected function transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags ) {
843 global $wgIgnoreImageErrors;
845 $handler = $this->getHandler();
846 if ( $handler && $wgIgnoreImageErrors && !( $flags & self
::RENDER_NOW
) ) {
847 return $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
849 return new MediaTransformError( 'thumbnail_error',
850 $params['width'], 0, wfMessage( 'thumbnail-dest-create' )->text() );
855 * Transform a media file
857 * @param array $params an associative array of handler-specific parameters.
858 * Typical keys are width, height and page.
859 * @param $flags Integer: a bitfield, may contain self::RENDER_NOW to force rendering
860 * @return MediaTransformOutput|bool False on failure
862 function transform( $params, $flags = 0 ) {
863 global $wgUseSquid, $wgIgnoreImageErrors, $wgThumbnailEpoch;
865 wfProfileIn( __METHOD__
);
867 if ( !$this->canRender() ) {
868 $thumb = $this->iconThumb();
869 break; // not a bitmap or renderable image, don't try
872 // Get the descriptionUrl to embed it as comment into the thumbnail. Bug 19791.
873 $descriptionUrl = $this->getDescriptionUrl();
874 if ( $descriptionUrl ) {
875 $params['descriptionUrl'] = wfExpandUrl( $descriptionUrl, PROTO_CANONICAL
);
878 $handler = $this->getHandler();
879 $script = $this->getTransformScript();
880 if ( $script && !( $flags & self
::RENDER_NOW
) ) {
881 // Use a script to transform on client request, if possible
882 $thumb = $handler->getScriptedTransform( $this, $script, $params );
888 $normalisedParams = $params;
889 $handler->normaliseParams( $this, $normalisedParams );
891 $thumbName = $this->thumbName( $normalisedParams );
892 $thumbUrl = $this->getThumbUrl( $thumbName );
893 $thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
896 // Defer rendering if a 404 handler is set up...
897 if ( $this->repo
->canTransformVia404() && !( $flags & self
::RENDER_NOW
) ) {
898 wfDebug( __METHOD__
. " transformation deferred." );
899 // XXX: Pass in the storage path even though we are not rendering anything
900 // and the path is supposed to be an FS path. This is due to getScalerType()
901 // getting called on the path and clobbering $thumb->getUrl() if it's false.
902 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
905 // Clean up broken thumbnails as needed
906 $this->migrateThumbFile( $thumbName );
907 // Check if an up-to-date thumbnail already exists...
908 wfDebug( __METHOD__
. ": Doing stat for $thumbPath\n" );
909 if ( !( $flags & self
::RENDER_FORCE
) && $this->repo
->fileExists( $thumbPath ) ) {
910 $timestamp = $this->repo
->getFileTimestamp( $thumbPath );
911 if ( $timestamp !== false && $timestamp >= $wgThumbnailEpoch ) {
912 // XXX: Pass in the storage path even though we are not rendering anything
913 // and the path is supposed to be an FS path. This is due to getScalerType()
914 // getting called on the path and clobbering $thumb->getUrl() if it's false.
915 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
916 $thumb->setStoragePath( $thumbPath );
919 } elseif ( $flags & self
::RENDER_FORCE
) {
920 wfDebug( __METHOD__
. " forcing rendering per flag File::RENDER_FORCE\n" );
924 // If the backend is ready-only, don't keep generating thumbnails
925 // only to return transformation errors, just return the error now.
926 if ( $this->repo
->getReadOnlyReason() !== false ) {
927 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
931 // Create a temp FS file with the same extension and the thumbnail
932 $thumbExt = FileBackend
::extensionFromPath( $thumbPath );
933 $tmpFile = TempFSFile
::factory( 'transform_', $thumbExt );
935 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
938 $tmpThumbPath = $tmpFile->getPath(); // path of 0-byte temp file
940 // Actually render the thumbnail...
941 wfProfileIn( __METHOD__
. '-doTransform' );
942 $thumb = $handler->doTransform( $this, $tmpThumbPath, $thumbUrl, $params );
943 wfProfileOut( __METHOD__
. '-doTransform' );
944 $tmpFile->bind( $thumb ); // keep alive with $thumb
946 if ( !$thumb ) { // bad params?
948 } elseif ( $thumb->isError() ) { // transform error
949 $this->lastError
= $thumb->toText();
950 // Ignore errors if requested
951 if ( $wgIgnoreImageErrors && !( $flags & self
::RENDER_NOW
) ) {
952 $thumb = $handler->getTransform( $this, $tmpThumbPath, $thumbUrl, $params );
954 } elseif ( $this->repo
&& $thumb->hasFile() && !$thumb->fileIsSource() ) {
955 // Copy the thumbnail from the file system into storage...
956 $disposition = $this->getThumbDisposition( $thumbName );
957 $status = $this->repo
->quickImport( $tmpThumbPath, $thumbPath, $disposition );
958 if ( $status->isOK() ) {
959 $thumb->setStoragePath( $thumbPath );
961 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
963 // Give extensions a chance to do something with this thumbnail...
964 wfRunHooks( 'FileTransformed', array( $this, $thumb, $tmpThumbPath, $thumbPath ) );
967 // Purge. Useful in the event of Core -> Squid connection failure or squid
968 // purge collisions from elsewhere during failure. Don't keep triggering for
969 // "thumbs" which have the main image URL though (bug 13776)
971 if ( !$thumb ||
$thumb->isError() ||
$thumb->getUrl() != $this->getURL() ) {
972 SquidUpdate
::purge( array( $thumbUrl ) );
977 wfProfileOut( __METHOD__
);
978 return is_object( $thumb ) ?
$thumb : false;
982 * @param string $thumbName Thumbnail name
983 * @return string Content-Disposition header value
985 function getThumbDisposition( $thumbName ) {
986 $fileName = $this->name
; // file name to suggest
987 $thumbExt = FileBackend
::extensionFromPath( $thumbName );
988 if ( $thumbExt != '' && $thumbExt !== $this->getExtension() ) {
989 $fileName .= ".$thumbExt";
991 return FileBackend
::makeContentDisposition( 'inline', $fileName );
995 * Hook into transform() to allow migration of thumbnail files
997 * Overridden by LocalFile
999 function migrateThumbFile( $thumbName ) {}
1002 * Get a MediaHandler instance for this file
1004 * @return MediaHandler|boolean Registered MediaHandler for file's mime type or false if none found
1006 function getHandler() {
1007 if ( !isset( $this->handler
) ) {
1008 $this->handler
= MediaHandler
::getHandler( $this->getMimeType() );
1010 return $this->handler
;
1014 * Get a ThumbnailImage representing a file type icon
1016 * @return ThumbnailImage
1018 function iconThumb() {
1019 global $wgStylePath, $wgStyleDirectory;
1021 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
1022 foreach ( $try as $icon ) {
1023 $path = '/common/images/icons/' . $icon;
1024 $filepath = $wgStyleDirectory . $path;
1025 if ( file_exists( $filepath ) ) { // always FS
1026 $params = array( 'width' => 120, 'height' => 120 );
1027 return new ThumbnailImage( $this, $wgStylePath . $path, false, $params );
1034 * Get last thumbnailing error.
1037 function getLastError() {
1038 return $this->lastError
;
1042 * Get all thumbnail names previously generated for this file
1044 * Overridden by LocalFile
1047 function getThumbnails() {
1052 * Purge shared caches such as thumbnails and DB data caching
1054 * Overridden by LocalFile
1055 * @param array $options Options, which include:
1056 * 'forThumbRefresh' : The purging is only to refresh thumbnails
1058 function purgeCache( $options = array() ) {}
1061 * Purge the file description page, but don't go after
1062 * pages using the file. Use when modifying file history
1063 * but not the current data.
1065 function purgeDescription() {
1066 $title = $this->getTitle();
1068 $title->invalidateCache();
1069 $title->purgeSquid();
1074 * Purge metadata and all affected pages when the file is created,
1075 * deleted, or majorly updated.
1077 function purgeEverything() {
1078 // Delete thumbnails and refresh file metadata cache
1079 $this->purgeCache();
1080 $this->purgeDescription();
1082 // Purge cache of all pages using this file
1083 $title = $this->getTitle();
1085 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
1086 $update->doUpdate();
1091 * Return a fragment of the history of file.
1094 * @param $limit integer Limit of rows to return
1095 * @param string $start timestamp Only revisions older than $start will be returned
1096 * @param string $end timestamp Only revisions newer than $end will be returned
1097 * @param bool $inc Include the endpoints of the time range
1101 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1106 * Return the history of this file, line by line. Starts with current version,
1107 * then old versions. Should return an object similar to an image/oldimage
1111 * Overridden in LocalFile
1114 public function nextHistoryLine() {
1119 * Reset the history pointer to the first element of the history.
1120 * Always call this function after using nextHistoryLine() to free db resources
1122 * Overridden in LocalFile.
1124 public function resetHistory() {}
1127 * Get the filename hash component of the directory including trailing slash,
1129 * If the repository is not hashed, returns an empty string.
1133 function getHashPath() {
1134 if ( !isset( $this->hashPath
) ) {
1135 $this->assertRepoDefined();
1136 $this->hashPath
= $this->repo
->getHashPath( $this->getName() );
1138 return $this->hashPath
;
1142 * Get the path of the file relative to the public zone root.
1143 * This function is overriden in OldLocalFile to be like getArchiveRel().
1148 return $this->getHashPath() . $this->getName();
1152 * Get the path of an archived file relative to the public zone root
1154 * @param bool|string $suffix if not false, the name of an archived thumbnail file
1158 function getArchiveRel( $suffix = false ) {
1159 $path = 'archive/' . $this->getHashPath();
1160 if ( $suffix === false ) {
1161 $path = substr( $path, 0, -1 );
1169 * Get the path, relative to the thumbnail zone root, of the
1170 * thumbnail directory or a particular file if $suffix is specified
1172 * @param bool|string $suffix if not false, the name of a thumbnail file
1176 function getThumbRel( $suffix = false ) {
1177 $path = $this->getRel();
1178 if ( $suffix !== false ) {
1179 $path .= '/' . $suffix;
1185 * Get urlencoded path of the file relative to the public zone root.
1186 * This function is overriden in OldLocalFile to be like getArchiveUrl().
1190 function getUrlRel() {
1191 return $this->getHashPath() . rawurlencode( $this->getName() );
1195 * Get the path, relative to the thumbnail zone root, for an archived file's thumbs directory
1196 * or a specific thumb if the $suffix is given.
1198 * @param string $archiveName the timestamped name of an archived image
1199 * @param bool|string $suffix if not false, the name of a thumbnail file
1203 function getArchiveThumbRel( $archiveName, $suffix = false ) {
1204 $path = 'archive/' . $this->getHashPath() . $archiveName . "/";
1205 if ( $suffix === false ) {
1206 $path = substr( $path, 0, -1 );
1214 * Get the path of the archived file.
1216 * @param bool|string $suffix if not false, the name of an archived file.
1220 function getArchivePath( $suffix = false ) {
1221 $this->assertRepoDefined();
1222 return $this->repo
->getZonePath( 'public' ) . '/' . $this->getArchiveRel( $suffix );
1226 * Get the path of an archived file's thumbs, or a particular thumb if $suffix is specified
1228 * @param string $archiveName the timestamped name of an archived image
1229 * @param bool|string $suffix if not false, the name of a thumbnail file
1233 function getArchiveThumbPath( $archiveName, $suffix = false ) {
1234 $this->assertRepoDefined();
1235 return $this->repo
->getZonePath( 'thumb' ) . '/' .
1236 $this->getArchiveThumbRel( $archiveName, $suffix );
1240 * Get the path of the thumbnail directory, or a particular file if $suffix is specified
1242 * @param bool|string $suffix if not false, the name of a thumbnail file
1246 function getThumbPath( $suffix = false ) {
1247 $this->assertRepoDefined();
1248 return $this->repo
->getZonePath( 'thumb' ) . '/' . $this->getThumbRel( $suffix );
1252 * Get the path of the transcoded directory, or a particular file if $suffix is specified
1254 * @param bool|string $suffix if not false, the name of a media file
1258 function getTranscodedPath( $suffix = false ) {
1259 $this->assertRepoDefined();
1260 return $this->repo
->getZonePath( 'transcoded' ) . '/' . $this->getThumbRel( $suffix );
1264 * Get the URL of the archive directory, or a particular file if $suffix is specified
1266 * @param bool|string $suffix if not false, the name of an archived file
1270 function getArchiveUrl( $suffix = false ) {
1271 $this->assertRepoDefined();
1272 $ext = $this->getExtension();
1273 $path = $this->repo
->getZoneUrl( 'public', $ext ) . '/archive/' . $this->getHashPath();
1274 if ( $suffix === false ) {
1275 $path = substr( $path, 0, -1 );
1277 $path .= rawurlencode( $suffix );
1283 * Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified
1285 * @param string $archiveName the timestamped name of an archived image
1286 * @param bool|string $suffix if not false, the name of a thumbnail file
1290 function getArchiveThumbUrl( $archiveName, $suffix = false ) {
1291 $this->assertRepoDefined();
1292 $ext = $this->getExtension();
1293 $path = $this->repo
->getZoneUrl( 'thumb', $ext ) . '/archive/' .
1294 $this->getHashPath() . rawurlencode( $archiveName ) . "/";
1295 if ( $suffix === false ) {
1296 $path = substr( $path, 0, -1 );
1298 $path .= rawurlencode( $suffix );
1304 * Get the URL of the zone directory, or a particular file if $suffix is specified
1306 * @param string $zone name of requested zone
1307 * @param bool|string $suffix if not false, the name of a file in zone
1309 * @return string path
1311 function getZoneUrl( $zone, $suffix = false ) {
1312 $this->assertRepoDefined();
1313 $ext = $this->getExtension();
1314 $path = $this->repo
->getZoneUrl( $zone, $ext ) . '/' . $this->getUrlRel();
1315 if ( $suffix !== false ) {
1316 $path .= '/' . rawurlencode( $suffix );
1322 * Get the URL of the thumbnail directory, or a particular file if $suffix is specified
1324 * @param bool|string $suffix if not false, the name of a thumbnail file
1326 * @return string path
1328 function getThumbUrl( $suffix = false ) {
1329 return $this->getZoneUrl( 'thumb', $suffix );
1333 * Get the URL of the transcoded directory, or a particular file if $suffix is specified
1335 * @param bool|string $suffix if not false, the name of a media file
1337 * @return string path
1339 function getTranscodedUrl( $suffix = false ) {
1340 return $this->getZoneUrl( 'transcoded', $suffix );
1344 * Get the public zone virtual URL for a current version source file
1346 * @param bool|string $suffix if not false, the name of a thumbnail file
1350 function getVirtualUrl( $suffix = false ) {
1351 $this->assertRepoDefined();
1352 $path = $this->repo
->getVirtualUrl() . '/public/' . $this->getUrlRel();
1353 if ( $suffix !== false ) {
1354 $path .= '/' . rawurlencode( $suffix );
1360 * Get the public zone virtual URL for an archived version source file
1362 * @param bool|string $suffix if not false, the name of a thumbnail file
1366 function getArchiveVirtualUrl( $suffix = false ) {
1367 $this->assertRepoDefined();
1368 $path = $this->repo
->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
1369 if ( $suffix === false ) {
1370 $path = substr( $path, 0, -1 );
1372 $path .= rawurlencode( $suffix );
1378 * Get the virtual URL for a thumbnail file or directory
1380 * @param bool|string $suffix if not false, the name of a thumbnail file
1384 function getThumbVirtualUrl( $suffix = false ) {
1385 $this->assertRepoDefined();
1386 $path = $this->repo
->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
1387 if ( $suffix !== false ) {
1388 $path .= '/' . rawurlencode( $suffix );
1396 function isHashed() {
1397 $this->assertRepoDefined();
1398 return (bool)$this->repo
->getHashLevels();
1402 * @throws MWException
1404 function readOnlyError() {
1405 throw new MWException( get_class( $this ) . ': write operations are not supported' );
1409 * Record a file upload in the upload log and the image table
1411 * Overridden by LocalFile
1414 * @param $license string
1415 * @param $copyStatus string
1416 * @param $source string
1417 * @param $watch bool
1418 * @param $timestamp string|bool
1419 * @param $user User object or null to use $wgUser
1421 * @throws MWException
1423 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false, $timestamp = false, User
$user = null ) {
1424 $this->readOnlyError();
1428 * Move or copy a file to its public location. If a file exists at the
1429 * destination, move it to an archive. Returns a FileRepoStatus object with
1430 * the archive name in the "value" member on success.
1432 * The archive name should be passed through to recordUpload for database
1435 * Options to $options include:
1436 * - headers : name/value map of HTTP headers to use in response to GET/HEAD requests
1438 * @param string $srcPath local filesystem path to the source image
1439 * @param $flags Integer: a bitwise combination of:
1440 * File::DELETE_SOURCE Delete the source file, i.e. move
1442 * @param array $options Optional additional parameters
1443 * @return FileRepoStatus object. On success, the value member contains the
1444 * archive name, or an empty string if it was a new file.
1447 * Overridden by LocalFile
1449 function publish( $srcPath, $flags = 0, array $options = array() ) {
1450 $this->readOnlyError();
1456 function formatMetadata() {
1457 if ( !$this->getHandler() ) {
1460 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
1464 * Returns true if the file comes from the local file repository.
1468 function isLocal() {
1469 return $this->repo
&& $this->repo
->isLocal();
1473 * Returns the name of the repository.
1477 function getRepoName() {
1478 return $this->repo ?
$this->repo
->getName() : 'unknown';
1482 * Returns the repository
1484 * @return FileRepo|bool
1486 function getRepo() {
1491 * Returns true if the image is an old version
1501 * Is this file a "deleted" file in a private archive?
1504 * @param integer $field one of DELETED_* bitfield constants
1508 function isDeleted( $field ) {
1513 * Return the deletion bitfield
1517 function getVisibility() {
1522 * Was this file ever deleted from the wiki?
1526 function wasDeleted() {
1527 $title = $this->getTitle();
1528 return $title && $title->isDeletedQuick();
1532 * Move file to the new title
1534 * Move current, old version and all thumbnails
1535 * to the new filename. Old file is deleted.
1537 * Cache purging is done; checks for validity
1538 * and logging are caller's responsibility
1540 * @param $target Title New file name
1541 * @return FileRepoStatus object.
1543 function move( $target ) {
1544 $this->readOnlyError();
1548 * Delete all versions of the file.
1550 * Moves the files into an archive directory (or deletes them)
1551 * and removes the database rows.
1553 * Cache purging is done; logging is caller's responsibility.
1555 * @param $reason String
1556 * @param $suppress Boolean: hide content from sysops?
1557 * @return bool on success, false on some kind of failure
1559 * Overridden by LocalFile
1561 function delete( $reason, $suppress = false ) {
1562 $this->readOnlyError();
1566 * Restore all or specified deleted revisions to the given file.
1567 * Permissions and logging are left to the caller.
1569 * May throw database exceptions on error.
1571 * @param array $versions set of record ids of deleted items to restore,
1572 * or empty to restore all revisions.
1573 * @param bool $unsuppress remove restrictions on content upon restoration?
1574 * @return int|bool the number of file revisions restored if successful,
1575 * or false on failure
1577 * Overridden by LocalFile
1579 function restore( $versions = array(), $unsuppress = false ) {
1580 $this->readOnlyError();
1584 * Returns 'true' if this file is a type which supports multiple pages,
1585 * e.g. DJVU or PDF. Note that this may be true even if the file in
1586 * question only has a single page.
1590 function isMultipage() {
1591 return $this->getHandler() && $this->handler
->isMultiPage( $this );
1595 * Returns the number of pages of a multipage document, or false for
1596 * documents which aren't multipage documents
1600 function pageCount() {
1601 if ( !isset( $this->pageCount
) ) {
1602 if ( $this->getHandler() && $this->handler
->isMultiPage( $this ) ) {
1603 $this->pageCount
= $this->handler
->pageCount( $this );
1605 $this->pageCount
= false;
1608 return $this->pageCount
;
1612 * Calculate the height of a thumbnail using the source and destination width
1620 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1621 // Exact integer multiply followed by division
1622 if ( $srcWidth == 0 ) {
1625 return round( $srcHeight * $dstWidth / $srcWidth );
1630 * Get an image size array like that returned by getImageSize(), or false if it
1631 * can't be determined.
1633 * @param string $fileName The filename
1636 function getImageSize( $fileName ) {
1637 if ( !$this->getHandler() ) {
1640 return $this->handler
->getImageSize( $this, $fileName );
1644 * Get the URL of the image description page. May return false if it is
1645 * unknown or not applicable.
1649 function getDescriptionUrl() {
1650 if ( $this->repo
) {
1651 return $this->repo
->getDescriptionUrl( $this->getName() );
1658 * Get the HTML text of the description page, if available
1660 * @param $lang Language Optional language to fetch description in
1663 function getDescriptionText( $lang = false ) {
1664 global $wgMemc, $wgLang;
1665 if ( !$this->repo ||
!$this->repo
->fetchDescription
) {
1671 $renderUrl = $this->repo
->getDescriptionRenderUrl( $this->getName(), $lang->getCode() );
1673 if ( $this->repo
->descriptionCacheExpiry
> 0 ) {
1674 wfDebug( "Attempting to get the description from cache..." );
1675 $key = $this->repo
->getLocalCacheKey( 'RemoteFileDescription', 'url', $lang->getCode(),
1677 $obj = $wgMemc->get( $key );
1679 wfDebug( "success!\n" );
1682 wfDebug( "miss\n" );
1684 wfDebug( "Fetching shared description from $renderUrl\n" );
1685 $res = Http
::get( $renderUrl );
1686 if ( $res && $this->repo
->descriptionCacheExpiry
> 0 ) {
1687 $wgMemc->set( $key, $res, $this->repo
->descriptionCacheExpiry
);
1696 * Get description of file revision
1699 * @param $audience Integer: one of:
1700 * File::FOR_PUBLIC to be displayed to all users
1701 * File::FOR_THIS_USER to be displayed to the given user
1702 * File::RAW get the description regardless of permissions
1703 * @param $user User object to check for, only if FOR_THIS_USER is passed
1704 * to the $audience parameter
1707 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1712 * Get the 14-character timestamp of the file upload
1714 * @return string|bool TS_MW timestamp or false on failure
1716 function getTimestamp() {
1717 $this->assertRepoDefined();
1718 return $this->repo
->getFileTimestamp( $this->getPath() );
1722 * Get the SHA-1 base 36 hash of the file
1726 function getSha1() {
1727 $this->assertRepoDefined();
1728 return $this->repo
->getFileSha1( $this->getPath() );
1732 * Get the deletion archive key, "<sha1>.<ext>"
1736 function getStorageKey() {
1737 $hash = $this->getSha1();
1741 $ext = $this->getExtension();
1742 $dotExt = $ext === '' ?
'' : ".$ext";
1743 return $hash . $dotExt;
1747 * Determine if the current user is allowed to view a particular
1748 * field of this file, if it's marked as deleted.
1750 * @param $field Integer
1751 * @param $user User object to check, or null to use $wgUser
1754 function userCan( $field, User
$user = null ) {
1759 * Get an associative array containing information about a file in the local filesystem.
1761 * @param string $path absolute local filesystem path
1762 * @param $ext Mixed: the file extension, or true to extract it from the filename.
1763 * Set it to false to ignore the extension.
1766 * @deprecated since 1.19
1768 static function getPropsFromPath( $path, $ext = true ) {
1769 wfDebug( __METHOD__
. ": Getting file info for $path\n" );
1770 wfDeprecated( __METHOD__
, '1.19' );
1772 $fsFile = new FSFile( $path );
1773 return $fsFile->getProps();
1777 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1778 * encoding, zero padded to 31 digits.
1780 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1783 * @param $path string
1785 * @return bool|string False on failure
1786 * @deprecated since 1.19
1788 static function sha1Base36( $path ) {
1789 wfDeprecated( __METHOD__
, '1.19' );
1791 $fsFile = new FSFile( $path );
1792 return $fsFile->getSha1Base36();
1796 * @return Array HTTP header name/value map to use for HEAD/GET request responses
1798 function getStreamHeaders() {
1799 $handler = $this->getHandler();
1801 return $handler->getStreamHeaders( $this->getMetadata() );
1810 function getLongDesc() {
1811 $handler = $this->getHandler();
1813 return $handler->getLongDesc( $this );
1815 return MediaHandler
::getGeneralLongDesc( $this );
1822 function getShortDesc() {
1823 $handler = $this->getHandler();
1825 return $handler->getShortDesc( $this );
1827 return MediaHandler
::getGeneralShortDesc( $this );
1834 function getDimensionsString() {
1835 $handler = $this->getHandler();
1837 return $handler->getDimensionsString( $this );
1846 function getRedirected() {
1847 return $this->redirected
;
1851 * @return Title|null
1853 function getRedirectedTitle() {
1854 if ( $this->redirected
) {
1855 if ( !$this->redirectTitle
) {
1856 $this->redirectTitle
= Title
::makeTitle( NS_FILE
, $this->redirected
);
1858 return $this->redirectTitle
;
1867 function redirectedFrom( $from ) {
1868 $this->redirected
= $from;
1874 function isMissing() {
1879 * Check if this file object is small and can be cached
1882 public function isCacheable() {
1887 * Assert that $this->repo is set to a valid FileRepo instance
1888 * @throws MWException
1890 protected function assertRepoDefined() {
1891 if ( !( $this->repo
instanceof $this->repoClass
) ) {
1892 throw new MWException( "A {$this->repoClass} object is not set for this File.\n" );
1897 * Assert that $this->title is set to a Title
1898 * @throws MWException
1900 protected function assertTitleDefined() {
1901 if ( !( $this->title
instanceof Title
) ) {
1902 throw new MWException( "A Title object is not set for this File.\n" );