Merge "Add 3D filetype for STL files"
[lhc/web/wiklou.git] / includes / media / MediaHandler.php
1 <?php
2 /**
3 * Media-handling base classes and generic functionality.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Media
22 */
23 use MediaWiki\MediaWikiServices;
24
25 /**
26 * Base media handler class
27 *
28 * @ingroup Media
29 */
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.
35 /**
36 * Max length of error logged by logErrorForExternalProcess()
37 */
38 const MAX_ERR_LOG_SIZE = 65535;
39
40 /**
41 * Get a MediaHandler for a given MIME type from the instance cache
42 *
43 * @param string $type
44 * @return MediaHandler|bool
45 */
46 static function getHandler( $type ) {
47 return MediaWikiServices::getInstance()
48 ->getMediaHandlerFactory()->getHandler( $type );
49 }
50
51 /**
52 * Get an associative array mapping magic word IDs to parameter names.
53 * Will be used by the parser to identify parameters.
54 */
55 abstract public function getParamMap();
56
57 /**
58 * Validate a thumbnail parameter at parse time.
59 * Return true to accept the parameter, and false to reject it.
60 * If you return false, the parser will do something quiet and forgiving.
61 *
62 * @param string $name
63 * @param mixed $value
64 */
65 abstract public function validateParam( $name, $value );
66
67 /**
68 * Merge a parameter array into a string appropriate for inclusion in filenames
69 *
70 * @param array $params Array of parameters that have been through normaliseParams.
71 * @return string
72 */
73 abstract public function makeParamString( $params );
74
75 /**
76 * Parse a param string made with makeParamString back into an array
77 *
78 * @param string $str The parameter string without file name (e.g. 122px)
79 * @return array|bool Array of parameters or false on failure.
80 */
81 abstract public function parseParamString( $str );
82
83 /**
84 * Changes the parameter array as necessary, ready for transformation.
85 * Should be idempotent.
86 * Returns false if the parameters are unacceptable and the transform should fail
87 * @param File $image
88 * @param array $params
89 */
90 abstract function normaliseParams( $image, &$params );
91
92 /**
93 * Get an image size array like that returned by getimagesize(), or false if it
94 * can't be determined.
95 *
96 * This function is used for determining the width, height and bitdepth directly
97 * from an image. The results are stored in the database in the img_width,
98 * img_height, img_bits fields.
99 *
100 * @note If this is a multipage file, return the width and height of the
101 * first page.
102 *
103 * @param File|FSFile $image The image object, or false if there isn't one.
104 * Warning, FSFile::getPropsFromPath might pass an FSFile instead of File (!)
105 * @param string $path The filename
106 * @return array|bool Follow the format of PHP getimagesize() internal function.
107 * See https://secure.php.net/getimagesize. MediaWiki will only ever use the
108 * first two array keys (the width and height), and the 'bits' associative
109 * key. All other array keys are ignored. Returning a 'bits' key is optional
110 * as not all formats have a notion of "bitdepth". Returns false on failure.
111 */
112 abstract function getImageSize( $image, $path );
113
114 /**
115 * Get handler-specific metadata which will be saved in the img_metadata field.
116 *
117 * @param File|FSFile $image The image object, or false if there isn't one.
118 * Warning, FSFile::getPropsFromPath might pass an FSFile instead of File (!)
119 * @param string $path The filename
120 * @return string A string of metadata in php serialized form (Run through serialize())
121 */
122 function getMetadata( $image, $path ) {
123 return '';
124 }
125
126 /**
127 * Get metadata version.
128 *
129 * This is not used for validating metadata, this is used for the api when returning
130 * metadata, since api content formats should stay the same over time, and so things
131 * using ForeignApiRepo can keep backwards compatibility
132 *
133 * All core media handlers share a common version number, and extensions can
134 * use the GetMetadataVersion hook to append to the array (they should append a unique
135 * string so not to get confusing). If there was a media handler named 'foo' with metadata
136 * version 3 it might add to the end of the array the element 'foo=3'. if the core metadata
137 * version is 2, the end version string would look like '2;foo=3'.
138 *
139 * @return string Version string
140 */
141 static function getMetadataVersion() {
142 $version = [ '2' ]; // core metadata version
143 Hooks::run( 'GetMetadataVersion', [ &$version ] );
144
145 return implode( ';', $version );
146 }
147
148 /**
149 * Convert metadata version.
150 *
151 * By default just returns $metadata, but can be used to allow
152 * media handlers to convert between metadata versions.
153 *
154 * @param string|array $metadata Metadata array (serialized if string)
155 * @param int $version Target version
156 * @return array Serialized metadata in specified version, or $metadata on fail.
157 */
158 function convertMetadataVersion( $metadata, $version = 1 ) {
159 if ( !is_array( $metadata ) ) {
160
161 // unserialize to keep return parameter consistent.
162 MediaWiki\suppressWarnings();
163 $ret = unserialize( $metadata );
164 MediaWiki\restoreWarnings();
165
166 return $ret;
167 }
168
169 return $metadata;
170 }
171
172 /**
173 * Get a string describing the type of metadata, for display purposes.
174 *
175 * @note This method is currently unused.
176 * @param File $image
177 * @return string
178 */
179 function getMetadataType( $image ) {
180 return false;
181 }
182
183 /**
184 * Check if the metadata string is valid for this handler.
185 * If it returns MediaHandler::METADATA_BAD (or false), Image
186 * will reload the metadata from the file and update the database.
187 * MediaHandler::METADATA_GOOD for if the metadata is a-ok,
188 * MediaHandler::METADATA_COMPATIBLE if metadata is old but backwards
189 * compatible (which may or may not trigger a metadata reload).
190 *
191 * @note Returning self::METADATA_BAD will trigger a metadata reload from
192 * file on page view. Always returning this from a broken file, or suddenly
193 * triggering as bad metadata for a large number of files can cause
194 * performance problems.
195 * @param File $image
196 * @param string $metadata The metadata in serialized form
197 * @return bool
198 */
199 function isMetadataValid( $image, $metadata ) {
200 return self::METADATA_GOOD;
201 }
202
203 /**
204 * Get an array of standard (FormatMetadata type) metadata values.
205 *
206 * The returned data is largely the same as that from getMetadata(),
207 * but formatted in a standard, stable, handler-independent way.
208 * The idea being that some values like ImageDescription or Artist
209 * are universal and should be retrievable in a handler generic way.
210 *
211 * The specific properties are the type of properties that can be
212 * handled by the FormatMetadata class. These values are exposed to the
213 * user via the filemetadata parser function.
214 *
215 * Details of the response format of this function can be found at
216 * https://www.mediawiki.org/wiki/Manual:File_metadata_handling
217 * tl/dr: the response is an associative array of
218 * properties keyed by name, but the value can be complex. You probably
219 * want to call one of the FormatMetadata::flatten* functions on the
220 * property values before using them, or call
221 * FormatMetadata::getFormattedData() on the full response array, which
222 * transforms all values into prettified, human-readable text.
223 *
224 * Subclasses overriding this function must return a value which is a
225 * valid API response fragment (all associative array keys are valid
226 * XML tagnames).
227 *
228 * Note, if the file simply has no metadata, but the handler supports
229 * this interface, it should return an empty array, not false.
230 *
231 * @param File $file
232 * @return array|bool False if interface not supported
233 * @since 1.23
234 */
235 public function getCommonMetaArray( File $file ) {
236 return false;
237 }
238
239 /**
240 * Get a MediaTransformOutput object representing an alternate of the transformed
241 * output which will call an intermediary thumbnail assist script.
242 *
243 * Used when the repository has a thumbnailScriptUrl option configured.
244 *
245 * Return false to fall back to the regular getTransform().
246 * @param File $image
247 * @param string $script
248 * @param array $params
249 * @return bool|ThumbnailImage
250 */
251 function getScriptedTransform( $image, $script, $params ) {
252 return false;
253 }
254
255 /**
256 * Get a MediaTransformOutput object representing the transformed output. Does not
257 * actually do the transform.
258 *
259 * @param File $image The image object
260 * @param string $dstPath Filesystem destination path
261 * @param string $dstUrl Destination URL to use in output HTML
262 * @param array $params Arbitrary set of parameters validated by $this->validateParam()
263 * @return MediaTransformOutput
264 */
265 final function getTransform( $image, $dstPath, $dstUrl, $params ) {
266 return $this->doTransform( $image, $dstPath, $dstUrl, $params, self::TRANSFORM_LATER );
267 }
268
269 /**
270 * Get a MediaTransformOutput object representing the transformed output. Does the
271 * transform unless $flags contains self::TRANSFORM_LATER.
272 *
273 * @param File $image The image object
274 * @param string $dstPath Filesystem destination path
275 * @param string $dstUrl Destination URL to use in output HTML
276 * @param array $params Arbitrary set of parameters validated by $this->validateParam()
277 * Note: These parameters have *not* gone through $this->normaliseParams()
278 * @param int $flags A bitfield, may contain self::TRANSFORM_LATER
279 * @return MediaTransformOutput
280 */
281 abstract function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 );
282
283 /**
284 * Get the thumbnail extension and MIME type for a given source MIME type
285 *
286 * @param string $ext Extension of original file
287 * @param string $mime MIME type of original file
288 * @param array $params Handler specific rendering parameters
289 * @return array Thumbnail extension and MIME type
290 */
291 function getThumbType( $ext, $mime, $params = null ) {
292 $magic = MimeMagic::singleton();
293 if ( !$ext || $magic->isMatchingExtension( $ext, $mime ) === false ) {
294 // The extension is not valid for this MIME type and we do
295 // recognize the MIME type
296 $extensions = $magic->getExtensionsForType( $mime );
297 if ( $extensions ) {
298 return [ strtok( $extensions, ' ' ), $mime ];
299 }
300 }
301
302 // The extension is correct (true) or the MIME type is unknown to
303 // MediaWiki (null)
304 return [ $ext, $mime ];
305 }
306
307 /**
308 * @deprecated since 1.30, use MediaHandler::getContentHeaders instead
309 */
310 public function getStreamHeaders( $metadata ) {
311 wfDeprecated( __METHOD__, '1.30' );
312 return $this->getContentHeaders( $metadata );
313 }
314
315 /**
316 * True if the handled types can be transformed
317 *
318 * @param File $file
319 * @return bool
320 */
321 public function canRender( $file ) {
322 return true;
323 }
324
325 /**
326 * True if handled types cannot be displayed directly in a browser
327 * but can be rendered
328 *
329 * @param File $file
330 * @return bool
331 */
332 public function mustRender( $file ) {
333 return false;
334 }
335
336 /**
337 * True if the type has multi-page capabilities
338 *
339 * @param File $file
340 * @return bool
341 */
342 public function isMultiPage( $file ) {
343 return false;
344 }
345
346 /**
347 * Page count for a multi-page document, false if unsupported or unknown
348 *
349 * @param File $file
350 * @return bool
351 */
352 function pageCount( File $file ) {
353 return false;
354 }
355
356 /**
357 * The material is vectorized and thus scaling is lossless
358 *
359 * @param File $file
360 * @return bool
361 */
362 function isVectorized( $file ) {
363 return false;
364 }
365
366 /**
367 * The material is an image, and is animated.
368 * In particular, video material need not return true.
369 * @note Before 1.20, this was a method of ImageHandler only
370 *
371 * @param File $file
372 * @return bool
373 */
374 function isAnimatedImage( $file ) {
375 return false;
376 }
377
378 /**
379 * If the material is animated, we can animate the thumbnail
380 * @since 1.20
381 *
382 * @param File $file
383 * @return bool If material is not animated, handler may return any value.
384 */
385 function canAnimateThumbnail( $file ) {
386 return true;
387 }
388
389 /**
390 * False if the handler is disabled for all files
391 * @return bool
392 */
393 function isEnabled() {
394 return true;
395 }
396
397 /**
398 * Get an associative array of page dimensions
399 * Currently "width" and "height" are understood, but this might be
400 * expanded in the future.
401 * Returns false if unknown.
402 *
403 * It is expected that handlers for paged media (e.g. DjVuHandler)
404 * will override this method so that it gives the correct results
405 * for each specific page of the file, using the $page argument.
406 *
407 * @note For non-paged media, use getImageSize.
408 *
409 * @param File $image
410 * @param int $page What page to get dimensions of
411 * @return array|bool
412 */
413 function getPageDimensions( File $image, $page ) {
414 $gis = $this->getImageSize( $image, $image->getLocalRefPath() );
415 if ( $gis ) {
416 return [
417 'width' => $gis[0],
418 'height' => $gis[1]
419 ];
420 } else {
421 return false;
422 }
423 }
424
425 /**
426 * Generic getter for text layer.
427 * Currently overloaded by PDF and DjVu handlers
428 * @param File $image
429 * @param int $page Page number to get information for
430 * @return bool|string Page text or false when no text found or if
431 * unsupported.
432 */
433 function getPageText( File $image, $page ) {
434 return false;
435 }
436
437 /**
438 * Get the text of the entire document.
439 * @param File $file
440 * @return bool|string The text of the document or false if unsupported.
441 */
442 public function getEntireText( File $file ) {
443 $numPages = $file->pageCount();
444 if ( !$numPages ) {
445 // Not a multipage document
446 return $this->getPageText( $file, 1 );
447 }
448 $document = '';
449 for ( $i = 1; $i <= $numPages; $i++ ) {
450 $curPage = $this->getPageText( $file, $i );
451 if ( is_string( $curPage ) ) {
452 $document .= $curPage . "\n";
453 }
454 }
455 if ( $document !== '' ) {
456 return $document;
457 }
458 return false;
459 }
460
461 /**
462 * Get an array structure that looks like this:
463 *
464 * [
465 * 'visible' => [
466 * 'Human-readable name' => 'Human readable value',
467 * ...
468 * ],
469 * 'collapsed' => [
470 * 'Human-readable name' => 'Human readable value',
471 * ...
472 * ]
473 * ]
474 * The UI will format this into a table where the visible fields are always
475 * visible, and the collapsed fields are optionally visible.
476 *
477 * The function should return false if there is no metadata to display.
478 */
479
480 /**
481 * @todo FIXME: This interface is not very flexible. The media handler
482 * should generate HTML instead. It can do all the formatting according
483 * to some standard. That makes it possible to do things like visual
484 * indication of grouped and chained streams in ogg container files.
485 * @param File $image
486 * @param bool|IContextSource $context Context to use (optional)
487 * @return array|bool
488 */
489 function formatMetadata( $image, $context = false ) {
490 return false;
491 }
492
493 /** sorts the visible/invisible field.
494 * Split off from ImageHandler::formatMetadata, as used by more than
495 * one type of handler.
496 *
497 * This is used by the media handlers that use the FormatMetadata class
498 *
499 * @param array $metadataArray Metadata array
500 * @param bool|IContextSource $context Context to use (optional)
501 * @return array Array for use displaying metadata.
502 */
503 function formatMetadataHelper( $metadataArray, $context = false ) {
504 $result = [
505 'visible' => [],
506 'collapsed' => []
507 ];
508
509 $formatted = FormatMetadata::getFormattedData( $metadataArray, $context );
510 // Sort fields into visible and collapsed
511 $visibleFields = $this->visibleMetadataFields();
512 foreach ( $formatted as $name => $value ) {
513 $tag = strtolower( $name );
514 self::addMeta( $result,
515 in_array( $tag, $visibleFields ) ? 'visible' : 'collapsed',
516 'exif',
517 $tag,
518 $value
519 );
520 }
521
522 return $result;
523 }
524
525 /**
526 * Get a list of metadata items which should be displayed when
527 * the metadata table is collapsed.
528 *
529 * @return array Array of strings
530 */
531 protected function visibleMetadataFields() {
532 return FormatMetadata::getVisibleFields();
533 }
534
535 /**
536 * This is used to generate an array element for each metadata value
537 * That array is then used to generate the table of metadata values
538 * on the image page
539 *
540 * @param array &$array An array containing elements for each type of visibility
541 * and each of those elements being an array of metadata items. This function adds
542 * a value to that array.
543 * @param string $visibility ('visible' or 'collapsed') if this value is hidden
544 * by default.
545 * @param string $type Type of metadata tag (currently always 'exif')
546 * @param string $id The name of the metadata tag (like 'artist' for example).
547 * its name in the table displayed is the message "$type-$id" (Ex exif-artist ).
548 * @param string $value Thingy goes into a wikitext table; it used to be escaped but
549 * that was incompatible with previous practise of customized display
550 * with wikitext formatting via messages such as 'exif-model-value'.
551 * So the escaping is taken back out, but generally this seems a confusing
552 * interface.
553 * @param bool|string $param Value to pass to the message for the name of the field
554 * as $1. Currently this parameter doesn't seem to ever be used.
555 *
556 * Note, everything here is passed through the parser later on (!)
557 */
558 protected static function addMeta( &$array, $visibility, $type, $id, $value, $param = false ) {
559 $msg = wfMessage( "$type-$id", $param );
560 if ( $msg->exists() ) {
561 $name = $msg->text();
562 } else {
563 // This is for future compatibility when using instant commons.
564 // So as to not display as ugly a name if a new metadata
565 // property is defined that we don't know about
566 // (not a major issue since such a property would be collapsed
567 // by default).
568 wfDebug( __METHOD__ . ' Unknown metadata name: ' . $id . "\n" );
569 $name = wfEscapeWikiText( $id );
570 }
571 $array[$visibility][] = [
572 'id' => "$type-$id",
573 'name' => $name,
574 'value' => $value
575 ];
576 }
577
578 /**
579 * Short description. Shown on Special:Search results.
580 *
581 * @param File $file
582 * @return string
583 */
584 function getShortDesc( $file ) {
585 return self::getGeneralShortDesc( $file );
586 }
587
588 /**
589 * Long description. Shown under image on image description page surounded by ().
590 *
591 * @param File $file
592 * @return string
593 */
594 function getLongDesc( $file ) {
595 return self::getGeneralLongDesc( $file );
596 }
597
598 /**
599 * Used instead of getShortDesc if there is no handler registered for file.
600 *
601 * @param File $file
602 * @return string
603 */
604 static function getGeneralShortDesc( $file ) {
605 global $wgLang;
606
607 return htmlspecialchars( $wgLang->formatSize( $file->getSize() ) );
608 }
609
610 /**
611 * Used instead of getLongDesc if there is no handler registered for file.
612 *
613 * @param File $file
614 * @return string
615 */
616 static function getGeneralLongDesc( $file ) {
617 return wfMessage( 'file-info' )->sizeParams( $file->getSize() )
618 ->params( '<span class="mime-type">' . $file->getMimeType() . '</span>' )->parse();
619 }
620
621 /**
622 * Calculate the largest thumbnail width for a given original file size
623 * such that the thumbnail's height is at most $maxHeight.
624 * @param int $boxWidth Width of the thumbnail box.
625 * @param int $boxHeight Height of the thumbnail box.
626 * @param int $maxHeight Maximum height expected for the thumbnail.
627 * @return int
628 */
629 public static function fitBoxWidth( $boxWidth, $boxHeight, $maxHeight ) {
630 $idealWidth = $boxWidth * $maxHeight / $boxHeight;
631 $roundedUp = ceil( $idealWidth );
632 if ( round( $roundedUp * $boxHeight / $boxWidth ) > $maxHeight ) {
633 return floor( $idealWidth );
634 } else {
635 return $roundedUp;
636 }
637 }
638
639 /**
640 * Shown in file history box on image description page.
641 *
642 * @param File $file
643 * @return string Dimensions
644 */
645 function getDimensionsString( $file ) {
646 return '';
647 }
648
649 /**
650 * Modify the parser object post-transform.
651 *
652 * This is often used to do $parser->addOutputHook(),
653 * in order to add some javascript to render a viewer.
654 * See TimedMediaHandler or OggHandler for an example.
655 *
656 * @param Parser $parser
657 * @param File $file
658 */
659 function parserTransformHook( $parser, $file ) {
660 }
661
662 /**
663 * File validation hook called on upload.
664 *
665 * If the file at the given local path is not valid, or its MIME type does not
666 * match the handler class, a Status object should be returned containing
667 * relevant errors.
668 *
669 * @param string $fileName The local path to the file.
670 * @return Status
671 */
672 function verifyUpload( $fileName ) {
673 return Status::newGood();
674 }
675
676 /**
677 * Check for zero-sized thumbnails. These can be generated when
678 * no disk space is available or some other error occurs
679 *
680 * @param string $dstPath The location of the suspect file
681 * @param int $retval Return value of some shell process, file will be deleted if this is non-zero
682 * @return bool True if removed, false otherwise
683 */
684 function removeBadFile( $dstPath, $retval = 0 ) {
685 if ( file_exists( $dstPath ) ) {
686 $thumbstat = stat( $dstPath );
687 if ( $thumbstat['size'] == 0 || $retval != 0 ) {
688 $result = unlink( $dstPath );
689
690 if ( $result ) {
691 wfDebugLog( 'thumbnail',
692 sprintf( 'Removing bad %d-byte thumbnail "%s". unlink() succeeded',
693 $thumbstat['size'], $dstPath ) );
694 } else {
695 wfDebugLog( 'thumbnail',
696 sprintf( 'Removing bad %d-byte thumbnail "%s". unlink() failed',
697 $thumbstat['size'], $dstPath ) );
698 }
699
700 return true;
701 }
702 }
703
704 return false;
705 }
706
707 /**
708 * Remove files from the purge list.
709 *
710 * This is used by some video handlers to prevent ?action=purge
711 * from removing a transcoded video, which is expensive to
712 * regenerate.
713 *
714 * @see LocalFile::purgeThumbnails
715 *
716 * @param array $files
717 * @param array $options Purge options. Currently will always be
718 * an array with a single key 'forThumbRefresh' set to true.
719 */
720 public function filterThumbnailPurgeList( &$files, $options ) {
721 // Do nothing
722 }
723
724 /**
725 * True if the handler can rotate the media
726 * @since 1.24 non-static. From 1.21-1.23 was static
727 * @return bool
728 */
729 public function canRotate() {
730 return false;
731 }
732
733 /**
734 * On supporting image formats, try to read out the low-level orientation
735 * of the file and return the angle that the file needs to be rotated to
736 * be viewed.
737 *
738 * This information is only useful when manipulating the original file;
739 * the width and height we normally work with is logical, and will match
740 * any produced output views.
741 *
742 * For files we don't know, we return 0.
743 *
744 * @param File $file
745 * @return int 0, 90, 180 or 270
746 */
747 public function getRotation( $file ) {
748 return 0;
749 }
750
751 /**
752 * Log an error that occurred in an external process
753 *
754 * Moved from BitmapHandler to MediaHandler with MediaWiki 1.23
755 *
756 * @since 1.23
757 * @param int $retval
758 * @param string $err Error reported by command. Anything longer than
759 * MediaHandler::MAX_ERR_LOG_SIZE is stripped off.
760 * @param string $cmd
761 */
762 protected function logErrorForExternalProcess( $retval, $err, $cmd ) {
763 # Keep error output limited (T59985)
764 $errMessage = trim( substr( $err, 0, self::MAX_ERR_LOG_SIZE ) );
765
766 wfDebugLog( 'thumbnail',
767 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
768 wfHostname(), $retval, $errMessage, $cmd ) );
769 }
770
771 /**
772 * Get list of languages file can be viewed in.
773 *
774 * @param File $file
775 * @return string[] Array of language codes, or empty array if unsupported.
776 * @since 1.23
777 */
778 public function getAvailableLanguages( File $file ) {
779 return [];
780 }
781
782 /**
783 * On file types that support renderings in multiple languages,
784 * which language is used by default if unspecified.
785 *
786 * If getAvailableLanguages returns a non-empty array, this must return
787 * a valid language code. Otherwise can return null if files of this
788 * type do not support alternative language renderings.
789 *
790 * @param File $file
791 * @return string|null Language code or null if multi-language not supported for filetype.
792 * @since 1.23
793 */
794 public function getDefaultRenderLanguage( File $file ) {
795 return null;
796 }
797
798 /**
799 * If its an audio file, return the length of the file. Otherwise 0.
800 *
801 * File::getLength() existed for a long time, but was calling a method
802 * that only existed in some subclasses of this class (The TMH ones).
803 *
804 * @param File $file
805 * @return float Length in seconds
806 * @since 1.23
807 */
808 public function getLength( $file ) {
809 return 0.0;
810 }
811
812 /**
813 * True if creating thumbnails from the file is large or otherwise resource-intensive.
814 * @param File $file
815 * @return bool
816 */
817 public function isExpensiveToThumbnail( $file ) {
818 return false;
819 }
820
821 /**
822 * Returns whether or not this handler supports the chained generation of thumbnails according
823 * to buckets
824 * @return bool
825 * @since 1.24
826 */
827 public function supportsBucketing() {
828 return false;
829 }
830
831 /**
832 * Returns a normalised params array for which parameters have been cleaned up for bucketing
833 * purposes
834 * @param array $params
835 * @return array
836 */
837 public function sanitizeParamsForBucketing( $params ) {
838 return $params;
839 }
840
841 /**
842 * Gets configuration for the file warning message. Return value of
843 * the following structure:
844 * [
845 * // Required, module with messages loaded for the client
846 * 'module' => 'example.filewarning.messages',
847 * // Required, array of names of messages
848 * 'messages' => [
849 * // Required, main warning message
850 * 'main' => 'example-filewarning-main',
851 * // Optional, header for warning dialog
852 * 'header' => 'example-filewarning-header',
853 * // Optional, footer for warning dialog
854 * 'footer' => 'example-filewarning-footer',
855 * // Optional, text for more-information link (see below)
856 * 'info' => 'example-filewarning-info',
857 * ],
858 * // Optional, link for more information
859 * 'link' => 'http://example.com',
860 * ]
861 *
862 * Returns null if no warning is necessary.
863 * @param File $file
864 * @return array|null
865 */
866 public function getWarningConfig( $file ) {
867 return null;
868 }
869
870 /**
871 * Converts a dimensions array about a potentially multipage document from an
872 * exhaustive list of ordered page numbers to a list of page ranges
873 * @param Array $pagesByDimensions
874 * @return String
875 * @since 1.30
876 */
877 public static function getPageRangesByDimensions( $pagesByDimensions ) {
878 $pageRangesByDimensions = [];
879
880 foreach ( $pagesByDimensions as $dimensions => $pageList ) {
881 $ranges = [];
882 $firstPage = $pageList[0];
883 $lastPage = $firstPage - 1;
884
885 foreach ( $pageList as $page ) {
886 if ( $page > $lastPage + 1 ) {
887 if ( $firstPage != $lastPage ) {
888 $ranges[] = "$firstPage-$lastPage";
889 } else {
890 $ranges[] = "$firstPage";
891 }
892
893 $firstPage = $page;
894 }
895
896 $lastPage = $page;
897 }
898
899 if ( $firstPage != $lastPage ) {
900 $ranges[] = "$firstPage-$lastPage";
901 } else {
902 $ranges[] = "$firstPage";
903 }
904
905 $pageRangesByDimensions[ $dimensions ] = $ranges;
906 }
907
908 $dimensionsString = [];
909 foreach ( $pageRangesByDimensions as $dimensions => $pageRanges ) {
910 $dimensionsString[] = "$dimensions:" . implode( ',', $pageRanges );
911 }
912
913 return implode( '/', $dimensionsString );
914 }
915
916 /**
917 * Get useful response headers for GET/HEAD requests for a file with the given metadata
918 * @param $metadata Array Contains this handler's unserialized getMetadata() for a file
919 * @return Array
920 * @since 1.30
921 */
922 public function getContentHeaders( $metadata ) {
923 return [];
924 }
925 }