Merge "UnregisteredLocalFile.php: Override File::getBitDepth() stub"
[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 MWException
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 MWException( 'Image type for various images differs.' );
65 }
66 $ext = $extensions[0];
67 if ( !isset( self::$fileTypes[$ext] ) ) {
68 throw new MWException( 'Invalid image type; svg, png, gif or jpg required.' );
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 of $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 */
195 public function getImageData( ResourceLoaderContext $context, $variant = false, $format = false ) {
196 if ( $variant === false ) {
197 $variant = $context->getVariant();
198 }
199 if ( $format === false ) {
200 $format = $context->getFormat();
201 }
202
203 if ( $this->getExtension() !== 'svg' ) {
204 return file_get_contents( $this->getPath( $context ) );
205 }
206
207 if ( $variant && isset( $this->variants[$variant] ) ) {
208 $data = $this->variantize( $this->variants[$variant], $context );
209 } else {
210 $data = file_get_contents( $this->getPath( $context ) );
211 }
212
213 if ( $format === 'rasterized' ) {
214 $data = $this->rasterize( $data );
215 }
216
217 return $data;
218 }
219
220 /**
221 * Send response headers (using the header() function) that are necessary to correctly serve the
222 * image data for this image, as returned by getImageData().
223 *
224 * Note that the headers are independent of the language or image variant.
225 *
226 * @param ResourceLoaderContext $context Image context
227 */
228 public function sendResponseHeaders( ResourceLoaderContext $context ) {
229 $format = $context->getFormat();
230 $mime = $this->getMimeType( $format );
231 $filename = $this->getName() . '.' . $this->getExtension( $format );
232
233 header( 'Content-Type: ' . $mime );
234 header( 'Content-Disposition: ' .
235 FileBackend::makeContentDisposition( 'inline', $filename ) );
236 }
237
238 /**
239 * Convert this image, which is assumed to be SVG, to given variant.
240 *
241 * @param array $variantConf Array with a 'color' key, its value will be used as fill color
242 * @param ResourceLoaderContext $context Image context
243 * @return string New SVG file data
244 */
245 protected function variantize( $variantConf, ResourceLoaderContext $context ) {
246 $dom = new DomDocument;
247 $dom->load( $this->getPath( $context ) );
248 $root = $dom->documentElement;
249 $wrapper = $dom->createElement( 'g' );
250 while ( $root->firstChild ) {
251 $wrapper->appendChild( $root->firstChild );
252 }
253 $root->appendChild( $wrapper );
254 $wrapper->setAttribute( 'fill', $variantConf['color'] );
255 return $dom->saveXml();
256 }
257
258 /**
259 * Massage the SVG image data for converters which doesn't understand some path data syntax.
260 *
261 * This is necessary for rsvg and ImageMagick when compiled with rsvg support.
262 * Upstream bug is https://bugzilla.gnome.org/show_bug.cgi?id=620923, fixed 2014-11-10, so
263 * this will be needed for a while. (T76852)
264 *
265 * @param string $svg SVG image data
266 * @return string Massaged SVG image data
267 */
268 protected function massageSvgPathdata( $svg ) {
269 $dom = new DomDocument;
270 $dom->loadXml( $svg );
271 foreach ( $dom->getElementsByTagName( 'path' ) as $node ) {
272 $pathData = $node->getAttribute( 'd' );
273 // Make sure there is at least one space between numbers, and that leading zero is not omitted.
274 // rsvg has issues with syntax like "M-1-2" and "M.445.483" and especially "M-.445-.483".
275 $pathData = preg_replace( '/(-?)(\d*\.\d+|\d+)/', ' ${1}0$2 ', $pathData );
276 // Strip unnecessary leading zeroes for prettiness, not strictly necessary
277 $pathData = preg_replace( '/([ -])0(\d)/', '$1$2', $pathData );
278 $node->setAttribute( 'd', $pathData );
279 }
280 return $dom->saveXml();
281 }
282
283 /**
284 * Convert passed image data, which is assumed to be SVG, to PNG.
285 *
286 * @param string $svg SVG image data
287 * @return string|bool PNG image data, or false on failure
288 */
289 protected function rasterize( $svg ) {
290 // This code should be factored out to a separate method on SvgHandler, or perhaps a separate
291 // class, with a separate set of configuration settings.
292 //
293 // This is a distinct use case from regular SVG rasterization:
294 // * we can skip many sanity and security checks (as the images come from a trusted source,
295 // rather than from the user)
296 // * we need to provide extra options to some converters to achieve acceptable quality for very
297 // small images, which might cause performance issues in the general case
298 // * we need to directly pass image data to the converter instead of a file path
299 //
300 // See https://phabricator.wikimedia.org/T76473#801446 for examples of what happens with the
301 // default settings.
302 //
303 // For now, we special-case rsvg (used in WMF production) and do a messy workaround for other
304 // converters.
305
306 global $wgSVGConverter, $wgSVGConverterPath;
307
308 $svg = $this->massageSvgPathdata( $svg );
309
310 if ( $wgSVGConverter === 'rsvg' ) {
311 $command = 'rsvg-convert';
312 if ( $wgSVGConverterPath ) {
313 $command = wfEscapeShellArg( "$wgSVGConverterPath/" ) . $command;
314 }
315
316 $process = proc_open(
317 $command,
318 array( 0 => array( 'pipe', 'r' ), 1 => array( 'pipe', 'w' ) ),
319 $pipes
320 );
321
322 if ( is_resource( $process ) ) {
323 fwrite( $pipes[0], $svg );
324 fclose( $pipes[0] );
325 $png = stream_get_contents( $pipes[1] );
326 fclose( $pipes[1] );
327 proc_close( $process );
328
329 return $png ?: false;
330 }
331 return false;
332
333 } else {
334 // Write input to and read output from a temporary file
335 $tempFilenameSvg = tempnam( wfTempDir(), 'ResourceLoaderImage' );
336 $tempFilenamePng = tempnam( wfTempDir(), 'ResourceLoaderImage' );
337
338 file_put_contents( $tempFilenameSvg, $svg );
339
340 $metadata = SVGMetadataExtractor::getMetadata( $tempFilenameSvg );
341 if ( !isset( $metadata['width'] ) || !isset( $metadata['height'] ) ) {
342 return false;
343 }
344
345 $handler = new SvgHandler;
346 $handler->rasterize( $tempFilenameSvg, $tempFilenamePng, $metadata['width'], $metadata['height'] );
347
348 $png = file_get_contents( $tempFilenamePng );
349
350 unlink( $tempFilenameSvg );
351 unlink( $tempFilenamePng );
352
353 return $png ?: false;
354 }
355 }
356 }