MediaWiki  1.34.0
MediaHandler.php
Go to the documentation of this file.
1 <?php
24 
30 abstract 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 public function normaliseParams( $image, &$params );
91 
112  abstract function getImageSize( $image, $path );
113 
122  public 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 
178  function getMetadataType( $image ) {
179  return false;
180  }
181 
198  public 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  public 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 
312  public function canRender( $file ) {
313  return true;
314  }
315 
323  public function mustRender( $file ) {
324  return false;
325  }
326 
333  public function isMultiPage( $file ) {
334  return false;
335  }
336 
343  public function pageCount( File $file ) {
344  return false;
345  }
346 
353  function isVectorized( $file ) {
354  return false;
355  }
356 
365  function isAnimatedImage( $file ) {
366  return false;
367  }
368 
377  return true;
378  }
379 
384  public function isEnabled() {
385  return true;
386  }
387 
404  public function getPageDimensions( File $image, $page ) {
405  $gis = $this->getImageSize( $image, $image->getLocalRefPath() );
406  if ( $gis ) {
407  return [
408  'width' => $gis[0],
409  'height' => $gis[1]
410  ];
411  } else {
412  return false;
413  }
414  }
415 
424  function getPageText( File $image, $page ) {
425  return false;
426  }
427 
433  public function getEntireText( File $file ) {
434  $numPages = $file->pageCount();
435  if ( !$numPages ) {
436  // Not a multipage document
437  return $this->getPageText( $file, 1 );
438  }
439  $document = '';
440  for ( $i = 1; $i <= $numPages; $i++ ) {
441  $curPage = $this->getPageText( $file, $i );
442  if ( is_string( $curPage ) ) {
443  $document .= $curPage . "\n";
444  }
445  }
446  if ( $document !== '' ) {
447  return $document;
448  }
449  return false;
450  }
451 
480  public function formatMetadata( $image, $context = false ) {
481  return false;
482  }
483 
494  function formatMetadataHelper( $metadataArray, $context = false ) {
495  $result = [
496  'visible' => [],
497  'collapsed' => []
498  ];
499 
500  $formatted = FormatMetadata::getFormattedData( $metadataArray, $context );
501  // Sort fields into visible and collapsed
502  $visibleFields = $this->visibleMetadataFields();
503  foreach ( $formatted as $name => $value ) {
504  $tag = strtolower( $name );
505  self::addMeta( $result,
506  in_array( $tag, $visibleFields ) ? 'visible' : 'collapsed',
507  'exif',
508  $tag,
509  $value
510  );
511  }
512 
513  return $result;
514  }
515 
522  protected function visibleMetadataFields() {
524  }
525 
549  protected static function addMeta( &$array, $visibility, $type, $id, $value, $param = false ) {
550  $msg = wfMessage( "$type-$id", $param );
551  if ( $msg->exists() ) {
552  $name = $msg->text();
553  } else {
554  // This is for future compatibility when using instant commons.
555  // So as to not display as ugly a name if a new metadata
556  // property is defined that we don't know about
557  // (not a major issue since such a property would be collapsed
558  // by default).
559  wfDebug( __METHOD__ . ' Unknown metadata name: ' . $id . "\n" );
560  $name = wfEscapeWikiText( $id );
561  }
562  $array[$visibility][] = [
563  'id' => "$type-$id",
564  'name' => $name,
565  'value' => $value
566  ];
567  }
568 
575  function getShortDesc( $file ) {
577  }
578 
585  public function getLongDesc( $file ) {
587  }
588 
595  static function getGeneralShortDesc( $file ) {
596  global $wgLang;
597 
598  return htmlspecialchars( $wgLang->formatSize( $file->getSize() ) );
599  }
600 
607  static function getGeneralLongDesc( $file ) {
608  return wfMessage( 'file-info' )->sizeParams( $file->getSize() )
609  ->params( '<span class="mime-type">' . $file->getMimeType() . '</span>' )->parse();
610  }
611 
620  public static function fitBoxWidth( $boxWidth, $boxHeight, $maxHeight ) {
621  $idealWidth = $boxWidth * $maxHeight / $boxHeight;
622  $roundedUp = ceil( $idealWidth );
623  if ( round( $roundedUp * $boxHeight / $boxWidth ) > $maxHeight ) {
624  return floor( $idealWidth );
625  } else {
626  return $roundedUp;
627  }
628  }
629 
637  return '';
638  }
639 
650  function parserTransformHook( $parser, $file ) {
651  }
652 
663  public function verifyUpload( $fileName ) {
664  return Status::newGood();
665  }
666 
675  function removeBadFile( $dstPath, $retval = 0 ) {
676  if ( file_exists( $dstPath ) ) {
677  $thumbstat = stat( $dstPath );
678  if ( $thumbstat['size'] == 0 || $retval != 0 ) {
679  $result = unlink( $dstPath );
680 
681  if ( $result ) {
682  wfDebugLog( 'thumbnail',
683  sprintf( 'Removing bad %d-byte thumbnail "%s". unlink() succeeded',
684  $thumbstat['size'], $dstPath ) );
685  } else {
686  wfDebugLog( 'thumbnail',
687  sprintf( 'Removing bad %d-byte thumbnail "%s". unlink() failed',
688  $thumbstat['size'], $dstPath ) );
689  }
690 
691  return true;
692  }
693  }
694 
695  return false;
696  }
697 
711  public function filterThumbnailPurgeList( &$files, $options ) {
712  // Do nothing
713  }
714 
720  public function canRotate() {
721  return false;
722  }
723 
738  public function getRotation( $file ) {
739  return 0;
740  }
741 
753  protected function logErrorForExternalProcess( $retval, $err, $cmd ) {
754  # Keep error output limited (T59985)
755  $errMessage = trim( substr( $err, 0, self::MAX_ERR_LOG_SIZE ) );
756 
757  wfDebugLog( 'thumbnail',
758  sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
759  wfHostname(), $retval, $errMessage, $cmd ) );
760  }
761 
769  public function getAvailableLanguages( File $file ) {
770  return [];
771  }
772 
782  public function getMatchedLanguage( $userPreferredLanguage, array $availableLanguages ) {
783  return null;
784  }
785 
798  public function getDefaultRenderLanguage( File $file ) {
799  return null;
800  }
801 
812  public function getLength( $file ) {
813  return 0.0;
814  }
815 
821  public function isExpensiveToThumbnail( $file ) {
822  return false;
823  }
824 
831  public function supportsBucketing() {
832  return false;
833  }
834 
841  public function sanitizeParamsForBucketing( $params ) {
842  return $params;
843  }
844 
870  public function getWarningConfig( $file ) {
871  return null;
872  }
873 
881  public static function getPageRangesByDimensions( $pagesByDimensions ) {
882  $pageRangesByDimensions = [];
883 
884  foreach ( $pagesByDimensions as $dimensions => $pageList ) {
885  $ranges = [];
886  $firstPage = $pageList[0];
887  $lastPage = $firstPage - 1;
888 
889  foreach ( $pageList as $page ) {
890  if ( $page > $lastPage + 1 ) {
891  if ( $firstPage != $lastPage ) {
892  $ranges[] = "$firstPage-$lastPage";
893  } else {
894  $ranges[] = "$firstPage";
895  }
896 
897  $firstPage = $page;
898  }
899 
900  $lastPage = $page;
901  }
902 
903  if ( $firstPage != $lastPage ) {
904  $ranges[] = "$firstPage-$lastPage";
905  } else {
906  $ranges[] = "$firstPage";
907  }
908 
909  $pageRangesByDimensions[ $dimensions ] = $ranges;
910  }
911 
912  $dimensionsString = [];
913  foreach ( $pageRangesByDimensions as $dimensions => $pageRanges ) {
914  $dimensionsString[] = "$dimensions:" . implode( ',', $pageRanges );
915  }
916 
917  return implode( '/', $dimensionsString );
918  }
919 
926  public function getContentHeaders( $metadata ) {
927  return [ 'X-Content-Dimensions' => '' ]; // T175689
928  }
929 }
MediaHandler\removeBadFile
removeBadFile( $dstPath, $retval=0)
Check for zero-sized thumbnails.
Definition: MediaHandler.php:675
MediaHandler\mustRender
mustRender( $file)
True if handled types cannot be displayed directly in a browser but can be rendered.
Definition: MediaHandler.php:323
MediaHandler\formatMetadata
formatMetadata( $image, $context=false)
Get an array structure that looks like this:
Definition: MediaHandler.php:480
MediaHandler\getWarningConfig
getWarningConfig( $file)
Gets configuration for the file warning message.
Definition: MediaHandler.php:870
MediaHandler\getCommonMetaArray
getCommonMetaArray(File $file)
Get an array of standard (FormatMetadata type) metadata values.
Definition: MediaHandler.php:234
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:663
MediaHandler\pageCount
pageCount(File $file)
Page count for a multi-page document, false if unsupported or unknown.
Definition: MediaHandler.php:343
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:82
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:117
MediaHandler\TRANSFORM_LATER
const TRANSFORM_LATER
Definition: MediaHandler.php:31
MediaHandler\getMetadataVersion
static getMetadataVersion()
Get metadata version.
Definition: MediaHandler.php:141
MediaHandler\filterThumbnailPurgeList
filterThumbnailPurgeList(&$files, $options)
Remove files from the purge list.
Definition: MediaHandler.php:711
MediaHandler\getEntireText
getEntireText(File $file)
Get the text of the entire document.
Definition: MediaHandler.php:433
MediaHandler\getShortDesc
getShortDesc( $file)
Short description.
Definition: MediaHandler.php:575
$ranges
$ranges
Definition: make-tables.php:64
MediaHandler\MAX_ERR_LOG_SIZE
const MAX_ERR_LOG_SIZE
Max length of error logged by logErrorForExternalProcess()
Definition: MediaHandler.php:38
MediaHandler\getThumbType
getThumbType( $ext, $mime, $params=null)
Get the thumbnail extension and MIME type for a given source MIME type.
Definition: MediaHandler.php:290
MediaHandler\canRotate
canRotate()
True if the handler can rotate the media.
Definition: MediaHandler.php:720
MediaHandler\getMatchedLanguage
getMatchedLanguage( $userPreferredLanguage, array $availableLanguages)
When overridden in a descendant class, returns a language code most suiting.
Definition: MediaHandler.php:782
$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()
Fetch server name for use in error reporting etc.
Definition: GlobalFunctions.php:1326
wfMessage
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Definition: GlobalFunctions.php:1264
MediaHandler\getLongDesc
getLongDesc( $file)
Long description.
Definition: MediaHandler.php:585
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:1007
MediaHandler\supportsBucketing
supportsBucketing()
Returns whether or not this handler supports the chained generation of thumbnails according to bucket...
Definition: MediaHandler.php:831
MediaHandler\getMetadataType
getMetadataType( $image)
Get a string describing the type of metadata, for display purposes.
Definition: MediaHandler.php:178
MediaHandler\getAvailableLanguages
getAvailableLanguages(File $file)
Get list of languages file can be viewed in.
Definition: MediaHandler.php:769
MediaWiki\MediaWikiServices\getInstance
static getInstance()
Returns the global default instance of the top level service locator.
Definition: MediaWikiServices.php:138
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:34
File
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition: File.php:61
MediaHandler\isExpensiveToThumbnail
isExpensiveToThumbnail( $file)
True if creating thumbnails from the file is large or otherwise resource-intensive.
Definition: MediaHandler.php:821
File\getLocalRefPath
getLocalRefPath()
Get an FS copy or original of this file and return the path.
Definition: File.php:443
MediaHandler\getPageRangesByDimensions
static getPageRangesByDimensions( $pagesByDimensions)
Converts a dimensions array about a potentially multipage document from an exhaustive list of ordered...
Definition: MediaHandler.php:881
MediaHandler\canAnimateThumbnail
canAnimateThumbnail( $file)
If the material is animated, we can animate the thumbnail.
Definition: MediaHandler.php:376
$wgLang
$wgLang
Definition: Setup.php:881
MediaHandler\getPageText
getPageText(File $image, $page)
Generic getter for text layer.
Definition: MediaHandler.php:424
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:549
MediaHandler\getPageDimensions
getPageDimensions(File $image, $page)
Get an associative array of page dimensions Currently "width" and "height" are understood,...
Definition: MediaHandler.php:404
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:913
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.
Definition: MediaHandler.php:384
MediaHandler\getDimensionsString
getDimensionsString( $file)
Shown in file history box on image description page.
Definition: MediaHandler.php:636
MediaHandler\getMetadata
getMetadata( $image, $path)
Get handler-specific metadata which will be saved in the img_metadata field.
Definition: MediaHandler.php:122
MediaHandler\convertMetadataVersion
convertMetadataVersion( $metadata, $version=1)
Convert metadata version.
Definition: MediaHandler.php:158
MediaHandler\getGeneralShortDesc
static getGeneralShortDesc( $file)
Used instead of getShortDesc if there is no handler registered for file.
Definition: MediaHandler.php:595
StatusValue\newGood
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:81
MediaHandler\getTransform
getTransform( $image, $dstPath, $dstUrl, $params)
Get a MediaTransformOutput object representing the transformed output.
Definition: MediaHandler.php:264
wfEscapeWikiText
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
Definition: GlobalFunctions.php:1551
MediaHandler\doTransform
doTransform( $image, $dstPath, $dstUrl, $params, $flags=0)
Get a MediaTransformOutput object representing the transformed output.
$context
$context
Definition: load.php:45
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:522
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.
Definition: MediaHandler.php:926
MediaHandler\logErrorForExternalProcess
logErrorForExternalProcess( $retval, $err, $cmd)
Log an error that occurred in an external process.
Definition: MediaHandler.php:753
MediaHandler\formatMetadataHelper
formatMetadataHelper( $metadataArray, $context=false)
sorts the visible/invisible field.
Definition: MediaHandler.php:494
$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:46
MediaHandler\parserTransformHook
parserTransformHook( $parser, $file)
Modify the parser object post-transform.
Definition: MediaHandler.php:650
MediaHandler\sanitizeParamsForBucketing
sanitizeParamsForBucketing( $params)
Returns a normalised params array for which parameters have been cleaned up for bucketing purposes.
Definition: MediaHandler.php:841
MediaHandler\isAnimatedImage
isAnimatedImage( $file)
The material is an image, and is animated.
Definition: MediaHandler.php:365
MediaHandler\parseParamString
parseParamString( $str)
Parse a param string made with makeParamString back into an array.
MediaHandler\METADATA_BAD
const METADATA_BAD
Definition: MediaHandler.php:33
MediaHandler\canRender
canRender( $file)
True if the handled types can be transformed.
Definition: MediaHandler.php:312
MediaHandler\isVectorized
isVectorized( $file)
The material is vectorized and thus scaling is lossless.
Definition: MediaHandler.php:353
MediaHandler\getScriptedTransform
getScriptedTransform( $image, $script, $params)
Get a MediaTransformOutput object representing an alternate of the transformed output which will call...
Definition: MediaHandler.php:250
$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:607
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:620
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:1580
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
MediaHandler\isMetadataValid
isMetadataValid( $image, $metadata)
Check if the metadata string is valid for this handler.
Definition: MediaHandler.php:198
MediaHandler\isMultiPage
isMultiPage( $file)
True if the type has multi-page capabilities.
Definition: MediaHandler.php:333
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:738
MediaHandler
Base media handler class.
Definition: MediaHandler.php:30
MediaHandler\getLength
getLength( $file)
If its an audio file, return the length of the file.
Definition: MediaHandler.php:812
MediaHandler\METADATA_GOOD
const METADATA_GOOD
Definition: MediaHandler.php:32
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:798
$type
$type
Definition: testCompression.php:48