Merge "Pass phpcs-strict on maintenance/ (7/8)"
[lhc/web/wiklou.git] / includes / media / MediaTransformOutput.php
1 <?php
2 /**
3 * Base class for the output of file transformation methods.
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
24 /**
25 * Base class for the output of MediaHandler::doTransform() and File::transform().
26 *
27 * @ingroup Media
28 */
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.
32 */
33 public $responsiveUrls = array();
34
35 /** @var File object */
36 protected $file;
37
38 /** @var int Image width */
39 protected $width;
40
41 /** @var int Image height */
42 protected $height;
43
44 /** @var string URL path to the thumb */
45 protected $url;
46
47 /** @var bool|string */
48 protected $page;
49
50 /** @var bool|string Filesystem path to the thumb */
51 protected $path;
52
53 /** @var bool|string Language code, false if not set */
54 protected $lang;
55
56 /** @var bool|string Permanent storage path */
57 protected $storagePath = false;
58
59 /**
60 * @return int Width of the output box
61 */
62 public function getWidth() {
63 return $this->width;
64 }
65
66 /**
67 * @return int Height of the output box
68 */
69 public function getHeight() {
70 return $this->height;
71 }
72
73 /**
74 * @return File file
75 */
76 public function getFile() {
77 return $this->file;
78 }
79
80 /**
81 * Get the final extension of the thumbnail.
82 * Returns false for scripted transformations.
83 * @return string|bool
84 */
85 public function getExtension() {
86 return $this->path ? FileBackend::extensionFromPath( $this->path ) : false;
87 }
88
89 /**
90 * @return string|bool The thumbnail URL
91 */
92 public function getUrl() {
93 return $this->url;
94 }
95
96 /**
97 * @return string|bool The permanent thumbnail storage path
98 */
99 public function getStoragePath() {
100 return $this->storagePath;
101 }
102
103 /**
104 * @param string $storagePath The permanent storage path
105 * @return void
106 */
107 public function setStoragePath( $storagePath ) {
108 $this->storagePath = $storagePath;
109 }
110
111 /**
112 * Fetch HTML for this transform output
113 *
114 * @param array $options Associative array of options. Boolean options
115 * should be indicated with a value of true for true, and false or
116 * absent for false.
117 *
118 * alt Alternate text or caption
119 * desc-link Boolean, show a description link
120 * file-link Boolean, show a file download link
121 * custom-url-link Custom URL to link to
122 * custom-title-link Custom Title object to link to
123 * valign vertical-align property, if the output is an inline element
124 * img-class Class applied to the "<img>" tag, if there is such a tag
125 *
126 * For images, desc-link and file-link are implemented as a click-through. For
127 * sounds and videos, they may be displayed in other ways.
128 *
129 * @return string
130 */
131 abstract public function toHtml( $options = array() );
132
133 /**
134 * This will be overridden to return true in error classes
135 * @return bool
136 */
137 public function isError() {
138 return false;
139 }
140
141 /**
142 * Check if an output thumbnail file actually exists.
143 * This will return false if there was an error, the
144 * thumbnail is to be handled client-side only, or if
145 * transformation was deferred via TRANSFORM_LATER.
146 *
147 * @return bool
148 */
149 public function hasFile() {
150 // If TRANSFORM_LATER, $this->path will be false.
151 // Note: a null path means "use the source file".
152 return ( !$this->isError() && ( $this->path || $this->path === null ) );
153 }
154
155 /**
156 * Check if the output thumbnail is the same as the source.
157 * This can occur if the requested width was bigger than the source.
158 *
159 * @return bool
160 */
161 public function fileIsSource() {
162 return ( !$this->isError() && $this->path === null );
163 }
164
165 /**
166 * Get the path of a file system copy of the thumbnail.
167 * Callers should never write to this path.
168 *
169 * @return string|bool Returns false if there isn't one
170 */
171 public function getLocalCopyPath() {
172 if ( $this->isError() ) {
173 return false;
174 } elseif ( $this->path === null ) {
175 return $this->file->getLocalRefPath(); // assume thumb was not scaled
176 } elseif ( FileBackend::isStoragePath( $this->path ) ) {
177 $be = $this->file->getRepo()->getBackend();
178 // The temp file will be process cached by FileBackend
179 $fsFile = $be->getLocalReference( array( 'src' => $this->path ) );
180
181 return $fsFile ? $fsFile->getPath() : false;
182 } else {
183 return $this->path; // may return false
184 }
185 }
186
187 /**
188 * Stream the file if there were no errors
189 *
190 * @param array $headers Additional HTTP headers to send on success
191 * @return bool Success
192 */
193 public function streamFile( $headers = array() ) {
194 if ( !$this->path ) {
195 return false;
196 } elseif ( FileBackend::isStoragePath( $this->path ) ) {
197 $be = $this->file->getRepo()->getBackend();
198
199 return $be->streamFile( array( 'src' => $this->path, 'headers' => $headers ) )->isOK();
200 } else { // FS-file
201 return StreamFile::stream( $this->getLocalCopyPath(), $headers );
202 }
203 }
204
205 /**
206 * Wrap some XHTML text in an anchor tag with the given attributes
207 *
208 * @param array $linkAttribs
209 * @param string $contents
210 * @return string
211 */
212 protected function linkWrap( $linkAttribs, $contents ) {
213 if ( $linkAttribs ) {
214 return Xml::tags( 'a', $linkAttribs, $contents );
215 } else {
216 return $contents;
217 }
218 }
219
220 /**
221 * @param string $title
222 * @param string|array $params Query parameters to add
223 * @return array
224 */
225 public function getDescLinkAttribs( $title = null, $params = array() ) {
226 if ( is_array( $params ) ) {
227 $query = $params;
228 } else {
229 $query = array();
230 }
231 if ( $this->page && $this->page !== 1 ) {
232 $query['page'] = $this->page;
233 }
234 if ( $this->lang ) {
235 $query['lang'] = $this->lang;
236 }
237
238 if ( is_string( $params ) && $params !== '' ) {
239 $query = $params . '&' . wfArrayToCgi( $query );
240 }
241
242 $attribs = array(
243 'href' => $this->file->getTitle()->getLocalURL( $query ),
244 'class' => 'image',
245 );
246 if ( $title ) {
247 $attribs['title'] = $title;
248 }
249
250 return $attribs;
251 }
252 }
253
254 /**
255 * Media transform output for images
256 *
257 * @ingroup Media
258 */
259 class ThumbnailImage extends MediaTransformOutput {
260 /**
261 * Get a thumbnail object from a file and parameters.
262 * If $path is set to null, the output file is treated as a source copy.
263 * If $path is set to false, no output file will be created.
264 * $parameters should include, as a minimum, (file) 'width' and 'height'.
265 * It may also include a 'page' parameter for multipage files.
266 *
267 * @param File $file
268 * @param string $url URL path to the thumb
269 * @param string|bool $path Filesystem path to the thumb
270 * @param array $parameters Associative array of parameters
271 */
272 function __construct( $file, $url, $path = false, $parameters = array() ) {
273 # Previous parameters:
274 # $file, $url, $width, $height, $path = false, $page = false
275
276 $defaults = array(
277 'page' => false,
278 'lang' => false
279 );
280
281 if ( is_array( $parameters ) ) {
282 $actualParams = $parameters + $defaults;
283 } else {
284 # Using old format, should convert. Later a warning could be added here.
285 $numArgs = func_num_args();
286 $actualParams = array(
287 'width' => $path,
288 'height' => $parameters,
289 'page' => ( $numArgs > 5 ) ? func_get_arg( 5 ) : false
290 ) + $defaults;
291 $path = ( $numArgs > 4 ) ? func_get_arg( 4 ) : false;
292 }
293
294 $this->file = $file;
295 $this->url = $url;
296 $this->path = $path;
297
298 # These should be integers when they get here.
299 # If not, there's a bug somewhere. But let's at
300 # least produce valid HTML code regardless.
301 $this->width = round( $actualParams['width'] );
302 $this->height = round( $actualParams['height'] );
303
304 $this->page = $actualParams['page'];
305 $this->lang = $actualParams['lang'];
306 }
307
308 /**
309 * Return HTML <img ... /> tag for the thumbnail, will include
310 * width and height attributes and a blank alt text (as required).
311 *
312 * @param array $options Associative array of options. Boolean options
313 * should be indicated with a value of true for true, and false or
314 * absent for false.
315 *
316 * alt HTML alt attribute
317 * title HTML title attribute
318 * desc-link Boolean, show a description link
319 * file-link Boolean, show a file download link
320 * valign vertical-align property, if the output is an inline element
321 * img-class Class applied to the \<img\> tag, if there is such a tag
322 * desc-query String, description link query params
323 * override-width Override width attribute. Should generally not set
324 * override-height Override height attribute. Should generally not set
325 * no-dimensions Boolean, skip width and height attributes (useful if
326 * set in CSS)
327 * custom-url-link Custom URL to link to
328 * custom-title-link Custom Title object to link to
329 * custom target-link Value of the target attribute, for custom-target-link
330 * parser-extlink-* Attributes added by parser for external links:
331 * parser-extlink-rel: add rel="nofollow"
332 * parser-extlink-target: link target, but overridden by custom-target-link
333 *
334 * For images, desc-link and file-link are implemented as a click-through. For
335 * sounds and videos, they may be displayed in other ways.
336 *
337 * @throws MWException
338 * @return string
339 */
340 function toHtml( $options = array() ) {
341 if ( count( func_get_args() ) == 2 ) {
342 throw new MWException( __METHOD__ . ' called in the old style' );
343 }
344
345 $alt = empty( $options['alt'] ) ? '' : $options['alt'];
346
347 $query = empty( $options['desc-query'] ) ? '' : $options['desc-query'];
348
349 if ( !empty( $options['custom-url-link'] ) ) {
350 $linkAttribs = array( 'href' => $options['custom-url-link'] );
351 if ( !empty( $options['title'] ) ) {
352 $linkAttribs['title'] = $options['title'];
353 }
354 if ( !empty( $options['custom-target-link'] ) ) {
355 $linkAttribs['target'] = $options['custom-target-link'];
356 } elseif ( !empty( $options['parser-extlink-target'] ) ) {
357 $linkAttribs['target'] = $options['parser-extlink-target'];
358 }
359 if ( !empty( $options['parser-extlink-rel'] ) ) {
360 $linkAttribs['rel'] = $options['parser-extlink-rel'];
361 }
362 } elseif ( !empty( $options['custom-title-link'] ) ) {
363 /** @var Title $title */
364 $title = $options['custom-title-link'];
365 $linkAttribs = array(
366 'href' => $title->getLinkURL(),
367 'title' => empty( $options['title'] ) ? $title->getFullText() : $options['title']
368 );
369 } elseif ( !empty( $options['desc-link'] ) ) {
370 $linkAttribs = $this->getDescLinkAttribs(
371 empty( $options['title'] ) ? null : $options['title'],
372 $query
373 );
374 } elseif ( !empty( $options['file-link'] ) ) {
375 $linkAttribs = array( 'href' => $this->file->getURL() );
376 } else {
377 $linkAttribs = false;
378 }
379
380 $attribs = array(
381 'alt' => $alt,
382 'src' => $this->url,
383 );
384
385 if ( empty( $options['no-dimensions'] ) ) {
386 $attribs['width'] = $this->width;
387 $attribs['height'] = $this->height;
388 }
389 if ( !empty( $options['valign'] ) ) {
390 $attribs['style'] = "vertical-align: {$options['valign']}";
391 }
392 if ( !empty( $options['img-class'] ) ) {
393 $attribs['class'] = $options['img-class'];
394 }
395 if ( isset( $options['override-height'] ) ) {
396 $attribs['height'] = $options['override-height'];
397 }
398 if ( isset( $options['override-width'] ) ) {
399 $attribs['width'] = $options['override-width'];
400 }
401
402 // Additional densities for responsive images, if specified.
403 if ( !empty( $this->responsiveUrls ) ) {
404 $attribs['srcset'] = Html::srcSet( $this->responsiveUrls );
405 }
406
407 wfRunHooks( 'ThumbnailBeforeProduceHTML', array( $this, &$attribs, &$linkAttribs ) );
408
409 return $this->linkWrap( $linkAttribs, Xml::element( 'img', $attribs ) );
410 }
411 }
412
413 /**
414 * Basic media transform error class
415 *
416 * @ingroup Media
417 */
418 class MediaTransformError extends MediaTransformOutput {
419 /** @var string HTML formatted version of the error */
420 private $htmlMsg;
421
422 /** @var string Plain text formatted version of the error */
423 private $textMsg;
424
425 function __construct( $msg, $width, $height /*, ... */ ) {
426 $args = array_slice( func_get_args(), 3 );
427 $htmlArgs = array_map( 'htmlspecialchars', $args );
428 $htmlArgs = array_map( 'nl2br', $htmlArgs );
429
430 $this->htmlMsg = wfMessage( $msg )->rawParams( $htmlArgs )->escaped();
431 $this->textMsg = wfMessage( $msg )->rawParams( $htmlArgs )->text();
432 $this->width = intval( $width );
433 $this->height = intval( $height );
434 $this->url = false;
435 $this->path = false;
436 }
437
438 function toHtml( $options = array() ) {
439 return "<div class=\"MediaTransformError\" style=\"" .
440 "width: {$this->width}px; height: {$this->height}px; display:inline-block;\">" .
441 $this->htmlMsg .
442 "</div>";
443 }
444
445 function toText() {
446 return $this->textMsg;
447 }
448
449 function getHtmlMsg() {
450 return $this->htmlMsg;
451 }
452
453 function isError() {
454 return true;
455 }
456 }
457
458 /**
459 * Shortcut class for parameter validation errors
460 *
461 * @ingroup Media
462 */
463 class TransformParameterError extends MediaTransformError {
464 function __construct( $params ) {
465 parent::__construct( 'thumbnail_error',
466 max( isset( $params['width'] ) ? $params['width'] : 0, 120 ),
467 max( isset( $params['height'] ) ? $params['height'] : 0, 120 ),
468 wfMessage( 'thumbnail_invalid_params' )->text() );
469 }
470 }