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