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