MediaWiki REL1_31
MediaHandler.php
Go to the documentation of this file.
1<?php
24
30abstract class MediaHandler {
31 const TRANSFORM_LATER = 1;
32 const METADATA_GOOD = true;
33 const METADATA_BAD = false;
34 const METADATA_COMPATIBLE = 2; // for old but backwards compatible.
38 const MAX_ERR_LOG_SIZE = 65535;
39
46 static function getHandler( $type ) {
47 return MediaWikiServices::getInstance()
48 ->getMediaHandlerFactory()->getHandler( $type );
49 }
50
55 abstract public function getParamMap();
56
65 abstract public function validateParam( $name, $value );
66
73 abstract public function makeParamString( $params );
74
81 abstract public function parseParamString( $str );
82
90 abstract function normaliseParams( $image, &$params );
91
112 abstract function getImageSize( $image, $path );
113
122 function getMetadata( $image, $path ) {
123 return '';
124 }
125
141 static function getMetadataVersion() {
142 $version = [ '2' ]; // core metadata version
143 Hooks::run( 'GetMetadataVersion', [ &$version ] );
144
145 return implode( ';', $version );
146 }
147
158 function convertMetadataVersion( $metadata, $version = 1 ) {
159 if ( !is_array( $metadata ) ) {
160 // unserialize to keep return parameter consistent.
161 Wikimedia\suppressWarnings();
162 $ret = unserialize( $metadata );
163 Wikimedia\restoreWarnings();
164
165 return $ret;
166 }
167
168 return $metadata;
169 }
170
179 return false;
180 }
181
198 function isMetadataValid( $image, $metadata ) {
199 return self::METADATA_GOOD;
200 }
201
234 public function getCommonMetaArray( File $file ) {
235 return false;
236 }
237
250 function getScriptedTransform( $image, $script, $params ) {
251 return false;
252 }
253
264 final function getTransform( $image, $dstPath, $dstUrl, $params ) {
265 return $this->doTransform( $image, $dstPath, $dstUrl, $params, self::TRANSFORM_LATER );
266 }
267
280 abstract function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 );
281
290 function getThumbType( $ext, $mime, $params = null ) {
291 $magic = MediaWiki\MediaWikiServices::getInstance()->getMimeAnalyzer();
292 if ( !$ext || $magic->isMatchingExtension( $ext, $mime ) === false ) {
293 // The extension is not valid for this MIME type and we do
294 // recognize the MIME type
295 $extensions = $magic->getExtensionsForType( $mime );
296 if ( $extensions ) {
297 return [ strtok( $extensions, ' ' ), $mime ];
298 }
299 }
300
301 // The extension is correct (true) or the MIME type is unknown to
302 // MediaWiki (null)
303 return [ $ext, $mime ];
304 }
305
311 public function getStreamHeaders( $metadata ) {
312 wfDeprecated( __METHOD__, '1.30' );
313 return $this->getContentHeaders( $metadata );
314 }
315
322 public function canRender( $file ) {
323 return true;
324 }
325
333 public function mustRender( $file ) {
334 return false;
335 }
336
343 public function isMultiPage( $file ) {
344 return false;
345 }
346
353 function pageCount( File $file ) {
354 return false;
355 }
356
363 function isVectorized( $file ) {
364 return false;
365 }
366
375 function isAnimatedImage( $file ) {
376 return false;
377 }
378
386 function canAnimateThumbnail( $file ) {
387 return true;
388 }
389
394 function isEnabled() {
395 return true;
396 }
397
414 function getPageDimensions( File $image, $page ) {
415 $gis = $this->getImageSize( $image, $image->getLocalRefPath() );
416 if ( $gis ) {
417 return [
418 'width' => $gis[0],
419 'height' => $gis[1]
420 ];
421 } else {
422 return false;
423 }
424 }
425
434 function getPageText( File $image, $page ) {
435 return false;
436 }
437
443 public function getEntireText( File $file ) {
444 $numPages = $file->pageCount();
445 if ( !$numPages ) {
446 // Not a multipage document
447 return $this->getPageText( $file, 1 );
448 }
449 $document = '';
450 for ( $i = 1; $i <= $numPages; $i++ ) {
451 $curPage = $this->getPageText( $file, $i );
452 if ( is_string( $curPage ) ) {
453 $document .= $curPage . "\n";
454 }
455 }
456 if ( $document !== '' ) {
457 return $document;
458 }
459 return false;
460 }
461
490 function formatMetadata( $image, $context = false ) {
491 return false;
492 }
493
504 function formatMetadataHelper( $metadataArray, $context = false ) {
505 $result = [
506 'visible' => [],
507 'collapsed' => []
508 ];
509
510 $formatted = FormatMetadata::getFormattedData( $metadataArray, $context );
511 // Sort fields into visible and collapsed
512 $visibleFields = $this->visibleMetadataFields();
513 foreach ( $formatted as $name => $value ) {
514 $tag = strtolower( $name );
515 self::addMeta( $result,
516 in_array( $tag, $visibleFields ) ? 'visible' : 'collapsed',
517 'exif',
518 $tag,
519 $value
520 );
521 }
522
523 return $result;
524 }
525
532 protected function visibleMetadataFields() {
534 }
535
559 protected static function addMeta( &$array, $visibility, $type, $id, $value, $param = false ) {
560 $msg = wfMessage( "$type-$id", $param );
561 if ( $msg->exists() ) {
562 $name = $msg->text();
563 } else {
564 // This is for future compatibility when using instant commons.
565 // So as to not display as ugly a name if a new metadata
566 // property is defined that we don't know about
567 // (not a major issue since such a property would be collapsed
568 // by default).
569 wfDebug( __METHOD__ . ' Unknown metadata name: ' . $id . "\n" );
570 $name = wfEscapeWikiText( $id );
571 }
572 $array[$visibility][] = [
573 'id' => "$type-$id",
574 'name' => $name,
575 'value' => $value
576 ];
577 }
578
585 function getShortDesc( $file ) {
586 return self::getGeneralShortDesc( $file );
587 }
588
595 function getLongDesc( $file ) {
596 return self::getGeneralLongDesc( $file );
597 }
598
605 static function getGeneralShortDesc( $file ) {
606 global $wgLang;
607
608 return htmlspecialchars( $wgLang->formatSize( $file->getSize() ) );
609 }
610
617 static function getGeneralLongDesc( $file ) {
618 return wfMessage( 'file-info' )->sizeParams( $file->getSize() )
619 ->params( '<span class="mime-type">' . $file->getMimeType() . '</span>' )->parse();
620 }
621
630 public static function fitBoxWidth( $boxWidth, $boxHeight, $maxHeight ) {
631 $idealWidth = $boxWidth * $maxHeight / $boxHeight;
632 $roundedUp = ceil( $idealWidth );
633 if ( round( $roundedUp * $boxHeight / $boxWidth ) > $maxHeight ) {
634 return floor( $idealWidth );
635 } else {
636 return $roundedUp;
637 }
638 }
639
646 function getDimensionsString( $file ) {
647 return '';
648 }
649
660 function parserTransformHook( $parser, $file ) {
661 }
662
673 function verifyUpload( $fileName ) {
674 return Status::newGood();
675 }
676
685 function removeBadFile( $dstPath, $retval = 0 ) {
686 if ( file_exists( $dstPath ) ) {
687 $thumbstat = stat( $dstPath );
688 if ( $thumbstat['size'] == 0 || $retval != 0 ) {
689 $result = unlink( $dstPath );
690
691 if ( $result ) {
692 wfDebugLog( 'thumbnail',
693 sprintf( 'Removing bad %d-byte thumbnail "%s". unlink() succeeded',
694 $thumbstat['size'], $dstPath ) );
695 } else {
696 wfDebugLog( 'thumbnail',
697 sprintf( 'Removing bad %d-byte thumbnail "%s". unlink() failed',
698 $thumbstat['size'], $dstPath ) );
699 }
700
701 return true;
702 }
703 }
704
705 return false;
706 }
707
721 public function filterThumbnailPurgeList( &$files, $options ) {
722 // Do nothing
723 }
724
730 public function canRotate() {
731 return false;
732 }
733
748 public function getRotation( $file ) {
749 return 0;
750 }
751
763 protected function logErrorForExternalProcess( $retval, $err, $cmd ) {
764 # Keep error output limited (T59985)
765 $errMessage = trim( substr( $err, 0, self::MAX_ERR_LOG_SIZE ) );
766
767 wfDebugLog( 'thumbnail',
768 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
769 wfHostname(), $retval, $errMessage, $cmd ) );
770 }
771
779 public function getAvailableLanguages( File $file ) {
780 return [];
781 }
782
795 public function getDefaultRenderLanguage( File $file ) {
796 return null;
797 }
798
809 public function getLength( $file ) {
810 return 0.0;
811 }
812
818 public function isExpensiveToThumbnail( $file ) {
819 return false;
820 }
821
828 public function supportsBucketing() {
829 return false;
830 }
831
839 return $params;
840 }
841
867 public function getWarningConfig( $file ) {
868 return null;
869 }
870
878 public static function getPageRangesByDimensions( $pagesByDimensions ) {
879 $pageRangesByDimensions = [];
880
881 foreach ( $pagesByDimensions as $dimensions => $pageList ) {
882 $ranges = [];
883 $firstPage = $pageList[0];
884 $lastPage = $firstPage - 1;
885
886 foreach ( $pageList as $page ) {
887 if ( $page > $lastPage + 1 ) {
888 if ( $firstPage != $lastPage ) {
889 $ranges[] = "$firstPage-$lastPage";
890 } else {
891 $ranges[] = "$firstPage";
892 }
893
894 $firstPage = $page;
895 }
896
897 $lastPage = $page;
898 }
899
900 if ( $firstPage != $lastPage ) {
901 $ranges[] = "$firstPage-$lastPage";
902 } else {
903 $ranges[] = "$firstPage";
904 }
905
906 $pageRangesByDimensions[ $dimensions ] = $ranges;
907 }
908
909 $dimensionsString = [];
910 foreach ( $pageRangesByDimensions as $dimensions => $pageRanges ) {
911 $dimensionsString[] = "$dimensions:" . implode( ',', $pageRanges );
912 }
913
914 return implode( '/', $dimensionsString );
915 }
916
923 public function getContentHeaders( $metadata ) {
924 return [ 'X-Content-Dimensions' => '' ]; // T175689
925 }
926}
unserialize( $serialized)
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfHostname()
Fetch server name for use in error reporting etc.
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition File.php:51
static getVisibleFields()
Get a list of fields that are visible by default.
static getFormattedData( $tags, $context=false)
Numbers given by Exif user agents are often magical, that is they should be replaced by a detailed ex...
Base media handler class.
normaliseParams( $image, &$params)
Changes the parameter array as necessary, ready for transformation.
getRotation( $file)
On supporting image formats, try to read out the low-level orientation of the file and return the ang...
const METADATA_COMPATIBLE
canRender( $file)
True if the handled types can be transformed.
canAnimateThumbnail( $file)
If the material is animated, we can animate the thumbnail.
verifyUpload( $fileName)
File validation hook called on upload.
visibleMetadataFields()
Get a list of metadata items which should be displayed when the metadata table is collapsed.
static addMeta(&$array, $visibility, $type, $id, $value, $param=false)
This is used to generate an array element for each metadata value That array is then used to generate...
supportsBucketing()
Returns whether or not this handler supports the chained generation of thumbnails according to bucket...
parserTransformHook( $parser, $file)
Modify the parser object post-transform.
static getGeneralLongDesc( $file)
Used instead of getLongDesc if there is no handler registered for file.
getStreamHeaders( $metadata)
canRotate()
True if the handler can rotate the media.
sanitizeParamsForBucketing( $params)
Returns a normalised params array for which parameters have been cleaned up for bucketing purposes.
getDefaultRenderLanguage(File $file)
On file types that support renderings in multiple languages, which language is used by default if uns...
getLength( $file)
If its an audio file, return the length of the file.
getTransform( $image, $dstPath, $dstUrl, $params)
Get a MediaTransformOutput object representing the transformed output.
getDimensionsString( $file)
Shown in file history box on image description page.
static getHandler( $type)
Get a MediaHandler for a given MIME type from the instance cache.
getCommonMetaArray(File $file)
Get an array of standard (FormatMetadata type) metadata values.
doTransform( $image, $dstPath, $dstUrl, $params, $flags=0)
Get a MediaTransformOutput object representing the transformed output.
getMetadata( $image, $path)
Get handler-specific metadata which will be saved in the img_metadata field.
getPageText(File $image, $page)
Generic getter for text layer.
isAnimatedImage( $file)
The material is an image, and is animated.
isVectorized( $file)
The material is vectorized and thus scaling is lossless.
getImageSize( $image, $path)
Get an image size array like that returned by getimagesize(), or false if it can't be determined.
convertMetadataVersion( $metadata, $version=1)
Convert metadata version.
formatMetadata( $image, $context=false)
Get an array structure that looks like this:
getWarningConfig( $file)
Gets configuration for the file warning message.
logErrorForExternalProcess( $retval, $err, $cmd)
Log an error that occurred in an external process.
isEnabled()
False if the handler is disabled for all files.
parseParamString( $str)
Parse a param string made with makeParamString back into an array.
static getGeneralShortDesc( $file)
Used instead of getShortDesc if there is no handler registered for file.
isMultiPage( $file)
True if the type has multi-page capabilities.
getLongDesc( $file)
Long description.
static fitBoxWidth( $boxWidth, $boxHeight, $maxHeight)
Calculate the largest thumbnail width for a given original file size such that the thumbnail's height...
mustRender( $file)
True if handled types cannot be displayed directly in a browser but can be rendered.
getScriptedTransform( $image, $script, $params)
Get a MediaTransformOutput object representing an alternate of the transformed output which will call...
getMetadataType( $image)
Get a string describing the type of metadata, for display purposes.
isExpensiveToThumbnail( $file)
True if creating thumbnails from the file is large or otherwise resource-intensive.
getEntireText(File $file)
Get the text of the entire document.
getAvailableLanguages(File $file)
Get list of languages file can be viewed in.
filterThumbnailPurgeList(&$files, $options)
Remove files from the purge list.
getShortDesc( $file)
Short description.
makeParamString( $params)
Merge a parameter array into a string appropriate for inclusion in filenames.
formatMetadataHelper( $metadataArray, $context=false)
sorts the visible/invisible field.
validateParam( $name, $value)
Validate a thumbnail parameter at parse time.
static getPageRangesByDimensions( $pagesByDimensions)
Converts a dimensions array about a potentially multipage document from an exhaustive list of ordered...
getPageDimensions(File $image, $page)
Get an associative array of page dimensions Currently "width" and "height" are understood,...
getContentHeaders( $metadata)
Get useful response headers for GET/HEAD requests for a file with the given metadata.
const TRANSFORM_LATER
getParamMap()
Get an associative array mapping magic word IDs to parameter names.
const MAX_ERR_LOG_SIZE
Max length of error logged by logErrorForExternalProcess()
const METADATA_GOOD
getThumbType( $ext, $mime, $params=null)
Get the thumbnail extension and MIME type for a given source MIME type.
removeBadFile( $dstPath, $retval=0)
Check for zero-sized thumbnails.
isMetadataValid( $image, $metadata)
Check if the metadata string is valid for this handler.
static getMetadataVersion()
Get metadata version.
pageCount(File $file)
Page count for a multi-page document, false if unsupported or unknown.
MediaWikiServices is the service locator for the application scope of MediaWiki.
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as $wgLang
Definition design.txt:56
namespace being checked & $result
Definition hooks.txt:2323
do that in ParserLimitReportFormat instead $parser
Definition hooks.txt:2603
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account incomplete not yet checked for validity & $retval
Definition hooks.txt:266
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check $image
Definition hooks.txt:895
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition hooks.txt:2001
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition hooks.txt:2811
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt;div ...>$1&lt;/div>"). - flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException':Called before an exception(or PHP error) is logged. This is meant for integration with external error aggregation services
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition hooks.txt:2005
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:302
if( $ext=='php'|| $ext=='php5') $mime
Definition router.php:59
if(!is_readable( $file)) $ext
Definition router.php:55
$params