3 * Base class for the output of file transformation methods.
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.
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.
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
25 * Base class for the output of MediaHandler::doTransform() and File::transform().
29 abstract class MediaTransformOutput
{
30 /** @var array Associative array mapping optional supplementary image files
31 * from pixel density (eg 1.5 or 2) to additional URLs.
33 public $responsiveUrls = [];
38 /** @var int Image width */
41 /** @var int Image height */
44 /** @var string URL path to the thumb */
47 /** @var bool|string */
50 /** @var bool|string Filesystem path to the thumb */
53 /** @var bool|string Language code, false if not set */
56 /** @var bool|string Permanent storage path */
57 protected $storagePath = false;
60 * @return int Width of the output box
62 public function getWidth() {
67 * @return int Height of the output box
69 public function getHeight() {
76 public function getFile() {
81 * Get the final extension of the thumbnail.
82 * Returns false for scripted transformations.
85 public function getExtension() {
86 return $this->path ? FileBackend
::extensionFromPath( $this->path
) : false;
90 * @return string|bool The thumbnail URL
92 public function getUrl() {
97 * @return string|bool The permanent thumbnail storage path
99 public function getStoragePath() {
100 return $this->storagePath
;
104 * @param string $storagePath The permanent storage path
107 public function setStoragePath( $storagePath ) {
108 $this->storagePath
= $storagePath;
109 if ( $this->path
=== false ) {
110 $this->path
= $storagePath;
115 * Fetch HTML for this transform output
117 * @param array $options Associative array of options. Boolean options
118 * should be indicated with a value of true for true, and false or
121 * alt Alternate text or caption
122 * desc-link Boolean, show a description link
123 * file-link Boolean, show a file download link
124 * custom-url-link Custom URL to link to
125 * custom-title-link Custom Title object to link to
126 * valign vertical-align property, if the output is an inline element
127 * img-class Class applied to the "<img>" tag, if there is such a tag
129 * For images, desc-link and file-link are implemented as a click-through. For
130 * sounds and videos, they may be displayed in other ways.
134 abstract public function toHtml( $options = [] );
137 * This will be overridden to return true in error classes
140 public function isError() {
145 * Check if an output thumbnail file actually exists.
147 * This will return false if there was an error, the
148 * thumbnail is to be handled client-side only, or if
149 * transformation was deferred via TRANSFORM_LATER.
150 * This file may exist as a new file in /tmp, a file
151 * in permanent storage, or even refer to the original.
155 public function hasFile() {
156 // If TRANSFORM_LATER, $this->path will be false.
157 // Note: a null path means "use the source file".
158 return ( !$this->isError() && ( $this->path ||
$this->path
=== null ) );
162 * Check if the output thumbnail is the same as the source.
163 * This can occur if the requested width was bigger than the source.
167 public function fileIsSource() {
168 return ( !$this->isError() && $this->path
=== null );
172 * Get the path of a file system copy of the thumbnail.
173 * Callers should never write to this path.
175 * @return string|bool Returns false if there isn't one
177 public function getLocalCopyPath() {
178 if ( $this->isError() ) {
180 } elseif ( $this->path
=== null ) {
181 return $this->file
->getLocalRefPath(); // assume thumb was not scaled
182 } elseif ( FileBackend
::isStoragePath( $this->path
) ) {
183 $be = $this->file
->getRepo()->getBackend();
184 // The temp file will be process cached by FileBackend
185 $fsFile = $be->getLocalReference( [ 'src' => $this->path
] );
187 return $fsFile ?
$fsFile->getPath() : false;
189 return $this->path
; // may return false
194 * Stream the file if there were no errors
196 * @param array $headers Additional HTTP headers to send on success
200 public function streamFileWithStatus( $headers = [] ) {
201 if ( !$this->path
) {
202 return Status
::newFatal( 'backend-fail-stream', '<no path>' );
203 } elseif ( FileBackend
::isStoragePath( $this->path
) ) {
204 $be = $this->file
->getRepo()->getBackend();
205 return $be->streamFile( [ 'src' => $this->path
, 'headers' => $headers ] );
207 $success = StreamFile
::stream( $this->getLocalCopyPath(), $headers );
208 return $success ? Status
::newGood() : Status
::newFatal( 'backend-fail-stream', $this->path
);
213 * Stream the file if there were no errors
215 * @deprecated since 1.26, use streamFileWithStatus
216 * @param array $headers Additional HTTP headers to send on success
217 * @return bool Success
219 public function streamFile( $headers = [] ) {
220 $this->streamFileWithStatus( $headers )->isOK();
224 * Wrap some XHTML text in an anchor tag with the given attributes
226 * @param array $linkAttribs
227 * @param string $contents
230 protected function linkWrap( $linkAttribs, $contents ) {
231 if ( $linkAttribs ) {
232 return Xml
::tags( 'a', $linkAttribs, $contents );
239 * @param string $title
240 * @param string|array $params Query parameters to add
243 public function getDescLinkAttribs( $title = null, $params = [] ) {
244 if ( is_array( $params ) ) {
249 if ( $this->page
&& $this->page
!== 1 ) {
250 $query['page'] = $this->page
;
253 $query['lang'] = $this->lang
;
256 if ( is_string( $params ) && $params !== '' ) {
257 $query = $params . '&' . wfArrayToCgi( $query );
261 'href' => $this->file
->getTitle()->getLocalURL( $query ),
265 $attribs['title'] = $title;
273 * Media transform output for images
277 class ThumbnailImage
extends MediaTransformOutput
{
279 * Get a thumbnail object from a file and parameters.
280 * If $path is set to null, the output file is treated as a source copy.
281 * If $path is set to false, no output file will be created.
282 * $parameters should include, as a minimum, (file) 'width' and 'height'.
283 * It may also include a 'page' parameter for multipage files.
286 * @param string $url URL path to the thumb
287 * @param string|bool $path Filesystem path to the thumb
288 * @param array $parameters Associative array of parameters
290 function __construct( $file, $url, $path = false, $parameters = [] ) {
291 # Previous parameters:
292 # $file, $url, $width, $height, $path = false, $page = false
299 if ( is_array( $parameters ) ) {
300 $actualParams = $parameters +
$defaults;
302 # Using old format, should convert. Later a warning could be added here.
303 $numArgs = func_num_args();
306 'height' => $parameters,
307 'page' => ( $numArgs > 5 ) ?
func_get_arg( 5 ) : false
309 $path = ( $numArgs > 4 ) ?
func_get_arg( 4 ) : false;
316 # These should be integers when they get here.
317 # If not, there's a bug somewhere. But let's at
318 # least produce valid HTML code regardless.
319 $this->width
= round( $actualParams['width'] );
320 $this->height
= round( $actualParams['height'] );
322 $this->page
= $actualParams['page'];
323 $this->lang
= $actualParams['lang'];
327 * Return HTML <img ... /> tag for the thumbnail, will include
328 * width and height attributes and a blank alt text (as required).
330 * @param array $options Associative array of options. Boolean options
331 * should be indicated with a value of true for true, and false or
334 * alt HTML alt attribute
335 * title HTML title attribute
336 * desc-link Boolean, show a description link
337 * file-link Boolean, show a file download link
338 * valign vertical-align property, if the output is an inline element
339 * img-class Class applied to the \<img\> tag, if there is such a tag
340 * desc-query String, description link query params
341 * override-width Override width attribute. Should generally not set
342 * override-height Override height attribute. Should generally not set
343 * no-dimensions Boolean, skip width and height attributes (useful if
345 * custom-url-link Custom URL to link to
346 * custom-title-link Custom Title object to link to
347 * custom target-link Value of the target attribute, for custom-target-link
348 * parser-extlink-* Attributes added by parser for external links:
349 * parser-extlink-rel: add rel="nofollow"
350 * parser-extlink-target: link target, but overridden by custom-target-link
352 * For images, desc-link and file-link are implemented as a click-through. For
353 * sounds and videos, they may be displayed in other ways.
355 * @throws MWException
358 function toHtml( $options = [] ) {
359 if ( count( func_get_args() ) == 2 ) {
360 throw new MWException( __METHOD__
. ' called in the old style' );
363 $alt = isset( $options['alt'] ) ?
$options['alt'] : '';
365 $query = isset( $options['desc-query'] ) ?
$options['desc-query'] : '';
372 if ( !empty( $options['custom-url-link'] ) ) {
373 $linkAttribs = [ 'href' => $options['custom-url-link'] ];
374 if ( !empty( $options['title'] ) ) {
375 $linkAttribs['title'] = $options['title'];
377 if ( !empty( $options['custom-target-link'] ) ) {
378 $linkAttribs['target'] = $options['custom-target-link'];
379 } elseif ( !empty( $options['parser-extlink-target'] ) ) {
380 $linkAttribs['target'] = $options['parser-extlink-target'];
382 if ( !empty( $options['parser-extlink-rel'] ) ) {
383 $linkAttribs['rel'] = $options['parser-extlink-rel'];
385 } elseif ( !empty( $options['custom-title-link'] ) ) {
386 /** @var Title $title */
387 $title = $options['custom-title-link'];
389 'href' => $title->getLinkURL(),
390 'title' => empty( $options['title'] ) ?
$title->getFullText() : $options['title']
392 } elseif ( !empty( $options['desc-link'] ) ) {
393 $linkAttribs = $this->getDescLinkAttribs(
394 empty( $options['title'] ) ?
null : $options['title'],
397 } elseif ( !empty( $options['file-link'] ) ) {
398 $linkAttribs = [ 'href' => $this->file
->getUrl() ];
400 $linkAttribs = false;
401 if ( !empty( $options['title'] ) ) {
402 $attribs['title'] = $options['title'];
406 if ( empty( $options['no-dimensions'] ) ) {
407 $attribs['width'] = $this->width
;
408 $attribs['height'] = $this->height
;
410 if ( !empty( $options['valign'] ) ) {
411 $attribs['style'] = "vertical-align: {$options['valign']}";
413 if ( !empty( $options['img-class'] ) ) {
414 $attribs['class'] = $options['img-class'];
416 if ( isset( $options['override-height'] ) ) {
417 $attribs['height'] = $options['override-height'];
419 if ( isset( $options['override-width'] ) ) {
420 $attribs['width'] = $options['override-width'];
423 // Additional densities for responsive images, if specified.
424 // If any of these urls is the same as src url, it'll be excluded.
425 $responsiveUrls = array_diff( $this->responsiveUrls
, [ $this->url
] );
426 if ( !empty( $responsiveUrls ) ) {
427 $attribs['srcset'] = Html
::srcSet( $responsiveUrls );
430 Hooks
::run( 'ThumbnailBeforeProduceHTML', [ $this, &$attribs, &$linkAttribs ] );
432 return $this->linkWrap( $linkAttribs, Xml
::element( 'img', $attribs ) );
437 * Basic media transform error class
441 class MediaTransformError
extends MediaTransformOutput
{
445 function __construct( $msg, $width, $height /*, ... */ ) {
446 $args = array_slice( func_get_args(), 3 );
447 $this->msg
= wfMessage( $msg )->params( $args );
448 $this->width
= intval( $width );
449 $this->height
= intval( $height );
454 function toHtml( $options = [] ) {
455 return "<div class=\"MediaTransformError\" style=\"" .
456 "width: {$this->width}px; height: {$this->height}px; display:inline-block;\">" .
457 $this->getHtmlMsg() .
462 return $this->msg
->text();
465 function getHtmlMsg() {
466 return $this->msg
->escaped();
477 function getHttpStatusCode() {
483 * Shortcut class for parameter validation errors
487 class TransformParameterError
extends MediaTransformError
{
488 function __construct( $params ) {
489 parent
::__construct( 'thumbnail_error',
490 max( isset( $params['width'] ) ?
$params['width'] : 0, 120 ),
491 max( isset( $params['height'] ) ?
$params['height'] : 0, 120 ),
492 wfMessage( 'thumbnail_invalid_params' )
496 function getHttpStatusCode() {
502 * Shortcut class for parameter file size errors
507 class TransformTooBigImageAreaError
extends MediaTransformError
{
508 function __construct( $params, $maxImageArea ) {
509 $msg = wfMessage( 'thumbnail_toobigimagearea' );
511 $msg->getLanguage()->formatComputingNumbers( $maxImageArea, 1000, "size-$1pixel" )
514 parent
::__construct( 'thumbnail_error',
515 max( isset( $params['width'] ) ?
$params['width'] : 0, 120 ),
516 max( isset( $params['height'] ) ?
$params['height'] : 0, 120 ),
521 function getHttpStatusCode() {