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