MediaWiki REL1_35
MediaHandler.php
Go to the documentation of this file.
1<?php
22
37abstract class MediaHandler {
38 public const TRANSFORM_LATER = 1;
39 public const METADATA_GOOD = true;
40 public const METADATA_BAD = false;
41 public const METADATA_COMPATIBLE = 2; // for old but backwards compatible.
45 private const MAX_ERR_LOG_SIZE = 65535;
46
53 public static function getHandler( $type ) {
54 return MediaWikiServices::getInstance()
55 ->getMediaHandlerFactory()->getHandler( $type );
56 }
57
62 abstract public function getParamMap();
63
72 abstract public function validateParam( $name, $value );
73
80 abstract public function makeParamString( $params );
81
88 abstract public function parseParamString( $str );
89
97 abstract public function normaliseParams( $image, &$params );
98
119 abstract public function getImageSize( $image, $path );
120
130 public function getMetadata( $image, $path ) {
131 return '';
132 }
133
151 public static function getMetadataVersion() {
152 $version = [ '2' ]; // core metadata version
153 Hooks::runner()->onGetMetadataVersion( $version );
154
155 return implode( ';', $version );
156 }
157
169 public function convertMetadataVersion( $metadata, $version = 1 ) {
170 if ( !is_array( $metadata ) ) {
171 // unserialize to keep return parameter consistent.
172 Wikimedia\suppressWarnings();
173 $ret = unserialize( $metadata );
174 Wikimedia\restoreWarnings();
175
176 return $ret;
177 }
178
179 return $metadata;
180 }
181
190 public function getMetadataType( $image ) {
191 return false;
192 }
193
212 public function isMetadataValid( $image, $metadata ) {
213 return self::METADATA_GOOD;
214 }
215
250 public function getCommonMetaArray( File $file ) {
251 return false;
252 }
253
269 public function getScriptedTransform( $image, $script, $params ) {
270 return false;
271 }
272
285 final public function getTransform( $image, $dstPath, $dstUrl, $params ) {
286 return $this->doTransform( $image, $dstPath, $dstUrl, $params, self::TRANSFORM_LATER );
287 }
288
303 abstract public function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 );
304
315 public function getThumbType( $ext, $mime, $params = null ) {
316 $magic = MediaWiki\MediaWikiServices::getInstance()->getMimeAnalyzer();
317 if ( !$ext || $magic->isMatchingExtension( $ext, $mime ) === false ) {
318 // The extension is not valid for this MIME type and we do
319 // recognize the MIME type
320 $knownExt = $magic->getExtensionFromMimeTypeOrNull( $mime );
321 if ( $knownExt !== null ) {
322 return [ $knownExt, $mime ];
323 }
324 }
325
326 // The extension is correct (true) or the MIME type is unknown to
327 // MediaWiki (null)
328 return [ $ext, $mime ];
329 }
330
339 public function canRender( $file ) {
340 return true;
341 }
342
352 public function mustRender( $file ) {
353 return false;
354 }
355
364 public function isMultiPage( $file ) {
365 return false;
366 }
367
376 public function pageCount( File $file ) {
377 return false;
378 }
379
388 public function isVectorized( $file ) {
389 return false;
390 }
391
402 public function isAnimatedImage( $file ) {
403 return false;
404 }
405
415 public function canAnimateThumbnail( $file ) {
416 return true;
417 }
418
425 public function isEnabled() {
426 return true;
427 }
428
447 public function getPageDimensions( File $image, $page ) {
448 $gis = $this->getImageSize( $image, $image->getLocalRefPath() );
449 if ( $gis ) {
450 return [
451 'width' => $gis[0],
452 'height' => $gis[1]
453 ];
454 } else {
455 return false;
456 }
457 }
458
469 public function getPageText( File $image, $page ) {
470 return false;
471 }
472
478 public function getEntireText( File $file ) {
479 $numPages = $file->pageCount();
480 if ( !$numPages ) {
481 // Not a multipage document
482 return $this->getPageText( $file, 1 );
483 }
484 $document = '';
485 for ( $i = 1; $i <= $numPages; $i++ ) {
486 $curPage = $this->getPageText( $file, $i );
487 if ( is_string( $curPage ) ) {
488 $document .= $curPage . "\n";
489 }
490 }
491 if ( $document !== '' ) {
492 return $document;
493 }
494 return false;
495 }
496
527 public function formatMetadata( $image, $context = false ) {
528 return false;
529 }
530
543 protected function formatMetadataHelper( $metadataArray, $context = false ) {
544 $result = [
545 'visible' => [],
546 'collapsed' => []
547 ];
548
549 $formatted = FormatMetadata::getFormattedData( $metadataArray, $context );
550 // Sort fields into visible and collapsed
551 $visibleFields = $this->visibleMetadataFields();
552 foreach ( $formatted as $name => $value ) {
553 $tag = strtolower( $name );
554 self::addMeta( $result,
555 in_array( $tag, $visibleFields ) ? 'visible' : 'collapsed',
556 'exif',
557 $tag,
558 $value
559 );
560 }
561
562 return $result;
563 }
564
573 protected function visibleMetadataFields() {
575 }
576
600 protected static function addMeta( &$array, $visibility, $type, $id, $value, $param = false ) {
601 $msg = wfMessage( "$type-$id", $param );
602 if ( $msg->exists() ) {
603 $name = $msg->text();
604 } else {
605 // This is for future compatibility when using instant commons.
606 // So as to not display as ugly a name if a new metadata
607 // property is defined that we don't know about
608 // (not a major issue since such a property would be collapsed
609 // by default).
610 wfDebug( __METHOD__ . ' Unknown metadata name: ' . $id );
611 $name = wfEscapeWikiText( $id );
612 }
613 $array[$visibility][] = [
614 'id' => "$type-$id",
615 'name' => $name,
616 'value' => $value
617 ];
618 }
619
628 public function getShortDesc( $file ) {
630 }
631
640 public function getLongDesc( $file ) {
642 }
643
650 public static function getGeneralShortDesc( $file ) {
651 global $wgLang;
652
653 return htmlspecialchars( $wgLang->formatSize( $file->getSize() ) );
654 }
655
662 public static function getGeneralLongDesc( $file ) {
663 return wfMessage( 'file-info' )->sizeParams( $file->getSize() )
664 ->params( '<span class="mime-type">' . $file->getMimeType() . '</span>' )->parse();
665 }
666
675 public static function fitBoxWidth( $boxWidth, $boxHeight, $maxHeight ) {
676 $idealWidth = $boxWidth * $maxHeight / $boxHeight;
677 $roundedUp = ceil( $idealWidth );
678 if ( round( $roundedUp * $boxHeight / $boxWidth ) > $maxHeight ) {
679 return floor( $idealWidth );
680 } else {
681 return $roundedUp;
682 }
683 }
684
693 public function getDimensionsString( $file ) {
694 return '';
695 }
696
709 public function parserTransformHook( $parser, $file ) {
710 }
711
724 public function verifyUpload( $fileName ) {
725 return Status::newGood();
726 }
727
738 public function removeBadFile( $dstPath, $retval = 0 ) {
739 if ( file_exists( $dstPath ) ) {
740 $thumbstat = stat( $dstPath );
741 if ( $thumbstat['size'] == 0 || $retval != 0 ) {
742 $result = unlink( $dstPath );
743
744 if ( $result ) {
745 wfDebugLog( 'thumbnail',
746 sprintf( 'Removing bad %d-byte thumbnail "%s". unlink() succeeded',
747 $thumbstat['size'], $dstPath ) );
748 } else {
749 wfDebugLog( 'thumbnail',
750 sprintf( 'Removing bad %d-byte thumbnail "%s". unlink() failed',
751 $thumbstat['size'], $dstPath ) );
752 }
753
754 return true;
755 }
756 }
757
758 return false;
759 }
760
775 public function filterThumbnailPurgeList( &$files, $options ) {
776 // Do nothing
777 }
778
786 public function canRotate() {
787 return false;
788 }
789
806 public function getRotation( $file ) {
807 return 0;
808 }
809
821 protected function logErrorForExternalProcess( $retval, $err, $cmd ) {
822 # Keep error output limited (T59985)
823 $errMessage = trim( substr( $err, 0, self::MAX_ERR_LOG_SIZE ) );
824
825 wfDebugLog( 'thumbnail',
826 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
827 wfHostname(), $retval, $errMessage, $cmd ) );
828 }
829
839 public function getAvailableLanguages( File $file ) {
840 return [];
841 }
842
854 public function getMatchedLanguage( $userPreferredLanguage, array $availableLanguages ) {
855 return null;
856 }
857
873 return null;
874 }
875
888 public function getLength( $file ) {
889 return 0.0;
890 }
891
899 public function isExpensiveToThumbnail( $file ) {
900 return false;
901 }
902
911 public function supportsBucketing() {
912 return false;
913 }
914
923 public function sanitizeParamsForBucketing( $params ) {
924 return $params;
925 }
926
953 public function getWarningConfig( $file ) {
954 return null;
955 }
956
964 public static function getPageRangesByDimensions( $pagesByDimensions ) {
965 $pageRangesByDimensions = [];
966
967 foreach ( $pagesByDimensions as $dimensions => $pageList ) {
968 $ranges = [];
969 $firstPage = $pageList[0];
970 $lastPage = $firstPage - 1;
971
972 foreach ( $pageList as $page ) {
973 if ( $page > $lastPage + 1 ) {
974 if ( $firstPage != $lastPage ) {
975 $ranges[] = "$firstPage-$lastPage";
976 } else {
977 $ranges[] = "$firstPage";
978 }
979
980 $firstPage = $page;
981 }
982
983 $lastPage = $page;
984 }
985
986 if ( $firstPage != $lastPage ) {
987 $ranges[] = "$firstPage-$lastPage";
988 } else {
989 $ranges[] = "$firstPage";
990 }
991
992 $pageRangesByDimensions[ $dimensions ] = $ranges;
993 }
994
995 $dimensionsString = [];
996 foreach ( $pageRangesByDimensions as $dimensions => $pageRanges ) {
997 $dimensionsString[] = "$dimensions:" . implode( ',', $pageRanges );
998 }
999
1000 return implode( '/', $dimensionsString );
1001 }
1002
1011 public function getContentHeaders( $metadata ) {
1012 return [ 'X-Content-Dimensions' => '' ]; // T175689
1013 }
1014}
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()
Get host name of the current machine, for use in error reporting.
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
$wgLang
Definition Setup.php:781
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition File.php:63
getLocalRefPath()
Get an FS copy or original of this file and return the path.
Definition File.php:457
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.
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 St...
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 Stable to override.
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 Stable to overri...
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.
getMatchedLanguage( $userPreferredLanguage, array $availableLanguages)
When overridden in a descendant class, returns a language code most suiting.
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.
$mime
Definition router.php:60
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition router.php:42
if(!is_readable( $file)) $ext
Definition router.php:48