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