MediaWiki  master
MediaHandler.php
Go to the documentation of this file.
1 <?php
22 
37 abstract 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 
872  public function getDefaultRenderLanguage( File $file ) {
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 }
MediaHandler\removeBadFile
removeBadFile( $dstPath, $retval=0)
Check for zero-sized thumbnails.
Definition: MediaHandler.php:738
MediaHandler\mustRender
mustRender( $file)
True if handled types cannot be displayed directly in a browser but can be rendered.
Definition: MediaHandler.php:352
MediaHandler\formatMetadata
formatMetadata( $image, $context=false)
Get an array structure that looks like this:
Definition: MediaHandler.php:527
MediaHandler\getWarningConfig
getWarningConfig( $file)
Gets configuration for the file warning message.
Definition: MediaHandler.php:953
MediaHandler\getCommonMetaArray
getCommonMetaArray(File $file)
Get an array of standard (FormatMetadata type) metadata values.
Definition: MediaHandler.php:250
MediaHandler\normaliseParams
normaliseParams( $image, &$params)
Changes the parameter array as necessary, ready for transformation.
MediaHandler\verifyUpload
verifyUpload( $fileName)
File validation hook called on upload.
Definition: MediaHandler.php:724
MediaHandler\pageCount
pageCount(File $file)
Page count for a multi-page document, false if unsupported or unknown.
Definition: MediaHandler.php:376
FormatMetadata\getFormattedData
static getFormattedData( $tags, $context=false)
Numbers given by Exif user agents are often magical, that is they should be replaced by a detailed ex...
Definition: FormatMetadata.php:86
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:157
MediaHandler\TRANSFORM_LATER
const TRANSFORM_LATER
Definition: MediaHandler.php:38
MediaHandler\getMetadataVersion
static getMetadataVersion()
Get metadata version.
Definition: MediaHandler.php:151
MediaHandler\filterThumbnailPurgeList
filterThumbnailPurgeList(&$files, $options)
Remove files from the purge list.
Definition: MediaHandler.php:775
MediaHandler\getEntireText
getEntireText(File $file)
Get the text of the entire document.
Definition: MediaHandler.php:478
MediaHandler\getShortDesc
getShortDesc( $file)
Short description.
Definition: MediaHandler.php:628
MediaHandler\MAX_ERR_LOG_SIZE
const MAX_ERR_LOG_SIZE
Max length of error logged by logErrorForExternalProcess()
Definition: MediaHandler.php:45
MediaHandler\getThumbType
getThumbType( $ext, $mime, $params=null)
Get the thumbnail extension and MIME type for a given source MIME type.
Definition: MediaHandler.php:315
MediaHandler\canRotate
canRotate()
True if the handler can rotate the media.
Definition: MediaHandler.php:786
MediaHandler\getMatchedLanguage
getMatchedLanguage( $userPreferredLanguage, array $availableLanguages)
When overridden in a descendant class, returns a language code most suiting.
Definition: MediaHandler.php:854
$file
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42
wfHostname
wfHostname()
Get host name of the current machine, for use in error reporting.
Definition: GlobalFunctions.php:1283
wfMessage
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Definition: GlobalFunctions.php:1220
MediaHandler\getLongDesc
getLongDesc( $file)
Long description.
Definition: MediaHandler.php:640
wfDebugLog
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
Definition: GlobalFunctions.php:989
MediaHandler\supportsBucketing
supportsBucketing()
Returns whether or not this handler supports the chained generation of thumbnails according to bucket...
Definition: MediaHandler.php:911
MediaHandler\getMetadataType
getMetadataType( $image)
Get a string describing the type of metadata, for display purposes.
Definition: MediaHandler.php:190
MediaHandler\getAvailableLanguages
getAvailableLanguages(File $file)
Get list of languages file can be viewed in.
Definition: MediaHandler.php:839
MediaWiki\MediaWikiServices\getInstance
static getInstance()
Returns the global default instance of the top level service locator.
Definition: MediaWikiServices.php:188
MediaHandler\makeParamString
makeParamString( $params)
Merge a parameter array into a string appropriate for inclusion in filenames.
MediaHandler\METADATA_COMPATIBLE
const METADATA_COMPATIBLE
Definition: MediaHandler.php:41
File
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition: File.php:63
MediaHandler\isExpensiveToThumbnail
isExpensiveToThumbnail( $file)
True if creating thumbnails from the file is large or otherwise resource-intensive.
Definition: MediaHandler.php:899
File\getLocalRefPath
getLocalRefPath()
Get an FS copy or original of this file and return the path.
Definition: File.php:457
MediaHandler\getPageRangesByDimensions
static getPageRangesByDimensions( $pagesByDimensions)
Converts a dimensions array about a potentially multipage document from an exhaustive list of ordered...
Definition: MediaHandler.php:964
MediaHandler\canAnimateThumbnail
canAnimateThumbnail( $file)
If the material is animated, we can animate the thumbnail.
Definition: MediaHandler.php:415
$wgLang
$wgLang
Definition: Setup.php:776
MediaHandler\getPageText
getPageText(File $image, $page)
Generic getter for text layer.
Definition: MediaHandler.php:469
MediaHandler\addMeta
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...
Definition: MediaHandler.php:600
MediaHandler\getPageDimensions
getPageDimensions(File $image, $page)
Get an associative array of page dimensions Currently "width" and "height" are understood,...
Definition: MediaHandler.php:447
wfDebug
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:910
MediaHandler\getImageSize
getImageSize( $image, $path)
Get an image size array like that returned by getimagesize(), or false if it can't be determined.
MediaHandler\isEnabled
isEnabled()
False if the handler is disabled for all files Stable to override.
Definition: MediaHandler.php:425
MediaHandler\getDimensionsString
getDimensionsString( $file)
Shown in file history box on image description page.
Definition: MediaHandler.php:693
MediaHandler\getMetadata
getMetadata( $image, $path)
Get handler-specific metadata which will be saved in the img_metadata field.
Definition: MediaHandler.php:130
MediaHandler\convertMetadataVersion
convertMetadataVersion( $metadata, $version=1)
Convert metadata version.
Definition: MediaHandler.php:169
MediaHandler\getGeneralShortDesc
static getGeneralShortDesc( $file)
Used instead of getShortDesc if there is no handler registered for file.
Definition: MediaHandler.php:650
StatusValue\newGood
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:82
MediaHandler\getTransform
getTransform( $image, $dstPath, $dstUrl, $params)
Get a MediaTransformOutput object representing the transformed output.
Definition: MediaHandler.php:285
Hooks\runner
static runner()
Get a HookRunner instance for calling hooks using the new interfaces.
Definition: Hooks.php:172
wfEscapeWikiText
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
Definition: GlobalFunctions.php:1488
MediaHandler\doTransform
doTransform( $image, $dstPath, $dstUrl, $params, $flags=0)
Get a MediaTransformOutput object representing the transformed output.
unserialize
unserialize( $serialized)
Definition: ApiMessageTrait.php:146
MediaHandler\visibleMetadataFields
visibleMetadataFields()
Get a list of metadata items which should be displayed when the metadata table is collapsed.
Definition: MediaHandler.php:573
MediaHandler\getParamMap
getParamMap()
Get an associative array mapping magic word IDs to parameter names.
MediaHandler\getContentHeaders
getContentHeaders( $metadata)
Get useful response headers for GET/HEAD requests for a file with the given metadata Stable to overri...
Definition: MediaHandler.php:1011
MediaHandler\logErrorForExternalProcess
logErrorForExternalProcess( $retval, $err, $cmd)
Log an error that occurred in an external process.
Definition: MediaHandler.php:821
MediaHandler\formatMetadataHelper
formatMetadataHelper( $metadataArray, $context=false)
sorts the visible/invisible field.
Definition: MediaHandler.php:543
$path
$path
Definition: NoLocalSettings.php:25
MediaHandler\getHandler
static getHandler( $type)
Get a MediaHandler for a given MIME type from the instance cache.
Definition: MediaHandler.php:53
MediaHandler\parserTransformHook
parserTransformHook( $parser, $file)
Modify the parser object post-transform.
Definition: MediaHandler.php:709
MediaHandler\sanitizeParamsForBucketing
sanitizeParamsForBucketing( $params)
Returns a normalised params array for which parameters have been cleaned up for bucketing purposes St...
Definition: MediaHandler.php:923
MediaHandler\isAnimatedImage
isAnimatedImage( $file)
The material is an image, and is animated.
Definition: MediaHandler.php:402
MediaHandler\parseParamString
parseParamString( $str)
Parse a param string made with makeParamString back into an array.
MediaHandler\METADATA_BAD
const METADATA_BAD
Definition: MediaHandler.php:40
MediaHandler\canRender
canRender( $file)
True if the handled types can be transformed.
Definition: MediaHandler.php:339
MediaHandler\isVectorized
isVectorized( $file)
The material is vectorized and thus scaling is lossless.
Definition: MediaHandler.php:388
MediaHandler\getScriptedTransform
getScriptedTransform( $image, $script, $params)
Get a MediaTransformOutput object representing an alternate of the transformed output which will call...
Definition: MediaHandler.php:269
$ext
if(!is_readable( $file)) $ext
Definition: router.php:48
MediaHandler\getGeneralLongDesc
static getGeneralLongDesc( $file)
Used instead of getLongDesc if there is no handler registered for file.
Definition: MediaHandler.php:662
MediaHandler\fitBoxWidth
static fitBoxWidth( $boxWidth, $boxHeight, $maxHeight)
Calculate the largest thumbnail width for a given original file size such that the thumbnail's height...
Definition: MediaHandler.php:675
$mime
$mime
Definition: router.php:60
MediaHandler\validateParam
validateParam( $name, $value)
Validate a thumbnail parameter at parse time.
FormatMetadata\getVisibleFields
static getVisibleFields()
Get a list of fields that are visible by default.
Definition: FormatMetadata.php:1584
MediaHandler\isMetadataValid
isMetadataValid( $image, $metadata)
Check if the metadata string is valid for this handler.
Definition: MediaHandler.php:212
MediaHandler\isMultiPage
isMultiPage( $file)
True if the type has multi-page capabilities.
Definition: MediaHandler.php:364
MediaHandler\getRotation
getRotation( $file)
On supporting image formats, try to read out the low-level orientation of the file and return the ang...
Definition: MediaHandler.php:806
MediaHandler
Base media handler class.
Definition: MediaHandler.php:37
MediaHandler\getLength
getLength( $file)
If its an audio file, return the length of the file.
Definition: MediaHandler.php:888
MediaHandler\METADATA_GOOD
const METADATA_GOOD
Definition: MediaHandler.php:39
MediaHandler\getDefaultRenderLanguage
getDefaultRenderLanguage(File $file)
On file types that support renderings in multiple languages, which language is used by default if uns...
Definition: MediaHandler.php:872
$type
$type
Definition: testCompression.php:52