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