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