Merge "DatabaseMssql: Don't duplicate body of makeList()"
[mediawiki.git] / includes / resourceloader / ResourceLoaderImage.php
blobc6e345f52b4b1e969d8335f219b668eca3bb4510
1 <?php
2 /**
3 * Class encapsulating an image used in a ResourceLoaderImageModule.
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.
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.
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
20 * @file
23 /**
24 * Class encapsulating an image used in a ResourceLoaderImageModule.
26 * @since 1.25
28 class ResourceLoaderImage {
30 /**
31 * Map of allowed file extensions to their MIME types.
32 * @var array
34 protected static $fileTypes = array(
35 'svg' => 'image/svg+xml',
36 'png' => 'image/png',
37 'gif' => 'image/gif',
38 'jpg' => 'image/jpg',
41 /**
42 * @param string $name Image name
43 * @param string $module Module name
44 * @param string|array $descriptor Path to image file, or array structure containing paths
45 * @param string $basePath Directory to which paths in descriptor refer
46 * @param array $variants
47 * @throws MWException
49 public function __construct( $name, $module, $descriptor, $basePath, $variants ) {
50 $this->name = $name;
51 $this->module = $module;
52 $this->descriptor = $descriptor;
53 $this->basePath = $basePath;
54 $this->variants = $variants;
56 // Ensure that all files have common extension.
57 $extensions = array();
58 $descriptor = (array)$descriptor;
59 array_walk_recursive( $descriptor, function ( $path ) use ( &$extensions ) {
60 $extensions[] = pathinfo( $path, PATHINFO_EXTENSION );
61 } );
62 $extensions = array_unique( $extensions );
63 if ( count( $extensions ) !== 1 ) {
64 throw new MWException( 'Image type for various images differs.' );
66 $ext = $extensions[0];
67 if ( !isset( self::$fileTypes[$ext] ) ) {
68 throw new MWException( 'Invalid image type; svg, png, gif or jpg required.' );
70 $this->extension = $ext;
73 /**
74 * Get name of this image.
76 * @return string
78 public function getName() {
79 return $this->name;
82 /**
83 * Get name of the module this image belongs to.
85 * @return string
87 public function getModule() {
88 return $this->module;
91 /**
92 * Get the list of variants this image can be converted to.
94 * @return string[]
96 public function getVariants() {
97 return array_keys( $this->variants );
101 * Get the path to image file for given context.
103 * @param ResourceLoaderContext $context Any context
104 * @return string
106 protected function getPath( ResourceLoaderContext $context ) {
107 $desc = $this->descriptor;
108 if ( is_string( $desc ) ) {
109 return $this->basePath . '/' . $desc;
110 } elseif ( isset( $desc['lang'][ $context->getLanguage() ] ) ) {
111 return $this->basePath . '/' . $desc['lang'][ $context->getLanguage() ];
112 } elseif ( isset( $desc[ $context->getDirection() ] ) ) {
113 return $this->basePath . '/' . $desc[ $context->getDirection() ];
114 } else {
115 return $this->basePath . '/' . $desc['default'];
120 * Get the extension of the image.
122 * @param string $format Format to get the extension for, 'original' or 'rasterized'
123 * @return string Extension without leading dot, e.g. 'png'
125 public function getExtension( $format = 'original' ) {
126 if ( $format === 'rasterized' && $this->extension === 'svg' ) {
127 return 'png';
128 } else {
129 return $this->extension;
134 * Get the MIME type of the image.
136 * @param string $format Format to get the MIME type for, 'original' or 'rasterized'
137 * @return string
139 public function getMimeType( $format = 'original' ) {
140 $ext = $this->getExtension( $format );
141 return self::$fileTypes[$ext];
145 * Get the load.php URL that will produce this image.
147 * @param ResourceLoaderContext $context Any context
148 * @param string $script URL to load.php
149 * @param string|null $variant Variant to get the URL for
150 * @param string $format Format to get the URL for, 'original' or 'rasterized'
151 * @return string
153 public function getUrl( ResourceLoaderContext $context, $script, $variant, $format ) {
154 $query = array(
155 'modules' => $this->getModule(),
156 'image' => $this->getName(),
157 'variant' => $variant,
158 'format' => $format,
159 'lang' => $context->getLanguage(),
160 'version' => $context->getVersion(),
163 return wfExpandUrl( wfAppendQuery( $script, $query ), PROTO_RELATIVE );
167 * Get the data: URI that will produce this image.
169 * @param ResourceLoaderContext $context Any context
170 * @param string|null $variant Variant to get the URI for
171 * @param string $format Format to get the URI for, 'original' or 'rasterized'
172 * @return string
174 public function getDataUri( ResourceLoaderContext $context, $variant, $format ) {
175 $type = $this->getMimeType( $format );
176 $contents = $this->getImageData( $context, $variant, $format );
177 return CSSMin::encodeStringAsDataURI( $contents, $type );
181 * Get actual image data for this image. This can be saved to a file or sent to the browser to
182 * produce the converted image.
184 * Call getExtension() or getMimeType() with the same $format argument to learn what file type the
185 * returned data uses.
187 * @param ResourceLoaderContext $context Image context, or any context of $variant and $format
188 * given.
189 * @param string|null $variant Variant to get the data for. Optional, if given, overrides the data
190 * from $context.
191 * @param string $format Format to get the data for, 'original' or 'rasterized'. Optional, if
192 * given, overrides the data from $context.
193 * @return string|false Possibly binary image data, or false on failure
195 public function getImageData( ResourceLoaderContext $context, $variant = false, $format = false ) {
196 if ( $variant === false ) {
197 $variant = $context->getVariant();
199 if ( $format === false ) {
200 $format = $context->getFormat();
203 $path = $this->getPath( $context );
204 if ( $this->getExtension() !== 'svg' ) {
205 return file_get_contents( $path );
208 if ( $variant && isset( $this->variants[$variant] ) ) {
209 $data = $this->variantize( $this->variants[$variant], $context );
210 } else {
211 $data = file_get_contents( $path );
214 if ( $format === 'rasterized' ) {
215 $data = $this->rasterize( $data );
216 if ( !$data ) {
217 wfDebugLog( 'ResourceLoaderImage', __METHOD__ . " failed to rasterize for $path" );
221 return $data;
225 * Send response headers (using the header() function) that are necessary to correctly serve the
226 * image data for this image, as returned by getImageData().
228 * Note that the headers are independent of the language or image variant.
230 * @param ResourceLoaderContext $context Image context
232 public function sendResponseHeaders( ResourceLoaderContext $context ) {
233 $format = $context->getFormat();
234 $mime = $this->getMimeType( $format );
235 $filename = $this->getName() . '.' . $this->getExtension( $format );
237 header( 'Content-Type: ' . $mime );
238 header( 'Content-Disposition: ' .
239 FileBackend::makeContentDisposition( 'inline', $filename ) );
243 * Convert this image, which is assumed to be SVG, to given variant.
245 * @param array $variantConf Array with a 'color' key, its value will be used as fill color
246 * @param ResourceLoaderContext $context Image context
247 * @return string New SVG file data
249 protected function variantize( $variantConf, ResourceLoaderContext $context ) {
250 $dom = new DomDocument;
251 $dom->load( $this->getPath( $context ) );
252 $root = $dom->documentElement;
253 $wrapper = $dom->createElement( 'g' );
254 while ( $root->firstChild ) {
255 $wrapper->appendChild( $root->firstChild );
257 $root->appendChild( $wrapper );
258 $wrapper->setAttribute( 'fill', $variantConf['color'] );
259 return $dom->saveXml();
263 * Massage the SVG image data for converters which doesn't understand some path data syntax.
265 * This is necessary for rsvg and ImageMagick when compiled with rsvg support.
266 * Upstream bug is https://bugzilla.gnome.org/show_bug.cgi?id=620923, fixed 2014-11-10, so
267 * this will be needed for a while. (T76852)
269 * @param string $svg SVG image data
270 * @return string Massaged SVG image data
272 protected function massageSvgPathdata( $svg ) {
273 $dom = new DomDocument;
274 $dom->loadXml( $svg );
275 foreach ( $dom->getElementsByTagName( 'path' ) as $node ) {
276 $pathData = $node->getAttribute( 'd' );
277 // Make sure there is at least one space between numbers, and that leading zero is not omitted.
278 // rsvg has issues with syntax like "M-1-2" and "M.445.483" and especially "M-.445-.483".
279 $pathData = preg_replace( '/(-?)(\d*\.\d+|\d+)/', ' ${1}0$2 ', $pathData );
280 // Strip unnecessary leading zeroes for prettiness, not strictly necessary
281 $pathData = preg_replace( '/([ -])0(\d)/', '$1$2', $pathData );
282 $node->setAttribute( 'd', $pathData );
284 return $dom->saveXml();
288 * Convert passed image data, which is assumed to be SVG, to PNG.
290 * @param string $svg SVG image data
291 * @return string|bool PNG image data, or false on failure
293 protected function rasterize( $svg ) {
294 // This code should be factored out to a separate method on SvgHandler, or perhaps a separate
295 // class, with a separate set of configuration settings.
297 // This is a distinct use case from regular SVG rasterization:
298 // * we can skip many sanity and security checks (as the images come from a trusted source,
299 // rather than from the user)
300 // * we need to provide extra options to some converters to achieve acceptable quality for very
301 // small images, which might cause performance issues in the general case
302 // * we need to directly pass image data to the converter instead of a file path
304 // See https://phabricator.wikimedia.org/T76473#801446 for examples of what happens with the
305 // default settings.
307 // For now, we special-case rsvg (used in WMF production) and do a messy workaround for other
308 // converters.
310 global $wgSVGConverter, $wgSVGConverterPath;
312 $svg = $this->massageSvgPathdata( $svg );
314 // Sometimes this might be 'rsvg-secure'. Long as it's rsvg.
315 if ( strpos( $wgSVGConverter, 'rsvg' ) === 0 ) {
316 $command = 'rsvg-convert';
317 if ( $wgSVGConverterPath ) {
318 $command = wfEscapeShellArg( "$wgSVGConverterPath/" ) . $command;
321 $process = proc_open(
322 $command,
323 array( 0 => array( 'pipe', 'r' ), 1 => array( 'pipe', 'w' ) ),
324 $pipes
327 if ( is_resource( $process ) ) {
328 fwrite( $pipes[0], $svg );
329 fclose( $pipes[0] );
330 $png = stream_get_contents( $pipes[1] );
331 fclose( $pipes[1] );
332 proc_close( $process );
334 return $png ?: false;
336 return false;
338 } else {
339 // Write input to and read output from a temporary file
340 $tempFilenameSvg = tempnam( wfTempDir(), 'ResourceLoaderImage' );
341 $tempFilenamePng = tempnam( wfTempDir(), 'ResourceLoaderImage' );
343 file_put_contents( $tempFilenameSvg, $svg );
345 $metadata = SVGMetadataExtractor::getMetadata( $tempFilenameSvg );
346 if ( !isset( $metadata['width'] ) || !isset( $metadata['height'] ) ) {
347 unlink( $tempFilenameSvg );
348 return false;
351 $handler = new SvgHandler;
352 $res = $handler->rasterize( $tempFilenameSvg, $tempFilenamePng, $metadata['width'], $metadata['height'] );
353 unlink( $tempFilenameSvg );
355 $png = null;
356 if ( $res === true ) {
357 $png = file_get_contents( $tempFilenamePng );
358 unlink( $tempFilenamePng );
361 return $png ?: false;