Merge "JsonContent: Remove never-used caption styles"
[lhc/web/wiklou.git] / includes / resourceloader / ResourceLoaderImage.php
1 <?php
2 /**
3 * Class encapsulating an image used in a ResourceLoaderImageModule.
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 */
22
23 use MediaWiki\Shell\Shell;
24
25 /**
26 * Class encapsulating an image used in a ResourceLoaderImageModule.
27 *
28 * @since 1.25
29 */
30 class ResourceLoaderImage {
31
32 /**
33 * Map of allowed file extensions to their MIME types.
34 * @var array
35 */
36 protected static $fileTypes = [
37 'svg' => 'image/svg+xml',
38 'png' => 'image/png',
39 'gif' => 'image/gif',
40 'jpg' => 'image/jpg',
41 ];
42
43 /** @var string */
44 private $name;
45 /** @var string */
46 private $module;
47 /** @var string|array */
48 private $descriptor;
49 /** @var string */
50 private $basePath;
51 /** @var array */
52 private $variants;
53 /** @var string|null */
54 private $defaultColor;
55 /** @var string */
56 private $extension;
57
58 /**
59 * @param string $name Image name
60 * @param string $module Module name
61 * @param string|array $descriptor Path to image file, or array structure containing paths
62 * @param string $basePath Directory to which paths in descriptor refer
63 * @param array $variants
64 * @param string|null $defaultColor of the base variant
65 * @throws InvalidArgumentException
66 */
67 public function __construct( $name, $module, $descriptor, $basePath, $variants,
68 $defaultColor = null
69 ) {
70 $this->name = $name;
71 $this->module = $module;
72 $this->descriptor = $descriptor;
73 $this->basePath = $basePath;
74 $this->variants = $variants;
75 $this->defaultColor = $defaultColor;
76
77 // Expand shorthands:
78 // [ "en,de,fr" => "foo.svg" ]
79 // → [ "en" => "foo.svg", "de" => "foo.svg", "fr" => "foo.svg" ]
80 if ( is_array( $this->descriptor ) && isset( $this->descriptor['lang'] ) ) {
81 foreach ( array_keys( $this->descriptor['lang'] ) as $langList ) {
82 if ( strpos( $langList, ',' ) !== false ) {
83 $this->descriptor['lang'] += array_fill_keys(
84 explode( ',', $langList ),
85 $this->descriptor['lang'][$langList]
86 );
87 unset( $this->descriptor['lang'][$langList] );
88 }
89 }
90 }
91 // Remove 'deprecated' key
92 if ( is_array( $this->descriptor ) ) {
93 unset( $this->descriptor['deprecated'] );
94 }
95
96 // Ensure that all files have common extension.
97 $extensions = [];
98 $descriptor = (array)$this->descriptor;
99 array_walk_recursive( $descriptor, function ( $path ) use ( &$extensions ) {
100 $extensions[] = pathinfo( $path, PATHINFO_EXTENSION );
101 } );
102 $extensions = array_unique( $extensions );
103 if ( count( $extensions ) !== 1 ) {
104 throw new InvalidArgumentException(
105 "File type for different image files of '$name' not the same in module '$module'"
106 );
107 }
108 $ext = $extensions[0];
109 if ( !isset( self::$fileTypes[$ext] ) ) {
110 throw new InvalidArgumentException(
111 "Invalid file type for image files of '$name' (valid: svg, png, gif, jpg) in module '$module'"
112 );
113 }
114 $this->extension = $ext;
115 }
116
117 /**
118 * Get name of this image.
119 *
120 * @return string
121 */
122 public function getName() {
123 return $this->name;
124 }
125
126 /**
127 * Get name of the module this image belongs to.
128 *
129 * @return string
130 */
131 public function getModule() {
132 return $this->module;
133 }
134
135 /**
136 * Get the list of variants this image can be converted to.
137 *
138 * @return string[]
139 */
140 public function getVariants() {
141 return array_keys( $this->variants );
142 }
143
144 /**
145 * Get the path to image file for given context.
146 *
147 * @param ResourceLoaderContext $context Any context
148 * @return string
149 */
150 public function getPath( ResourceLoaderContext $context ) {
151 $desc = $this->descriptor;
152 if ( is_string( $desc ) ) {
153 return $this->basePath . '/' . $desc;
154 }
155 if ( isset( $desc['lang'] ) ) {
156 $contextLang = $context->getLanguage();
157 if ( isset( $desc['lang'][$contextLang] ) ) {
158 return $this->basePath . '/' . $desc['lang'][$contextLang];
159 }
160 $fallbacks = Language::getFallbacksFor( $contextLang, Language::STRICT_FALLBACKS );
161 foreach ( $fallbacks as $lang ) {
162 if ( isset( $desc['lang'][$lang] ) ) {
163 return $this->basePath . '/' . $desc['lang'][$lang];
164 }
165 }
166 }
167 if ( isset( $desc[$context->getDirection()] ) ) {
168 return $this->basePath . '/' . $desc[$context->getDirection()];
169 }
170 return $this->basePath . '/' . $desc['default'];
171 }
172
173 /**
174 * Get the extension of the image.
175 *
176 * @param string $format Format to get the extension for, 'original' or 'rasterized'
177 * @return string Extension without leading dot, e.g. 'png'
178 */
179 public function getExtension( $format = 'original' ) {
180 if ( $format === 'rasterized' && $this->extension === 'svg' ) {
181 return 'png';
182 }
183 return $this->extension;
184 }
185
186 /**
187 * Get the MIME type of the image.
188 *
189 * @param string $format Format to get the MIME type for, 'original' or 'rasterized'
190 * @return string
191 */
192 public function getMimeType( $format = 'original' ) {
193 $ext = $this->getExtension( $format );
194 return self::$fileTypes[$ext];
195 }
196
197 /**
198 * Get the load.php URL that will produce this image.
199 *
200 * @param ResourceLoaderContext $context Any context
201 * @param string $script URL to load.php
202 * @param string|null $variant Variant to get the URL for
203 * @param string $format Format to get the URL for, 'original' or 'rasterized'
204 * @return string
205 */
206 public function getUrl( ResourceLoaderContext $context, $script, $variant, $format ) {
207 $query = [
208 'modules' => $this->getModule(),
209 'image' => $this->getName(),
210 'variant' => $variant,
211 'format' => $format,
212 'lang' => $context->getLanguage(),
213 'skin' => $context->getSkin(),
214 'version' => $context->getVersion(),
215 ];
216
217 return wfAppendQuery( $script, $query );
218 }
219
220 /**
221 * Get the data: URI that will produce this image.
222 *
223 * @param ResourceLoaderContext $context Any context
224 * @param string|null $variant Variant to get the URI for
225 * @param string $format Format to get the URI for, 'original' or 'rasterized'
226 * @return string
227 */
228 public function getDataUri( ResourceLoaderContext $context, $variant, $format ) {
229 $type = $this->getMimeType( $format );
230 $contents = $this->getImageData( $context, $variant, $format );
231 return CSSMin::encodeStringAsDataURI( $contents, $type );
232 }
233
234 /**
235 * Get actual image data for this image. This can be saved to a file or sent to the browser to
236 * produce the converted image.
237 *
238 * Call getExtension() or getMimeType() with the same $format argument to learn what file type the
239 * returned data uses.
240 *
241 * @param ResourceLoaderContext $context Image context, or any context if $variant and $format
242 * given.
243 * @param string|null $variant Variant to get the data for. Optional; if given, overrides the data
244 * from $context.
245 * @param string $format Format to get the data for, 'original' or 'rasterized'. Optional; if
246 * given, overrides the data from $context.
247 * @return string|false Possibly binary image data, or false on failure
248 * @throws MWException If the image file doesn't exist
249 */
250 public function getImageData( ResourceLoaderContext $context, $variant = false, $format = false ) {
251 if ( $variant === false ) {
252 $variant = $context->getVariant();
253 }
254 if ( $format === false ) {
255 $format = $context->getFormat();
256 }
257
258 $path = $this->getPath( $context );
259 if ( !file_exists( $path ) ) {
260 throw new MWException( "File '$path' does not exist" );
261 }
262
263 if ( $this->getExtension() !== 'svg' ) {
264 return file_get_contents( $path );
265 }
266
267 if ( $variant && isset( $this->variants[$variant] ) ) {
268 $data = $this->variantize( $this->variants[$variant], $context );
269 } else {
270 $defaultColor = $this->defaultColor;
271 $data = $defaultColor ?
272 $this->variantize( [ 'color' => $defaultColor ], $context ) :
273 file_get_contents( $path );
274 }
275
276 if ( $format === 'rasterized' ) {
277 $data = $this->rasterize( $data );
278 if ( !$data ) {
279 wfDebugLog( 'ResourceLoaderImage', __METHOD__ . " failed to rasterize for $path" );
280 }
281 }
282
283 return $data;
284 }
285
286 /**
287 * Send response headers (using the header() function) that are necessary to correctly serve the
288 * image data for this image, as returned by getImageData().
289 *
290 * Note that the headers are independent of the language or image variant.
291 *
292 * @param ResourceLoaderContext $context Image context
293 */
294 public function sendResponseHeaders( ResourceLoaderContext $context ) {
295 $format = $context->getFormat();
296 $mime = $this->getMimeType( $format );
297 $filename = $this->getName() . '.' . $this->getExtension( $format );
298
299 header( 'Content-Type: ' . $mime );
300 header( 'Content-Disposition: ' .
301 FileBackend::makeContentDisposition( 'inline', $filename ) );
302 }
303
304 /**
305 * Convert this image, which is assumed to be SVG, to given variant.
306 *
307 * @param array $variantConf Array with a 'color' key, its value will be used as fill color
308 * @param ResourceLoaderContext $context Image context
309 * @return string New SVG file data
310 */
311 protected function variantize( $variantConf, ResourceLoaderContext $context ) {
312 $dom = new DOMDocument;
313 $dom->loadXML( file_get_contents( $this->getPath( $context ) ) );
314 $root = $dom->documentElement;
315 $titleNode = null;
316 $wrapper = $dom->createElementNS( 'http://www.w3.org/2000/svg', 'g' );
317 // Reattach all direct children of the `<svg>` root node to the `<g>` wrapper
318 while ( $root->firstChild ) {
319 $node = $root->firstChild;
320 if ( !$titleNode && $node->nodeType === XML_ELEMENT_NODE && $node->tagName === 'title' ) {
321 // Remember the first encountered `<title>` node
322 $titleNode = $node;
323 }
324 $wrapper->appendChild( $node );
325 }
326 if ( $titleNode ) {
327 // Reattach the `<title>` node to the `<svg>` root node rather than the `<g>` wrapper
328 $root->appendChild( $titleNode );
329 }
330 $root->appendChild( $wrapper );
331 $wrapper->setAttribute( 'fill', $variantConf['color'] );
332 return $dom->saveXML();
333 }
334
335 /**
336 * Massage the SVG image data for converters which don't understand some path data syntax.
337 *
338 * This is necessary for rsvg and ImageMagick when compiled with rsvg support.
339 * Upstream bug is https://bugzilla.gnome.org/show_bug.cgi?id=620923, fixed 2014-11-10, so
340 * this will be needed for a while. (T76852)
341 *
342 * @param string $svg SVG image data
343 * @return string Massaged SVG image data
344 */
345 protected function massageSvgPathdata( $svg ) {
346 $dom = new DOMDocument;
347 $dom->loadXML( $svg );
348 foreach ( $dom->getElementsByTagName( 'path' ) as $node ) {
349 $pathData = $node->getAttribute( 'd' );
350 // Make sure there is at least one space between numbers, and that leading zero is not omitted.
351 // rsvg has issues with syntax like "M-1-2" and "M.445.483" and especially "M-.445-.483".
352 $pathData = preg_replace( '/(-?)(\d*\.\d+|\d+)/', ' ${1}0$2 ', $pathData );
353 // Strip unnecessary leading zeroes for prettiness, not strictly necessary
354 $pathData = preg_replace( '/([ -])0(\d)/', '$1$2', $pathData );
355 $node->setAttribute( 'd', $pathData );
356 }
357 return $dom->saveXML();
358 }
359
360 /**
361 * Convert passed image data, which is assumed to be SVG, to PNG.
362 *
363 * @param string $svg SVG image data
364 * @return string|bool PNG image data, or false on failure
365 */
366 protected function rasterize( $svg ) {
367 /**
368 * This code should be factored out to a separate method on SvgHandler, or perhaps a separate
369 * class, with a separate set of configuration settings.
370 *
371 * This is a distinct use case from regular SVG rasterization:
372 * * We can skip many sanity and security checks (as the images come from a trusted source,
373 * rather than from the user).
374 * * We need to provide extra options to some converters to achieve acceptable quality for very
375 * small images, which might cause performance issues in the general case.
376 * * We want to directly pass image data to the converter, rather than a file path.
377 *
378 * See https://phabricator.wikimedia.org/T76473#801446 for examples of what happens with the
379 * default settings.
380 *
381 * For now, we special-case rsvg (used in WMF production) and do a messy workaround for other
382 * converters.
383 */
384
385 global $wgSVGConverter, $wgSVGConverterPath;
386
387 $svg = $this->massageSvgPathdata( $svg );
388
389 // Sometimes this might be 'rsvg-secure'. Long as it's rsvg.
390 if ( strpos( $wgSVGConverter, 'rsvg' ) === 0 ) {
391 $command = 'rsvg-convert';
392 if ( $wgSVGConverterPath ) {
393 $command = Shell::escape( "$wgSVGConverterPath/" ) . $command;
394 }
395
396 $process = proc_open(
397 $command,
398 [ 0 => [ 'pipe', 'r' ], 1 => [ 'pipe', 'w' ] ],
399 $pipes
400 );
401
402 if ( is_resource( $process ) ) {
403 fwrite( $pipes[0], $svg );
404 fclose( $pipes[0] );
405 $png = stream_get_contents( $pipes[1] );
406 fclose( $pipes[1] );
407 proc_close( $process );
408
409 return $png ?: false;
410 }
411 return false;
412
413 } else {
414 // Write input to and read output from a temporary file
415 $tempFilenameSvg = tempnam( wfTempDir(), 'ResourceLoaderImage' );
416 $tempFilenamePng = tempnam( wfTempDir(), 'ResourceLoaderImage' );
417
418 file_put_contents( $tempFilenameSvg, $svg );
419
420 $metadata = SVGMetadataExtractor::getMetadata( $tempFilenameSvg );
421 if ( !isset( $metadata['width'] ) || !isset( $metadata['height'] ) ) {
422 unlink( $tempFilenameSvg );
423 return false;
424 }
425
426 $handler = new SvgHandler;
427 $res = $handler->rasterize(
428 $tempFilenameSvg,
429 $tempFilenamePng,
430 $metadata['width'],
431 $metadata['height']
432 );
433 unlink( $tempFilenameSvg );
434
435 $png = null;
436 if ( $res === true ) {
437 $png = file_get_contents( $tempFilenamePng );
438 unlink( $tempFilenamePng );
439 }
440
441 return $png ?: false;
442 }
443 }
444 }