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