Implement extension registration from an extension.json file
[mediawiki.git] / includes / resourceloader / ResourceLoaderImage.php
blob0e43f65c3fda3ac189aecdf82d654092222c3f0e
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 if ( $this->getExtension() !== 'svg' ) {
204 return file_get_contents( $this->getPath( $context ) );
207 if ( $variant && isset( $this->variants[$variant] ) ) {
208 $data = $this->variantize( $this->variants[$variant], $context );
209 } else {
210 $data = file_get_contents( $this->getPath( $context ) );
213 if ( $format === 'rasterized' ) {
214 $data = $this->rasterize( $data );
217 return $data;
221 * Send response headers (using the header() function) that are necessary to correctly serve the
222 * image data for this image, as returned by getImageData().
224 * Note that the headers are independent of the language or image variant.
226 * @param ResourceLoaderContext $context Image context
228 public function sendResponseHeaders( ResourceLoaderContext $context ) {
229 $format = $context->getFormat();
230 $mime = $this->getMimeType( $format );
231 $filename = $this->getName() . '.' . $this->getExtension( $format );
233 header( 'Content-Type: ' . $mime );
234 header( 'Content-Disposition: ' .
235 FileBackend::makeContentDisposition( 'inline', $filename ) );
239 * Convert this image, which is assumed to be SVG, to given variant.
241 * @param array $variantConf Array with a 'color' key, its value will be used as fill color
242 * @param ResourceLoaderContext $context Image context
243 * @return string New SVG file data
245 protected function variantize( $variantConf, ResourceLoaderContext $context ) {
246 $dom = new DomDocument;
247 $dom->load( $this->getPath( $context ) );
248 $root = $dom->documentElement;
249 $wrapper = $dom->createElement( 'g' );
250 while ( $root->firstChild ) {
251 $wrapper->appendChild( $root->firstChild );
253 $root->appendChild( $wrapper );
254 $wrapper->setAttribute( 'fill', $variantConf['color'] );
255 return $dom->saveXml();
259 * Massage the SVG image data for converters which doesn't understand some path data syntax.
261 * This is necessary for rsvg and ImageMagick when compiled with rsvg support.
262 * Upstream bug is https://bugzilla.gnome.org/show_bug.cgi?id=620923, fixed 2014-11-10, so
263 * this will be needed for a while. (T76852)
265 * @param string $svg SVG image data
266 * @return string Massaged SVG image data
268 protected function massageSvgPathdata( $svg ) {
269 $dom = new DomDocument;
270 $dom->loadXml( $svg );
271 foreach ( $dom->getElementsByTagName( 'path' ) as $node ) {
272 $pathData = $node->getAttribute( 'd' );
273 // Make sure there is at least one space between numbers, and that leading zero is not omitted.
274 // rsvg has issues with syntax like "M-1-2" and "M.445.483" and especially "M-.445-.483".
275 $pathData = preg_replace( '/(-?)(\d*\.\d+|\d+)/', ' ${1}0$2 ', $pathData );
276 // Strip unnecessary leading zeroes for prettiness, not strictly necessary
277 $pathData = preg_replace( '/([ -])0(\d)/', '$1$2', $pathData );
278 $node->setAttribute( 'd', $pathData );
280 return $dom->saveXml();
284 * Convert passed image data, which is assumed to be SVG, to PNG.
286 * @param string $svg SVG image data
287 * @return string|bool PNG image data, or false on failure
289 protected function rasterize( $svg ) {
290 // This code should be factored out to a separate method on SvgHandler, or perhaps a separate
291 // class, with a separate set of configuration settings.
293 // This is a distinct use case from regular SVG rasterization:
294 // * we can skip many sanity and security checks (as the images come from a trusted source,
295 // rather than from the user)
296 // * we need to provide extra options to some converters to achieve acceptable quality for very
297 // small images, which might cause performance issues in the general case
298 // * we need to directly pass image data to the converter instead of a file path
300 // See https://phabricator.wikimedia.org/T76473#801446 for examples of what happens with the
301 // default settings.
303 // For now, we special-case rsvg (used in WMF production) and do a messy workaround for other
304 // converters.
306 global $wgSVGConverter, $wgSVGConverterPath;
308 $svg = $this->massageSvgPathdata( $svg );
310 if ( $wgSVGConverter === 'rsvg' ) {
311 $command = 'rsvg-convert'; // Should be just 'rsvg'? T76476
312 if ( $wgSVGConverterPath ) {
313 $command = wfEscapeShellArg( "$wgSVGConverterPath/" ) . $command;
316 $process = proc_open(
317 $command,
318 array( 0 => array( 'pipe', 'r' ), 1 => array( 'pipe', 'w' ) ),
319 $pipes
322 if ( is_resource( $process ) ) {
323 fwrite( $pipes[0], $svg );
324 fclose( $pipes[0] );
325 $png = stream_get_contents( $pipes[1] );
326 fclose( $pipes[1] );
327 proc_close( $process );
329 return $png ?: false;
331 return false;
333 } else {
334 // Write input to and read output from a temporary file
335 $tempFilenameSvg = tempnam( wfTempDir(), 'ResourceLoaderImage' );
336 $tempFilenamePng = tempnam( wfTempDir(), 'ResourceLoaderImage' );
338 file_put_contents( $tempFilenameSvg, $svg );
340 $metadata = SVGMetadataExtractor::getMetadata( $tempFilenameSvg );
341 if ( !isset( $metadata['width'] ) || !isset( $metadata['height'] ) ) {
342 return false;
345 $handler = new SvgHandler;
346 $handler->rasterize( $tempFilenameSvg, $tempFilenamePng, $metadata['width'], $metadata['height'] );
348 $png = file_get_contents( $tempFilenamePng );
350 unlink( $tempFilenameSvg );
351 unlink( $tempFilenamePng );
353 return $png ?: false;