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