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