Revert "merged master"
[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 wfMsg( 'thumbnail_dest_directory' ) );
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 * @param $file File
218 * @return string
219 */
220 function getLongDesc( $file ) {
221 global $wgLang;
222 return wfMsgExt( 'svg-long-desc', 'parseinline',
223 $wgLang->formatNum( $file->getWidth() ),
224 $wgLang->formatNum( $file->getHeight() ),
225 $wgLang->formatSize( $file->getSize() ) );
226 }
227
228 function getMetadata( $file, $filename ) {
229 try {
230 $metadata = SVGMetadataExtractor::getMetadata( $filename );
231 } catch( Exception $e ) {
232 // Broken file?
233 wfDebug( __METHOD__ . ': ' . $e->getMessage() . "\n" );
234 return '0';
235 }
236 $metadata['version'] = self::SVG_METADATA_VERSION;
237 return serialize( $metadata );
238 }
239
240 function unpackMetadata( $metadata ) {
241 wfSuppressWarnings();
242 $unser = unserialize( $metadata );
243 wfRestoreWarnings();
244 if ( isset( $unser['version'] ) && $unser['version'] == self::SVG_METADATA_VERSION ) {
245 return $unser;
246 } else {
247 return false;
248 }
249 }
250
251 function getMetadataType( $image ) {
252 return 'parsed-svg';
253 }
254
255 function isMetadataValid( $image, $metadata ) {
256 return $this->unpackMetadata( $metadata ) !== false;
257 }
258
259 function visibleMetadataFields() {
260 $fields = array( 'title', 'description', 'animated' );
261 return $fields;
262 }
263
264 /**
265 * @param $file File
266 * @return array|bool
267 */
268 function formatMetadata( $file ) {
269 $result = array(
270 'visible' => array(),
271 'collapsed' => array()
272 );
273 $metadata = $file->getMetadata();
274 if ( !$metadata ) {
275 return false;
276 }
277 $metadata = $this->unpackMetadata( $metadata );
278 if ( !$metadata ) {
279 return false;
280 }
281 unset( $metadata['version'] );
282 unset( $metadata['metadata'] ); /* non-formatted XML */
283
284 /* TODO: add a formatter
285 $format = new FormatSVG( $metadata );
286 $formatted = $format->getFormattedData();
287 */
288
289 // Sort fields into visible and collapsed
290 $visibleFields = $this->visibleMetadataFields();
291
292 // Rename fields to be compatible with exif, so that
293 // the labels for these fields work.
294 $conversion = array( 'width' => 'imagewidth',
295 'height' => 'imagelength',
296 'description' => 'imagedescription',
297 'title' => 'objectname',
298 );
299 foreach ( $metadata as $name => $value ) {
300 $tag = strtolower( $name );
301 if ( isset( $conversion[$tag] ) ) {
302 $tag = $conversion[$tag];
303 }
304 self::addMeta( $result,
305 in_array( $tag, $visibleFields ) ? 'visible' : 'collapsed',
306 'exif',
307 $tag,
308 $value
309 );
310 }
311 return $result;
312 }
313 }