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