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