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