Move ILoadBalancer to Rdbms namespace
[mediawiki.git] / includes / resourceloader / ResourceLoaderImage.php
blob2503b22e5902a111e55c36160a5605e62b5ec6f1
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 = [
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 InvalidArgumentException
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 // Expand shorthands:
57 // [ "en,de,fr" => "foo.svg" ]
58 // → [ "en" => "foo.svg", "de" => "foo.svg", "fr" => "foo.svg" ]
59 if ( is_array( $this->descriptor ) && isset( $this->descriptor['lang'] ) ) {
60 foreach ( array_keys( $this->descriptor['lang'] ) as $langList ) {
61 if ( strpos( $langList, ',' ) !== false ) {
62 $this->descriptor['lang'] += array_fill_keys(
63 explode( ',', $langList ),
64 $this->descriptor['lang'][$langList]
66 unset( $this->descriptor['lang'][$langList] );
71 // Ensure that all files have common extension.
72 $extensions = [];
73 $descriptor = (array)$descriptor;
74 array_walk_recursive( $descriptor, function ( $path ) use ( &$extensions ) {
75 $extensions[] = pathinfo( $path, PATHINFO_EXTENSION );
76 } );
77 $extensions = array_unique( $extensions );
78 if ( count( $extensions ) !== 1 ) {
79 throw new InvalidArgumentException(
80 "File type for different image files of '$name' not the same"
83 $ext = $extensions[0];
84 if ( !isset( self::$fileTypes[$ext] ) ) {
85 throw new InvalidArgumentException(
86 "Invalid file type for image files of '$name' (valid: svg, png, gif, jpg)"
89 $this->extension = $ext;
92 /**
93 * Get name of this image.
95 * @return string
97 public function getName() {
98 return $this->name;
102 * Get name of the module this image belongs to.
104 * @return string
106 public function getModule() {
107 return $this->module;
111 * Get the list of variants this image can be converted to.
113 * @return string[]
115 public function getVariants() {
116 return array_keys( $this->variants );
120 * Get the path to image file for given context.
122 * @param ResourceLoaderContext $context Any context
123 * @return string
125 public function getPath( ResourceLoaderContext $context ) {
126 $desc = $this->descriptor;
127 if ( is_string( $desc ) ) {
128 return $this->basePath . '/' . $desc;
129 } elseif ( isset( $desc['lang'][$context->getLanguage()] ) ) {
130 return $this->basePath . '/' . $desc['lang'][$context->getLanguage()];
131 } elseif ( isset( $desc[$context->getDirection()] ) ) {
132 return $this->basePath . '/' . $desc[$context->getDirection()];
133 } else {
134 return $this->basePath . '/' . $desc['default'];
139 * Get the extension of the image.
141 * @param string $format Format to get the extension for, 'original' or 'rasterized'
142 * @return string Extension without leading dot, e.g. 'png'
144 public function getExtension( $format = 'original' ) {
145 if ( $format === 'rasterized' && $this->extension === 'svg' ) {
146 return 'png';
147 } else {
148 return $this->extension;
153 * Get the MIME type of the image.
155 * @param string $format Format to get the MIME type for, 'original' or 'rasterized'
156 * @return string
158 public function getMimeType( $format = 'original' ) {
159 $ext = $this->getExtension( $format );
160 return self::$fileTypes[$ext];
164 * Get the load.php URL that will produce this image.
166 * @param ResourceLoaderContext $context Any context
167 * @param string $script URL to load.php
168 * @param string|null $variant Variant to get the URL for
169 * @param string $format Format to get the URL for, 'original' or 'rasterized'
170 * @return string
172 public function getUrl( ResourceLoaderContext $context, $script, $variant, $format ) {
173 $query = [
174 'modules' => $this->getModule(),
175 'image' => $this->getName(),
176 'variant' => $variant,
177 'format' => $format,
178 'lang' => $context->getLanguage(),
179 'version' => $context->getVersion(),
182 return wfAppendQuery( $script, $query );
186 * Get the data: URI that will produce this image.
188 * @param ResourceLoaderContext $context Any context
189 * @param string|null $variant Variant to get the URI for
190 * @param string $format Format to get the URI for, 'original' or 'rasterized'
191 * @return string
193 public function getDataUri( ResourceLoaderContext $context, $variant, $format ) {
194 $type = $this->getMimeType( $format );
195 $contents = $this->getImageData( $context, $variant, $format );
196 return CSSMin::encodeStringAsDataURI( $contents, $type );
200 * Get actual image data for this image. This can be saved to a file or sent to the browser to
201 * produce the converted image.
203 * Call getExtension() or getMimeType() with the same $format argument to learn what file type the
204 * returned data uses.
206 * @param ResourceLoaderContext $context Image context, or any context if $variant and $format
207 * given.
208 * @param string|null $variant Variant to get the data for. Optional; if given, overrides the data
209 * from $context.
210 * @param string $format Format to get the data for, 'original' or 'rasterized'. Optional; if
211 * given, overrides the data from $context.
212 * @return string|false Possibly binary image data, or false on failure
213 * @throws MWException If the image file doesn't exist
215 public function getImageData( ResourceLoaderContext $context, $variant = false, $format = false ) {
216 if ( $variant === false ) {
217 $variant = $context->getVariant();
219 if ( $format === false ) {
220 $format = $context->getFormat();
223 $path = $this->getPath( $context );
224 if ( !file_exists( $path ) ) {
225 throw new MWException( "File '$path' does not exist" );
228 if ( $this->getExtension() !== 'svg' ) {
229 return file_get_contents( $path );
232 if ( $variant && isset( $this->variants[$variant] ) ) {
233 $data = $this->variantize( $this->variants[$variant], $context );
234 } else {
235 $data = file_get_contents( $path );
238 if ( $format === 'rasterized' ) {
239 $data = $this->rasterize( $data );
240 if ( !$data ) {
241 wfDebugLog( 'ResourceLoaderImage', __METHOD__ . " failed to rasterize for $path" );
245 return $data;
249 * Send response headers (using the header() function) that are necessary to correctly serve the
250 * image data for this image, as returned by getImageData().
252 * Note that the headers are independent of the language or image variant.
254 * @param ResourceLoaderContext $context Image context
256 public function sendResponseHeaders( ResourceLoaderContext $context ) {
257 $format = $context->getFormat();
258 $mime = $this->getMimeType( $format );
259 $filename = $this->getName() . '.' . $this->getExtension( $format );
261 header( 'Content-Type: ' . $mime );
262 header( 'Content-Disposition: ' .
263 FileBackend::makeContentDisposition( 'inline', $filename ) );
267 * Convert this image, which is assumed to be SVG, to given variant.
269 * @param array $variantConf Array with a 'color' key, its value will be used as fill color
270 * @param ResourceLoaderContext $context Image context
271 * @return string New SVG file data
273 protected function variantize( $variantConf, ResourceLoaderContext $context ) {
274 $dom = new DomDocument;
275 $dom->loadXML( file_get_contents( $this->getPath( $context ) ) );
276 $root = $dom->documentElement;
277 $wrapper = $dom->createElement( 'g' );
278 while ( $root->firstChild ) {
279 $wrapper->appendChild( $root->firstChild );
281 $root->appendChild( $wrapper );
282 $wrapper->setAttribute( 'fill', $variantConf['color'] );
283 return $dom->saveXML();
287 * Massage the SVG image data for converters which don't understand some path data syntax.
289 * This is necessary for rsvg and ImageMagick when compiled with rsvg support.
290 * Upstream bug is https://bugzilla.gnome.org/show_bug.cgi?id=620923, fixed 2014-11-10, so
291 * this will be needed for a while. (T76852)
293 * @param string $svg SVG image data
294 * @return string Massaged SVG image data
296 protected function massageSvgPathdata( $svg ) {
297 $dom = new DomDocument;
298 $dom->loadXML( $svg );
299 foreach ( $dom->getElementsByTagName( 'path' ) as $node ) {
300 $pathData = $node->getAttribute( 'd' );
301 // Make sure there is at least one space between numbers, and that leading zero is not omitted.
302 // rsvg has issues with syntax like "M-1-2" and "M.445.483" and especially "M-.445-.483".
303 $pathData = preg_replace( '/(-?)(\d*\.\d+|\d+)/', ' ${1}0$2 ', $pathData );
304 // Strip unnecessary leading zeroes for prettiness, not strictly necessary
305 $pathData = preg_replace( '/([ -])0(\d)/', '$1$2', $pathData );
306 $node->setAttribute( 'd', $pathData );
308 return $dom->saveXML();
312 * Convert passed image data, which is assumed to be SVG, to PNG.
314 * @param string $svg SVG image data
315 * @return string|bool PNG image data, or false on failure
317 protected function rasterize( $svg ) {
319 * This code should be factored out to a separate method on SvgHandler, or perhaps a separate
320 * class, with a separate set of configuration settings.
322 * This is a distinct use case from regular SVG rasterization:
323 * * We can skip many sanity and security checks (as the images come from a trusted source,
324 * rather than from the user).
325 * * We need to provide extra options to some converters to achieve acceptable quality for very
326 * small images, which might cause performance issues in the general case.
327 * * We want to directly pass image data to the converter, rather than a file path.
329 * See https://phabricator.wikimedia.org/T76473#801446 for examples of what happens with the
330 * default settings.
332 * For now, we special-case rsvg (used in WMF production) and do a messy workaround for other
333 * converters.
336 global $wgSVGConverter, $wgSVGConverterPath;
338 $svg = $this->massageSvgPathdata( $svg );
340 // Sometimes this might be 'rsvg-secure'. Long as it's rsvg.
341 if ( strpos( $wgSVGConverter, 'rsvg' ) === 0 ) {
342 $command = 'rsvg-convert';
343 if ( $wgSVGConverterPath ) {
344 $command = wfEscapeShellArg( "$wgSVGConverterPath/" ) . $command;
347 $process = proc_open(
348 $command,
349 [ 0 => [ 'pipe', 'r' ], 1 => [ 'pipe', 'w' ] ],
350 $pipes
353 if ( is_resource( $process ) ) {
354 fwrite( $pipes[0], $svg );
355 fclose( $pipes[0] );
356 $png = stream_get_contents( $pipes[1] );
357 fclose( $pipes[1] );
358 proc_close( $process );
360 return $png ?: false;
362 return false;
364 } else {
365 // Write input to and read output from a temporary file
366 $tempFilenameSvg = tempnam( wfTempDir(), 'ResourceLoaderImage' );
367 $tempFilenamePng = tempnam( wfTempDir(), 'ResourceLoaderImage' );
369 file_put_contents( $tempFilenameSvg, $svg );
371 $metadata = SVGMetadataExtractor::getMetadata( $tempFilenameSvg );
372 if ( !isset( $metadata['width'] ) || !isset( $metadata['height'] ) ) {
373 unlink( $tempFilenameSvg );
374 return false;
377 $handler = new SvgHandler;
378 $res = $handler->rasterize(
379 $tempFilenameSvg,
380 $tempFilenamePng,
381 $metadata['width'],
382 $metadata['height']
384 unlink( $tempFilenameSvg );
386 $png = null;
387 if ( $res === true ) {
388 $png = file_get_contents( $tempFilenamePng );
389 unlink( $tempFilenamePng );
392 return $png ?: false;