Merge "(bug 39431) Fix how SVG metadata is displayed (esp. animated status)"
[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 * @param $image File
68 * @param $params
69 * @return bool
70 */
71 function normaliseParams( $image, &$params ) {
72 global $wgSVGMaxSize;
73 if ( !parent::normaliseParams( $image, $params ) ) {
74 return false;
75 }
76 # Don't make an image bigger than wgMaxSVGSize on the smaller side
77 if ( $params['physicalWidth'] <= $params['physicalHeight'] ) {
78 if ( $params['physicalWidth'] > $wgSVGMaxSize ) {
79 $srcWidth = $image->getWidth( $params['page'] );
80 $srcHeight = $image->getHeight( $params['page'] );
81 $params['physicalWidth'] = $wgSVGMaxSize;
82 $params['physicalHeight'] = File::scaleHeight( $srcWidth, $srcHeight, $wgSVGMaxSize );
83 }
84 } else {
85 if ( $params['physicalHeight'] > $wgSVGMaxSize ) {
86 $srcWidth = $image->getWidth( $params['page'] );
87 $srcHeight = $image->getHeight( $params['page'] );
88 $params['physicalWidth'] = File::scaleHeight( $srcHeight, $srcWidth, $wgSVGMaxSize );
89 $params['physicalHeight'] = $wgSVGMaxSize;
90 }
91 }
92 return true;
93 }
94
95 /**
96 * @param $image File
97 * @param $dstPath
98 * @param $dstUrl
99 * @param $params
100 * @param int $flags
101 * @return bool|MediaTransformError|ThumbnailImage|TransformParameterError
102 */
103 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
104 if ( !$this->normaliseParams( $image, $params ) ) {
105 return new TransformParameterError( $params );
106 }
107 $clientWidth = $params['width'];
108 $clientHeight = $params['height'];
109 $physicalWidth = $params['physicalWidth'];
110 $physicalHeight = $params['physicalHeight'];
111
112 if ( $flags & self::TRANSFORM_LATER ) {
113 return new ThumbnailImage( $image, $dstUrl, $clientWidth, $clientHeight, $dstPath );
114 }
115
116 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__ ) ) {
117 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight,
118 wfMessage( 'thumbnail_dest_directory' )->text() );
119 }
120
121 $srcPath = $image->getLocalRefPath();
122 $status = $this->rasterize( $srcPath, $dstPath, $physicalWidth, $physicalHeight );
123 if( $status === true ) {
124 return new ThumbnailImage( $image, $dstUrl, $clientWidth, $clientHeight, $dstPath );
125 } else {
126 return $status; // MediaTransformError
127 }
128 }
129
130 /**
131 * Transform an SVG file to PNG
132 * This function can be called outside of thumbnail contexts
133 * @param string $srcPath
134 * @param string $dstPath
135 * @param string $width
136 * @param string $height
137 * @return bool|MediaTransformError
138 */
139 public function rasterize( $srcPath, $dstPath, $width, $height ) {
140 global $wgSVGConverters, $wgSVGConverter, $wgSVGConverterPath;
141 $err = false;
142 $retval = '';
143 if ( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
144 if ( is_array( $wgSVGConverters[$wgSVGConverter] ) ) {
145 // This is a PHP callable
146 $func = $wgSVGConverters[$wgSVGConverter][0];
147 $args = array_merge( array( $srcPath, $dstPath, $width, $height ),
148 array_slice( $wgSVGConverters[$wgSVGConverter], 1 ) );
149 if ( !is_callable( $func ) ) {
150 throw new MWException( "$func is not callable" );
151 }
152 $err = call_user_func_array( $func, $args );
153 $retval = (bool)$err;
154 } else {
155 // External command
156 $cmd = str_replace(
157 array( '$path/', '$width', '$height', '$input', '$output' ),
158 array( $wgSVGConverterPath ? wfEscapeShellArg( "$wgSVGConverterPath/" ) : "",
159 intval( $width ),
160 intval( $height ),
161 wfEscapeShellArg( $srcPath ),
162 wfEscapeShellArg( $dstPath ) ),
163 $wgSVGConverters[$wgSVGConverter]
164 ) . " 2>&1";
165 wfProfileIn( 'rsvg' );
166 wfDebug( __METHOD__.": $cmd\n" );
167 $err = wfShellExec( $cmd, $retval );
168 wfProfileOut( 'rsvg' );
169 }
170 }
171 $removed = $this->removeBadFile( $dstPath, $retval );
172 if ( $retval != 0 || $removed ) {
173 wfDebugLog( 'thumbnail', sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
174 wfHostname(), $retval, trim($err), $cmd ) );
175 return new MediaTransformError( 'thumbnail_error', $width, $height, $err );
176 }
177 return true;
178 }
179
180 public static function rasterizeImagickExt( $srcPath, $dstPath, $width, $height ) {
181 $im = new Imagick( $srcPath );
182 $im->setImageFormat( 'png' );
183 $im->setBackgroundColor( 'transparent' );
184 $im->setImageDepth( 8 );
185
186 if ( !$im->thumbnailImage( intval( $width ), intval( $height ), /* fit */ false ) ) {
187 return 'Could not resize image';
188 }
189 if ( !$im->writeImage( $dstPath ) ) {
190 return "Could not write to $dstPath";
191 }
192 }
193
194 /**
195 * @param $file File
196 * @param $path
197 * @param bool $metadata
198 * @return array
199 */
200 function getImageSize( $file, $path, $metadata = false ) {
201 if ( $metadata === false ) {
202 $metadata = $file->getMetaData();
203 }
204 $metadata = $this->unpackMetaData( $metadata );
205
206 if ( isset( $metadata['width'] ) && isset( $metadata['height'] ) ) {
207 return array( $metadata['width'], $metadata['height'], 'SVG',
208 "width=\"{$metadata['width']}\" height=\"{$metadata['height']}\"" );
209 }
210 }
211
212 function getThumbType( $ext, $mime, $params = null ) {
213 return array( 'png', 'image/png' );
214 }
215
216 /**
217 * Subtitle for the image. Different from the base
218 * class so it can be denoted that SVG's have
219 * a "nominal" resolution, and not a fixed one,
220 * as well as so animation can be denoted.
221 *
222 * @param $file File
223 * @return string
224 */
225 function getLongDesc( $file ) {
226 global $wgLang;
227 $size = $wgLang->formatSize( $file->getSize() );
228
229 if ( $this->isAnimatedImage( $file ) ) {
230 $msg = wfMessage( 'svg-long-desc-animated' );
231 } else {
232 $msg = wfMessage( 'svg-long-desc' );
233 }
234
235 $msg->numParams(
236 $file->getWidth(),
237 $file->getHeight()
238 );
239 $msg->Params( $size );
240 return $msg->parse();
241 }
242
243 function getMetadata( $file, $filename ) {
244 try {
245 $metadata = SVGMetadataExtractor::getMetadata( $filename );
246 } catch( Exception $e ) {
247 // Broken file?
248 wfDebug( __METHOD__ . ': ' . $e->getMessage() . "\n" );
249 return '0';
250 }
251 $metadata['version'] = self::SVG_METADATA_VERSION;
252 return serialize( $metadata );
253 }
254
255 function unpackMetadata( $metadata ) {
256 wfSuppressWarnings();
257 $unser = unserialize( $metadata );
258 wfRestoreWarnings();
259 if ( isset( $unser['version'] ) && $unser['version'] == self::SVG_METADATA_VERSION ) {
260 return $unser;
261 } else {
262 return false;
263 }
264 }
265
266 function getMetadataType( $image ) {
267 return 'parsed-svg';
268 }
269
270 function isMetadataValid( $image, $metadata ) {
271 return $this->unpackMetadata( $metadata ) !== false;
272 }
273
274 function visibleMetadataFields() {
275 $fields = array( 'objectname', 'imagedescription' );
276 return $fields;
277 }
278
279 /**
280 * @param $file File
281 * @return array|bool
282 */
283 function formatMetadata( $file ) {
284 $result = array(
285 'visible' => array(),
286 'collapsed' => array()
287 );
288 $metadata = $file->getMetadata();
289 if ( !$metadata ) {
290 return false;
291 }
292 $metadata = $this->unpackMetadata( $metadata );
293 if ( !$metadata ) {
294 return false;
295 }
296
297 /* TODO: add a formatter
298 $format = new FormatSVG( $metadata );
299 $formatted = $format->getFormattedData();
300 */
301
302 // Sort fields into visible and collapsed
303 $visibleFields = $this->visibleMetadataFields();
304
305 // Rename fields to be compatible with exif, so that
306 // the labels for these fields work and reuse existing messages.
307 $conversion = array(
308 'width' => 'imagewidth',
309 'height' => 'imagelength',
310 'description' => 'imagedescription',
311 'title' => 'objectname',
312 );
313 foreach ( $metadata as $name => $value ) {
314 $tag = strtolower( $name );
315 if ( isset( $conversion[$tag] ) ) {
316 $tag = $conversion[$tag];
317 } else {
318 // Do not output other metadata not in list
319 continue;
320 }
321 self::addMeta( $result,
322 in_array( $tag, $visibleFields ) ? 'visible' : 'collapsed',
323 'exif',
324 $tag,
325 $value
326 );
327 }
328 return $result;
329 }
330 }