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