Merge "(bug 42030) Include original URL params in variant links"
[lhc/web/wiklou.git] / includes / media / SVG.php
1 <?php
2 /**
3 * Handler for SVG images.
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 * Handler for SVG images.
26 *
27 * @ingroup Media
28 */
29 class SvgHandler extends ImageHandler {
30 const SVG_METADATA_VERSION = 2;
31
32 function isEnabled() {
33 global $wgSVGConverters, $wgSVGConverter;
34 if ( !isset( $wgSVGConverters[$wgSVGConverter] ) ) {
35 wfDebug( "\$wgSVGConverter is invalid, disabling SVG rendering.\n" );
36 return false;
37 } else {
38 return true;
39 }
40 }
41
42 function mustRender( $file ) {
43 return true;
44 }
45
46 function isVectorized( $file ) {
47 return true;
48 }
49
50 /**
51 * @param $file File
52 * @return bool
53 */
54 function isAnimatedImage( $file ) {
55 # TODO: detect animated SVGs
56 $metadata = $file->getMetadata();
57 if ( $metadata ) {
58 $metadata = $this->unpackMetadata( $metadata );
59 if( isset( $metadata['animated'] ) ) {
60 return $metadata['animated'];
61 }
62 }
63 return false;
64 }
65
66 /**
67 * We do not support making animated svg thumbnails
68 */
69 function canAnimateThumb( $file ) {
70 return false;
71 }
72
73 /**
74 * @param $image File
75 * @param $params
76 * @return bool
77 */
78 function normaliseParams( $image, &$params ) {
79 global $wgSVGMaxSize;
80 if ( !parent::normaliseParams( $image, $params ) ) {
81 return false;
82 }
83 # Don't make an image bigger than wgMaxSVGSize on the smaller side
84 if ( $params['physicalWidth'] <= $params['physicalHeight'] ) {
85 if ( $params['physicalWidth'] > $wgSVGMaxSize ) {
86 $srcWidth = $image->getWidth( $params['page'] );
87 $srcHeight = $image->getHeight( $params['page'] );
88 $params['physicalWidth'] = $wgSVGMaxSize;
89 $params['physicalHeight'] = File::scaleHeight( $srcWidth, $srcHeight, $wgSVGMaxSize );
90 }
91 } else {
92 if ( $params['physicalHeight'] > $wgSVGMaxSize ) {
93 $srcWidth = $image->getWidth( $params['page'] );
94 $srcHeight = $image->getHeight( $params['page'] );
95 $params['physicalWidth'] = File::scaleHeight( $srcHeight, $srcWidth, $wgSVGMaxSize );
96 $params['physicalHeight'] = $wgSVGMaxSize;
97 }
98 }
99 return true;
100 }
101
102 /**
103 * @param $image File
104 * @param $dstPath
105 * @param $dstUrl
106 * @param $params
107 * @param int $flags
108 * @return bool|MediaTransformError|ThumbnailImage|TransformParameterError
109 */
110 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
111 if ( !$this->normaliseParams( $image, $params ) ) {
112 return new TransformParameterError( $params );
113 }
114 $clientWidth = $params['width'];
115 $clientHeight = $params['height'];
116 $physicalWidth = $params['physicalWidth'];
117 $physicalHeight = $params['physicalHeight'];
118
119 if ( $flags & self::TRANSFORM_LATER ) {
120 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
121 }
122
123 $metadata = $this->unpackMetadata( $image->getMetadata() );
124 if ( isset( $metadata['error'] ) ) { // sanity check
125 $err = wfMessage( 'svg-long-error', $metadata['error']['message'] )->text();
126 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $err );
127 }
128
129 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__ ) ) {
130 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight,
131 wfMessage( 'thumbnail_dest_directory' )->text() );
132 }
133
134 $srcPath = $image->getLocalRefPath();
135 $status = $this->rasterize( $srcPath, $dstPath, $physicalWidth, $physicalHeight );
136 if ( $status === true ) {
137 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
138 } else {
139 return $status; // MediaTransformError
140 }
141 }
142
143 /**
144 * Transform an SVG file to PNG
145 * This function can be called outside of thumbnail contexts
146 * @param string $srcPath
147 * @param string $dstPath
148 * @param string $width
149 * @param string $height
150 * @throws MWException
151 * @return bool|MediaTransformError
152 */
153 public function rasterize( $srcPath, $dstPath, $width, $height ) {
154 global $wgSVGConverters, $wgSVGConverter, $wgSVGConverterPath;
155 $err = false;
156 $retval = '';
157 if ( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
158 if ( is_array( $wgSVGConverters[$wgSVGConverter] ) ) {
159 // This is a PHP callable
160 $func = $wgSVGConverters[$wgSVGConverter][0];
161 $args = array_merge( array( $srcPath, $dstPath, $width, $height ),
162 array_slice( $wgSVGConverters[$wgSVGConverter], 1 ) );
163 if ( !is_callable( $func ) ) {
164 throw new MWException( "$func is not callable" );
165 }
166 $err = call_user_func_array( $func, $args );
167 $retval = (bool)$err;
168 } else {
169 // External command
170 $cmd = str_replace(
171 array( '$path/', '$width', '$height', '$input', '$output' ),
172 array( $wgSVGConverterPath ? wfEscapeShellArg( "$wgSVGConverterPath/" ) : "",
173 intval( $width ),
174 intval( $height ),
175 wfEscapeShellArg( $srcPath ),
176 wfEscapeShellArg( $dstPath ) ),
177 $wgSVGConverters[$wgSVGConverter]
178 ) . " 2>&1";
179 wfProfileIn( 'rsvg' );
180 wfDebug( __METHOD__.": $cmd\n" );
181 $err = wfShellExec( $cmd, $retval );
182 wfProfileOut( 'rsvg' );
183 }
184 }
185 $removed = $this->removeBadFile( $dstPath, $retval );
186 if ( $retval != 0 || $removed ) {
187 wfDebugLog( 'thumbnail', sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
188 wfHostname(), $retval, trim($err), $cmd ) );
189 return new MediaTransformError( 'thumbnail_error', $width, $height, $err );
190 }
191 return true;
192 }
193
194 public static function rasterizeImagickExt( $srcPath, $dstPath, $width, $height ) {
195 $im = new Imagick( $srcPath );
196 $im->setImageFormat( 'png' );
197 $im->setBackgroundColor( 'transparent' );
198 $im->setImageDepth( 8 );
199
200 if ( !$im->thumbnailImage( intval( $width ), intval( $height ), /* fit */ false ) ) {
201 return 'Could not resize image';
202 }
203 if ( !$im->writeImage( $dstPath ) ) {
204 return "Could not write to $dstPath";
205 }
206 }
207
208 /**
209 * @param $file File
210 * @param $path
211 * @param bool $metadata
212 * @return array
213 */
214 function getImageSize( $file, $path, $metadata = false ) {
215 if ( $metadata === false ) {
216 $metadata = $file->getMetaData();
217 }
218 $metadata = $this->unpackMetaData( $metadata );
219
220 if ( isset( $metadata['width'] ) && isset( $metadata['height'] ) ) {
221 return array( $metadata['width'], $metadata['height'], 'SVG',
222 "width=\"{$metadata['width']}\" height=\"{$metadata['height']}\"" );
223 } else { // error
224 return array( 0, 0, 'SVG', "width=\"0\" height=\"0\"" );
225 }
226 }
227
228 function getThumbType( $ext, $mime, $params = null ) {
229 return array( 'png', 'image/png' );
230 }
231
232 /**
233 * Subtitle for the image. Different from the base
234 * class so it can be denoted that SVG's have
235 * a "nominal" resolution, and not a fixed one,
236 * as well as so animation can be denoted.
237 *
238 * @param $file File
239 * @return string
240 */
241 function getLongDesc( $file ) {
242 global $wgLang;
243
244 $metadata = $this->unpackMetadata( $file->getMetadata() );
245 if ( isset( $metadata['error'] ) ) {
246 return wfMessage( 'svg-long-error', $metadata['error']['message'] )->text();
247 }
248
249 $size = $wgLang->formatSize( $file->getSize() );
250
251 if ( $this->isAnimatedImage( $file ) ) {
252 $msg = wfMessage( 'svg-long-desc-animated' );
253 } else {
254 $msg = wfMessage( 'svg-long-desc' );
255 }
256
257 $msg->numParams( $file->getWidth(), $file->getHeight() )->params( $size );
258
259 return $msg->parse();
260 }
261
262 function getMetadata( $file, $filename ) {
263 $metadata = array( 'version' => self::SVG_METADATA_VERSION );
264 try {
265 $metadata += SVGMetadataExtractor::getMetadata( $filename );
266 } catch( MWException $e ) { // @TODO: SVG specific exceptions
267 // File not found, broken, etc.
268 $metadata['error'] = array(
269 'message' => $e->getMessage(),
270 'code' => $e->getCode()
271 );
272 wfDebug( __METHOD__ . ': ' . $e->getMessage() . "\n" );
273 }
274 return serialize( $metadata );
275 }
276
277 function unpackMetadata( $metadata ) {
278 wfSuppressWarnings();
279 $unser = unserialize( $metadata );
280 wfRestoreWarnings();
281 if ( isset( $unser['version'] ) && $unser['version'] == self::SVG_METADATA_VERSION ) {
282 return $unser;
283 } else {
284 return false;
285 }
286 }
287
288 function getMetadataType( $image ) {
289 return 'parsed-svg';
290 }
291
292 function isMetadataValid( $image, $metadata ) {
293 $meta = $this->unpackMetadata( $metadata );
294 if ( $meta === false ) {
295 return self::METADATA_BAD;
296 }
297 if ( !isset( $meta['originalWidth'] ) ) {
298 // Old but compatible
299 return self::METADATA_COMPATIBLE;
300 }
301 return self::METADATA_GOOD;
302 }
303
304 function visibleMetadataFields() {
305 $fields = array( 'objectname', 'imagedescription' );
306 return $fields;
307 }
308
309 /**
310 * @param $file File
311 * @return array|bool
312 */
313 function formatMetadata( $file ) {
314 $result = array(
315 'visible' => array(),
316 'collapsed' => array()
317 );
318 $metadata = $file->getMetadata();
319 if ( !$metadata ) {
320 return false;
321 }
322 $metadata = $this->unpackMetadata( $metadata );
323 if ( !$metadata || isset( $metadata['error'] ) ) {
324 return false;
325 }
326
327 /* TODO: add a formatter
328 $format = new FormatSVG( $metadata );
329 $formatted = $format->getFormattedData();
330 */
331
332 // Sort fields into visible and collapsed
333 $visibleFields = $this->visibleMetadataFields();
334
335 // Rename fields to be compatible with exif, so that
336 // the labels for these fields work and reuse existing messages.
337 $conversion = array(
338 'originalwidth' => 'imagewidth',
339 'originalheight' => 'imagelength',
340 'description' => 'imagedescription',
341 'title' => 'objectname',
342 );
343 foreach ( $metadata as $name => $value ) {
344 $tag = strtolower( $name );
345 if ( isset( $conversion[$tag] ) ) {
346 $tag = $conversion[$tag];
347 } else {
348 // Do not output other metadata not in list
349 continue;
350 }
351 self::addMeta( $result,
352 in_array( $tag, $visibleFields ) ? 'visible' : 'collapsed',
353 'exif',
354 $tag,
355 $value
356 );
357 }
358 return $result;
359 }
360 }