Merged FileBackend branch. Manually avoiding merging the many prop-only changes SVN...
[lhc/web/wiklou.git] / includes / media / SVG.php
1 <?php
2 /**
3 * Handler for SVG images.
4 *
5 * @file
6 * @ingroup Media
7 */
8
9 /**
10 * Handler for SVG images.
11 *
12 * @ingroup Media
13 */
14 class SvgHandler extends ImageHandler {
15 const SVG_METADATA_VERSION = 2;
16
17 function isEnabled() {
18 global $wgSVGConverters, $wgSVGConverter;
19 if ( !isset( $wgSVGConverters[$wgSVGConverter] ) ) {
20 wfDebug( "\$wgSVGConverter is invalid, disabling SVG rendering.\n" );
21 return false;
22 } else {
23 return true;
24 }
25 }
26
27 function mustRender( $file ) {
28 return true;
29 }
30
31 function isVectorized( $file ) {
32 return true;
33 }
34
35 /**
36 * @param $file File
37 * @return bool
38 */
39 function isAnimatedImage( $file ) {
40 # TODO: detect animated SVGs
41 $metadata = $file->getMetadata();
42 if ( $metadata ) {
43 $metadata = $this->unpackMetadata( $metadata );
44 if( isset( $metadata['animated'] ) ) {
45 return $metadata['animated'];
46 }
47 }
48 return false;
49 }
50
51 /**
52 * @param $image File
53 * @param $params
54 * @return bool
55 */
56 function normaliseParams( $image, &$params ) {
57 global $wgSVGMaxSize;
58 if ( !parent::normaliseParams( $image, $params ) ) {
59 return false;
60 }
61 # Don't make an image bigger than wgMaxSVGSize on the smaller side
62 if ( $params['physicalWidth'] <= $params['physicalHeight'] ) {
63 if ( $params['physicalWidth'] > $wgSVGMaxSize ) {
64 $srcWidth = $image->getWidth( $params['page'] );
65 $srcHeight = $image->getHeight( $params['page'] );
66 $params['physicalWidth'] = $wgSVGMaxSize;
67 $params['physicalHeight'] = File::scaleHeight( $srcWidth, $srcHeight, $wgSVGMaxSize );
68 }
69 } else {
70 if ( $params['physicalHeight'] > $wgSVGMaxSize ) {
71 $srcWidth = $image->getWidth( $params['page'] );
72 $srcHeight = $image->getHeight( $params['page'] );
73 $params['physicalWidth'] = File::scaleHeight( $srcHeight, $srcWidth, $wgSVGMaxSize );
74 $params['physicalHeight'] = $wgSVGMaxSize;
75 }
76 }
77 return true;
78 }
79
80 /**
81 * @param $image File
82 * @param $dstPath
83 * @param $dstUrl
84 * @param $params
85 * @param int $flags
86 * @return bool|MediaTransformError|ThumbnailImage|TransformParameterError
87 */
88 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
89 if ( !$this->normaliseParams( $image, $params ) ) {
90 return new TransformParameterError( $params );
91 }
92 $clientWidth = $params['width'];
93 $clientHeight = $params['height'];
94 $physicalWidth = $params['physicalWidth'];
95 $physicalHeight = $params['physicalHeight'];
96 $srcPath = $image->getLocalRefPath();
97
98 if ( $flags & self::TRANSFORM_LATER ) {
99 return new ThumbnailImage( $image, $dstUrl, $clientWidth, $clientHeight, $dstPath );
100 }
101
102 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__ ) ) {
103 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight,
104 wfMsg( 'thumbnail_dest_directory' ) );
105 }
106
107 $status = $this->rasterize( $srcPath, $dstPath, $physicalWidth, $physicalHeight );
108 if( $status === true ) {
109 return new ThumbnailImage( $image, $dstUrl, $clientWidth, $clientHeight, $dstPath );
110 } else {
111 return $status; // MediaTransformError
112 }
113 }
114
115 /**
116 * Transform an SVG file to PNG
117 * This function can be called outside of thumbnail contexts
118 * @param string $srcPath
119 * @param string $dstPath
120 * @param string $width
121 * @param string $height
122 * @return true|MediaTransformError
123 */
124 public function rasterize( $srcPath, $dstPath, $width, $height ) {
125 global $wgSVGConverters, $wgSVGConverter, $wgSVGConverterPath;
126 $err = false;
127 $retval = '';
128 if ( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
129 if ( is_array( $wgSVGConverters[$wgSVGConverter] ) ) {
130 // This is a PHP callable
131 $func = $wgSVGConverters[$wgSVGConverter][0];
132 $args = array_merge( array( $srcPath, $dstPath, $width, $height ),
133 array_slice( $wgSVGConverters[$wgSVGConverter], 1 ) );
134 if ( !is_callable( $func ) ) {
135 throw new MWException( "$func is not callable" );
136 }
137 $err = call_user_func_array( $func, $args );
138 $retval = (bool)$err;
139 } else {
140 // External command
141 $cmd = str_replace(
142 array( '$path/', '$width', '$height', '$input', '$output' ),
143 array( $wgSVGConverterPath ? wfEscapeShellArg( "$wgSVGConverterPath/" ) : "",
144 intval( $width ),
145 intval( $height ),
146 wfEscapeShellArg( $srcPath ),
147 wfEscapeShellArg( $dstPath ) ),
148 $wgSVGConverters[$wgSVGConverter]
149 ) . " 2>&1";
150 wfProfileIn( 'rsvg' );
151 wfDebug( __METHOD__.": $cmd\n" );
152 $err = wfShellExec( $cmd, $retval );
153 wfProfileOut( 'rsvg' );
154 }
155 }
156 $removed = $this->removeBadFile( $dstPath, $retval );
157 if ( $retval != 0 || $removed ) {
158 wfDebugLog( 'thumbnail', sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
159 wfHostname(), $retval, trim($err), $cmd ) );
160 return new MediaTransformError( 'thumbnail_error', $width, $height, $err );
161 }
162 return true;
163 }
164
165 public static function rasterizeImagickExt( $srcPath, $dstPath, $width, $height ) {
166 $im = new Imagick( $srcPath );
167 $im->setImageFormat( 'png' );
168 $im->setBackgroundColor( 'transparent' );
169 $im->setImageDepth( 8 );
170
171 if ( !$im->thumbnailImage( intval( $width ), intval( $height ), /* fit */ false ) ) {
172 return 'Could not resize image';
173 }
174 if ( !$im->writeImage( $dstPath ) ) {
175 return "Could not write to $dstPath";
176 }
177 }
178
179 /**
180 * @param $file File
181 * @param $path
182 * @param bool $metadata
183 * @return array
184 */
185 function getImageSize( $file, $path, $metadata = false ) {
186 if ( $metadata === false ) {
187 $metadata = $file->getMetaData();
188 }
189 $metadata = $this->unpackMetaData( $metadata );
190
191 if ( isset( $metadata['width'] ) && isset( $metadata['height'] ) ) {
192 return array( $metadata['width'], $metadata['height'], 'SVG',
193 "width=\"{$metadata['width']}\" height=\"{$metadata['height']}\"" );
194 }
195 }
196
197 function getThumbType( $ext, $mime, $params = null ) {
198 return array( 'png', 'image/png' );
199 }
200
201 /**
202 * @param $file File
203 * @return string
204 */
205 function getLongDesc( $file ) {
206 global $wgLang;
207 return wfMsgExt( 'svg-long-desc', 'parseinline',
208 $wgLang->formatNum( $file->getWidth() ),
209 $wgLang->formatNum( $file->getHeight() ),
210 $wgLang->formatSize( $file->getSize() ) );
211 }
212
213 function getMetadata( $file, $filename ) {
214 try {
215 $metadata = SVGMetadataExtractor::getMetadata( $filename );
216 } catch( Exception $e ) {
217 // Broken file?
218 wfDebug( __METHOD__ . ': ' . $e->getMessage() . "\n" );
219 return '0';
220 }
221 $metadata['version'] = self::SVG_METADATA_VERSION;
222 return serialize( $metadata );
223 }
224
225 function unpackMetadata( $metadata ) {
226 wfSuppressWarnings();
227 $unser = unserialize( $metadata );
228 wfRestoreWarnings();
229 if ( isset( $unser['version'] ) && $unser['version'] == self::SVG_METADATA_VERSION ) {
230 return $unser;
231 } else {
232 return false;
233 }
234 }
235
236 function getMetadataType( $image ) {
237 return 'parsed-svg';
238 }
239
240 function isMetadataValid( $image, $metadata ) {
241 return $this->unpackMetadata( $metadata ) !== false;
242 }
243
244 function visibleMetadataFields() {
245 $fields = array( 'title', 'description', 'animated' );
246 return $fields;
247 }
248
249 /**
250 * @param $file File
251 * @return array|bool
252 */
253 function formatMetadata( $file ) {
254 $result = array(
255 'visible' => array(),
256 'collapsed' => array()
257 );
258 $metadata = $file->getMetadata();
259 if ( !$metadata ) {
260 return false;
261 }
262 $metadata = $this->unpackMetadata( $metadata );
263 if ( !$metadata ) {
264 return false;
265 }
266 unset( $metadata['version'] );
267 unset( $metadata['metadata'] ); /* non-formatted XML */
268
269 /* TODO: add a formatter
270 $format = new FormatSVG( $metadata );
271 $formatted = $format->getFormattedData();
272 */
273
274 // Sort fields into visible and collapsed
275 $visibleFields = $this->visibleMetadataFields();
276
277 // Rename fields to be compatible with exif, so that
278 // the labels for these fields work.
279 $conversion = array( 'width' => 'imagewidth',
280 'height' => 'imagelength',
281 'description' => 'imagedescription',
282 'title' => 'objectname',
283 );
284 foreach ( $metadata as $name => $value ) {
285 $tag = strtolower( $name );
286 if ( isset( $conversion[$tag] ) ) {
287 $tag = $conversion[$tag];
288 }
289 self::addMeta( $result,
290 in_array( $tag, $visibleFields ) ? 'visible' : 'collapsed',
291 'exif',
292 $tag,
293 $value
294 );
295 }
296 return $result;
297 }
298 }