Update button focus and hover state according to spec
[mediawiki.git] / includes / media / MediaTransformOutput.php
blob1dd8519155ef69283aa2580010392e1db54da275
1 <?php
2 /**
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
20 * @file
21 * @ingroup Media
24 /**
25 * Base class for the output of MediaHandler::doTransform() and File::transform().
27 * @ingroup Media
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 = array();
35 /** @var File */
36 protected $file;
38 /** @var int Image width */
39 protected $width;
41 /** @var int Image height */
42 protected $height;
44 /** @var string URL path to the thumb */
45 protected $url;
47 /** @var bool|string */
48 protected $page;
50 /** @var bool|string Filesystem path to the thumb */
51 protected $path;
53 /** @var bool|string Language code, false if not set */
54 protected $lang;
56 /** @var bool|string Permanent storage path */
57 protected $storagePath = false;
59 /**
60 * @return int Width of the output box
62 public function getWidth() {
63 return $this->width;
66 /**
67 * @return int Height of the output box
69 public function getHeight() {
70 return $this->height;
73 /**
74 * @return File
76 public function getFile() {
77 return $this->file;
80 /**
81 * Get the final extension of the thumbnail.
82 * Returns false for scripted transformations.
83 * @return string|bool
85 public function getExtension() {
86 return $this->path ? FileBackend::extensionFromPath( $this->path ) : false;
89 /**
90 * @return string|bool The thumbnail URL
92 public function getUrl() {
93 return $this->url;
96 /**
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
105 * @return void
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
119 * absent for false.
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.
132 * @return string
134 abstract public function toHtml( $options = array() );
137 * This will be overridden to return true in error classes
138 * @return bool
140 public function isError() {
141 return false;
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.
153 * @return bool
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.
165 * @return bool
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() ) {
179 return false;
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( array( 'src' => $this->path ) );
187 return $fsFile ? $fsFile->getPath() : false;
188 } else {
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
197 * @return bool Success
199 public function streamFile( $headers = array() ) {
200 if ( !$this->path ) {
201 return false;
202 } elseif ( FileBackend::isStoragePath( $this->path ) ) {
203 $be = $this->file->getRepo()->getBackend();
205 return $be->streamFile( array( 'src' => $this->path, 'headers' => $headers ) )->isOK();
206 } else { // FS-file
207 return StreamFile::stream( $this->getLocalCopyPath(), $headers );
212 * Wrap some XHTML text in an anchor tag with the given attributes
214 * @param array $linkAttribs
215 * @param string $contents
216 * @return string
218 protected function linkWrap( $linkAttribs, $contents ) {
219 if ( $linkAttribs ) {
220 return Xml::tags( 'a', $linkAttribs, $contents );
221 } else {
222 return $contents;
227 * @param string $title
228 * @param string|array $params Query parameters to add
229 * @return array
231 public function getDescLinkAttribs( $title = null, $params = array() ) {
232 if ( is_array( $params ) ) {
233 $query = $params;
234 } else {
235 $query = array();
237 if ( $this->page && $this->page !== 1 ) {
238 $query['page'] = $this->page;
240 if ( $this->lang ) {
241 $query['lang'] = $this->lang;
244 if ( is_string( $params ) && $params !== '' ) {
245 $query = $params . '&' . wfArrayToCgi( $query );
248 $attribs = array(
249 'href' => $this->file->getTitle()->getLocalURL( $query ),
250 'class' => 'image',
252 if ( $title ) {
253 $attribs['title'] = $title;
256 return $attribs;
261 * Media transform output for images
263 * @ingroup Media
265 class ThumbnailImage extends MediaTransformOutput {
267 * Get a thumbnail object from a file and parameters.
268 * If $path is set to null, the output file is treated as a source copy.
269 * If $path is set to false, no output file will be created.
270 * $parameters should include, as a minimum, (file) 'width' and 'height'.
271 * It may also include a 'page' parameter for multipage files.
273 * @param File $file
274 * @param string $url URL path to the thumb
275 * @param string|bool $path Filesystem path to the thumb
276 * @param array $parameters Associative array of parameters
278 function __construct( $file, $url, $path = false, $parameters = array() ) {
279 # Previous parameters:
280 # $file, $url, $width, $height, $path = false, $page = false
282 $defaults = array(
283 'page' => false,
284 'lang' => false
287 if ( is_array( $parameters ) ) {
288 $actualParams = $parameters + $defaults;
289 } else {
290 # Using old format, should convert. Later a warning could be added here.
291 $numArgs = func_num_args();
292 $actualParams = array(
293 'width' => $path,
294 'height' => $parameters,
295 'page' => ( $numArgs > 5 ) ? func_get_arg( 5 ) : false
296 ) + $defaults;
297 $path = ( $numArgs > 4 ) ? func_get_arg( 4 ) : false;
300 $this->file = $file;
301 $this->url = $url;
302 $this->path = $path;
304 # These should be integers when they get here.
305 # If not, there's a bug somewhere. But let's at
306 # least produce valid HTML code regardless.
307 $this->width = round( $actualParams['width'] );
308 $this->height = round( $actualParams['height'] );
310 $this->page = $actualParams['page'];
311 $this->lang = $actualParams['lang'];
315 * Return HTML <img ... /> tag for the thumbnail, will include
316 * width and height attributes and a blank alt text (as required).
318 * @param array $options Associative array of options. Boolean options
319 * should be indicated with a value of true for true, and false or
320 * absent for false.
322 * alt HTML alt attribute
323 * title HTML title attribute
324 * desc-link Boolean, show a description link
325 * file-link Boolean, show a file download link
326 * valign vertical-align property, if the output is an inline element
327 * img-class Class applied to the \<img\> tag, if there is such a tag
328 * desc-query String, description link query params
329 * override-width Override width attribute. Should generally not set
330 * override-height Override height attribute. Should generally not set
331 * no-dimensions Boolean, skip width and height attributes (useful if
332 * set in CSS)
333 * custom-url-link Custom URL to link to
334 * custom-title-link Custom Title object to link to
335 * custom target-link Value of the target attribute, for custom-target-link
336 * parser-extlink-* Attributes added by parser for external links:
337 * parser-extlink-rel: add rel="nofollow"
338 * parser-extlink-target: link target, but overridden by custom-target-link
340 * For images, desc-link and file-link are implemented as a click-through. For
341 * sounds and videos, they may be displayed in other ways.
343 * @throws MWException
344 * @return string
346 function toHtml( $options = array() ) {
347 if ( count( func_get_args() ) == 2 ) {
348 throw new MWException( __METHOD__ . ' called in the old style' );
351 $alt = isset( $options['alt'] ) ? $options['alt'] : '';
353 $query = isset( $options['desc-query'] ) ? $options['desc-query'] : '';
355 $attribs = array(
356 'alt' => $alt,
357 'src' => $this->url,
360 if ( !empty( $options['custom-url-link'] ) ) {
361 $linkAttribs = array( 'href' => $options['custom-url-link'] );
362 if ( !empty( $options['title'] ) ) {
363 $linkAttribs['title'] = $options['title'];
365 if ( !empty( $options['custom-target-link'] ) ) {
366 $linkAttribs['target'] = $options['custom-target-link'];
367 } elseif ( !empty( $options['parser-extlink-target'] ) ) {
368 $linkAttribs['target'] = $options['parser-extlink-target'];
370 if ( !empty( $options['parser-extlink-rel'] ) ) {
371 $linkAttribs['rel'] = $options['parser-extlink-rel'];
373 } elseif ( !empty( $options['custom-title-link'] ) ) {
374 /** @var Title $title */
375 $title = $options['custom-title-link'];
376 $linkAttribs = array(
377 'href' => $title->getLinkURL(),
378 'title' => empty( $options['title'] ) ? $title->getFullText() : $options['title']
380 } elseif ( !empty( $options['desc-link'] ) ) {
381 $linkAttribs = $this->getDescLinkAttribs(
382 empty( $options['title'] ) ? null : $options['title'],
383 $query
385 } elseif ( !empty( $options['file-link'] ) ) {
386 $linkAttribs = array( 'href' => $this->file->getURL() );
387 } else {
388 $linkAttribs = false;
389 if ( !empty( $options['title'] ) ) {
390 $attribs['title'] = $options['title'];
394 if ( empty( $options['no-dimensions'] ) ) {
395 $attribs['width'] = $this->width;
396 $attribs['height'] = $this->height;
398 if ( !empty( $options['valign'] ) ) {
399 $attribs['style'] = "vertical-align: {$options['valign']}";
401 if ( !empty( $options['img-class'] ) ) {
402 $attribs['class'] = $options['img-class'];
404 if ( isset( $options['override-height'] ) ) {
405 $attribs['height'] = $options['override-height'];
407 if ( isset( $options['override-width'] ) ) {
408 $attribs['width'] = $options['override-width'];
411 // Additional densities for responsive images, if specified.
412 if ( !empty( $this->responsiveUrls ) ) {
413 $attribs['srcset'] = Html::srcSet( $this->responsiveUrls );
416 Hooks::run( 'ThumbnailBeforeProduceHTML', array( $this, &$attribs, &$linkAttribs ) );
418 return $this->linkWrap( $linkAttribs, Xml::element( 'img', $attribs ) );
423 * Basic media transform error class
425 * @ingroup Media
427 class MediaTransformError extends MediaTransformOutput {
428 /** @var string HTML formatted version of the error */
429 private $htmlMsg;
431 /** @var string Plain text formatted version of the error */
432 private $textMsg;
434 function __construct( $msg, $width, $height /*, ... */ ) {
435 $args = array_slice( func_get_args(), 3 );
436 $htmlArgs = array_map( 'htmlspecialchars', $args );
437 $htmlArgs = array_map( 'nl2br', $htmlArgs );
439 $this->htmlMsg = wfMessage( $msg )->rawParams( $htmlArgs )->escaped();
440 $this->textMsg = wfMessage( $msg )->rawParams( $htmlArgs )->text();
441 $this->width = intval( $width );
442 $this->height = intval( $height );
443 $this->url = false;
444 $this->path = false;
447 function toHtml( $options = array() ) {
448 return "<div class=\"MediaTransformError\" style=\"" .
449 "width: {$this->width}px; height: {$this->height}px; display:inline-block;\">" .
450 $this->htmlMsg .
451 "</div>";
454 function toText() {
455 return $this->textMsg;
458 function getHtmlMsg() {
459 return $this->htmlMsg;
462 function isError() {
463 return true;
468 * Shortcut class for parameter validation errors
470 * @ingroup Media
472 class TransformParameterError extends MediaTransformError {
473 function __construct( $params ) {
474 parent::__construct( 'thumbnail_error',
475 max( isset( $params['width'] ) ? $params['width'] : 0, 120 ),
476 max( isset( $params['height'] ) ? $params['height'] : 0, 120 ),
477 wfMessage( 'thumbnail_invalid_params' )->text() );
482 * Shortcut class for parameter file size errors
484 * @ingroup Media
485 * @since 1.25
487 class TransformTooBigImageAreaError extends MediaTransformError {
488 function __construct( $params, $maxImageArea ) {
489 $msg = wfMessage( 'thumbnail_toobigimagearea' );
491 parent::__construct( 'thumbnail_error',
492 max( isset( $params['width'] ) ? $params['width'] : 0, 120 ),
493 max( isset( $params['height'] ) ? $params['height'] : 0, 120 ),
494 $msg->rawParams(
495 $msg->getLanguage()->formatComputingNumbers(
496 $maxImageArea, 1000, "size-$1pixel" )
497 )->text()