MediaWiki REL1_33
ResourceLoaderImage.php
Go to the documentation of this file.
1<?php
24
31
36 protected static $fileTypes = [
37 'svg' => 'image/svg+xml',
38 'png' => 'image/png',
39 'gif' => 'image/gif',
40 'jpg' => 'image/jpg',
41 ];
42
52 public function __construct( $name, $module, $descriptor, $basePath, $variants,
53 $defaultColor = null
54 ) {
55 $this->name = $name;
56 $this->module = $module;
57 $this->descriptor = $descriptor;
58 $this->basePath = $basePath;
59 $this->variants = $variants;
60 $this->defaultColor = $defaultColor;
61
62 // Expand shorthands:
63 // [ "en,de,fr" => "foo.svg" ]
64 // → [ "en" => "foo.svg", "de" => "foo.svg", "fr" => "foo.svg" ]
65 if ( is_array( $this->descriptor ) && isset( $this->descriptor['lang'] ) ) {
66 foreach ( array_keys( $this->descriptor['lang'] ) as $langList ) {
67 if ( strpos( $langList, ',' ) !== false ) {
68 $this->descriptor['lang'] += array_fill_keys(
69 explode( ',', $langList ),
70 $this->descriptor['lang'][$langList]
71 );
72 unset( $this->descriptor['lang'][$langList] );
73 }
74 }
75 }
76 // Remove 'deprecated' key
77 if ( is_array( $this->descriptor ) ) {
78 unset( $this->descriptor['deprecated'] );
79 }
80
81 // Ensure that all files have common extension.
82 $extensions = [];
83 $descriptor = (array)$this->descriptor;
84 array_walk_recursive( $descriptor, function ( $path ) use ( &$extensions ) {
85 $extensions[] = pathinfo( $path, PATHINFO_EXTENSION );
86 } );
87 $extensions = array_unique( $extensions );
88 if ( count( $extensions ) !== 1 ) {
89 throw new InvalidArgumentException(
90 "File type for different image files of '$name' not the same in module '$module'"
91 );
92 }
93 $ext = $extensions[0];
94 if ( !isset( self::$fileTypes[$ext] ) ) {
95 throw new InvalidArgumentException(
96 "Invalid file type for image files of '$name' (valid: svg, png, gif, jpg) in module '$module'"
97 );
98 }
99 $this->extension = $ext;
100 }
101
107 public function getName() {
108 return $this->name;
109 }
110
116 public function getModule() {
117 return $this->module;
118 }
119
125 public function getVariants() {
126 return array_keys( $this->variants );
127 }
128
136 $desc = $this->descriptor;
137 if ( is_string( $desc ) ) {
138 return $this->basePath . '/' . $desc;
139 }
140 if ( isset( $desc['lang'] ) ) {
141 $contextLang = $context->getLanguage();
142 if ( isset( $desc['lang'][$contextLang] ) ) {
143 return $this->basePath . '/' . $desc['lang'][$contextLang];
144 }
145 $fallbacks = Language::getFallbacksFor( $contextLang, Language::STRICT_FALLBACKS );
146 foreach ( $fallbacks as $lang ) {
147 if ( isset( $desc['lang'][$lang] ) ) {
148 return $this->basePath . '/' . $desc['lang'][$lang];
149 }
150 }
151 }
152 if ( isset( $desc[$context->getDirection()] ) ) {
153 return $this->basePath . '/' . $desc[$context->getDirection()];
154 }
155 return $this->basePath . '/' . $desc['default'];
156 }
157
164 public function getExtension( $format = 'original' ) {
165 if ( $format === 'rasterized' && $this->extension === 'svg' ) {
166 return 'png';
167 }
168 return $this->extension;
169 }
170
177 public function getMimeType( $format = 'original' ) {
178 $ext = $this->getExtension( $format );
179 return self::$fileTypes[$ext];
180 }
181
191 public function getUrl( ResourceLoaderContext $context, $script, $variant, $format ) {
192 $query = [
193 'modules' => $this->getModule(),
194 'image' => $this->getName(),
195 'variant' => $variant,
196 'format' => $format,
197 'lang' => $context->getLanguage(),
198 'skin' => $context->getSkin(),
199 'version' => $context->getVersion(),
200 ];
201
202 return wfAppendQuery( $script, $query );
203 }
204
213 public function getDataUri( ResourceLoaderContext $context, $variant, $format ) {
214 $type = $this->getMimeType( $format );
215 $contents = $this->getImageData( $context, $variant, $format );
216 return CSSMin::encodeStringAsDataURI( $contents, $type );
217 }
218
235 public function getImageData( ResourceLoaderContext $context, $variant = false, $format = false ) {
236 if ( $variant === false ) {
237 $variant = $context->getVariant();
238 }
239 if ( $format === false ) {
240 $format = $context->getFormat();
241 }
242
243 $path = $this->getPath( $context );
244 if ( !file_exists( $path ) ) {
245 throw new MWException( "File '$path' does not exist" );
246 }
247
248 if ( $this->getExtension() !== 'svg' ) {
249 return file_get_contents( $path );
250 }
251
252 if ( $variant && isset( $this->variants[$variant] ) ) {
253 $data = $this->variantize( $this->variants[$variant], $context );
254 } else {
255 $defaultColor = $this->defaultColor;
256 $data = $defaultColor ?
257 $this->variantize( [ 'color' => $defaultColor ], $context ) :
258 file_get_contents( $path );
259 }
260
261 if ( $format === 'rasterized' ) {
262 $data = $this->rasterize( $data );
263 if ( !$data ) {
264 wfDebugLog( 'ResourceLoaderImage', __METHOD__ . " failed to rasterize for $path" );
265 }
266 }
267
268 return $data;
269 }
270
280 $format = $context->getFormat();
281 $mime = $this->getMimeType( $format );
282 $filename = $this->getName() . '.' . $this->getExtension( $format );
283
284 header( 'Content-Type: ' . $mime );
285 header( 'Content-Disposition: ' .
286 FileBackend::makeContentDisposition( 'inline', $filename ) );
287 }
288
296 protected function variantize( $variantConf, ResourceLoaderContext $context ) {
297 $dom = new DOMDocument;
298 $dom->loadXML( file_get_contents( $this->getPath( $context ) ) );
299 $root = $dom->documentElement;
300 $titleNode = null;
301 $wrapper = $dom->createElementNS( 'http://www.w3.org/2000/svg', 'g' );
302 // Reattach all direct children of the `<svg>` root node to the `<g>` wrapper
303 while ( $root->firstChild ) {
304 $node = $root->firstChild;
305 if ( !$titleNode && $node->nodeType === XML_ELEMENT_NODE && $node->tagName === 'title' ) {
306 // Remember the first encountered `<title>` node
307 $titleNode = $node;
308 }
309 $wrapper->appendChild( $node );
310 }
311 if ( $titleNode ) {
312 // Reattach the `<title>` node to the `<svg>` root node rather than the `<g>` wrapper
313 $root->appendChild( $titleNode );
314 }
315 $root->appendChild( $wrapper );
316 $wrapper->setAttribute( 'fill', $variantConf['color'] );
317 return $dom->saveXML();
318 }
319
330 protected function massageSvgPathdata( $svg ) {
331 $dom = new DOMDocument;
332 $dom->loadXML( $svg );
333 foreach ( $dom->getElementsByTagName( 'path' ) as $node ) {
334 $pathData = $node->getAttribute( 'd' );
335 // Make sure there is at least one space between numbers, and that leading zero is not omitted.
336 // rsvg has issues with syntax like "M-1-2" and "M.445.483" and especially "M-.445-.483".
337 $pathData = preg_replace( '/(-?)(\d*\.\d+|\d+)/', ' ${1}0$2 ', $pathData );
338 // Strip unnecessary leading zeroes for prettiness, not strictly necessary
339 $pathData = preg_replace( '/([ -])0(\d)/', '$1$2', $pathData );
340 $node->setAttribute( 'd', $pathData );
341 }
342 return $dom->saveXML();
343 }
344
351 protected function rasterize( $svg ) {
371
372 $svg = $this->massageSvgPathdata( $svg );
373
374 // Sometimes this might be 'rsvg-secure'. Long as it's rsvg.
375 if ( strpos( $wgSVGConverter, 'rsvg' ) === 0 ) {
376 $command = 'rsvg-convert';
377 if ( $wgSVGConverterPath ) {
378 $command = Shell::escape( "$wgSVGConverterPath/" ) . $command;
379 }
380
381 $process = proc_open(
382 $command,
383 [ 0 => [ 'pipe', 'r' ], 1 => [ 'pipe', 'w' ] ],
384 $pipes
385 );
386
387 if ( is_resource( $process ) ) {
388 fwrite( $pipes[0], $svg );
389 fclose( $pipes[0] );
390 $png = stream_get_contents( $pipes[1] );
391 fclose( $pipes[1] );
392 proc_close( $process );
393
394 return $png ?: false;
395 }
396 return false;
397
398 } else {
399 // Write input to and read output from a temporary file
400 $tempFilenameSvg = tempnam( wfTempDir(), 'ResourceLoaderImage' );
401 $tempFilenamePng = tempnam( wfTempDir(), 'ResourceLoaderImage' );
402
403 file_put_contents( $tempFilenameSvg, $svg );
404
405 $metadata = SVGMetadataExtractor::getMetadata( $tempFilenameSvg );
406 if ( !isset( $metadata['width'] ) || !isset( $metadata['height'] ) ) {
407 unlink( $tempFilenameSvg );
408 return false;
409 }
410
411 $handler = new SvgHandler;
413 $tempFilenameSvg,
414 $tempFilenamePng,
415 $metadata['width'],
416 $metadata['height']
417 );
418 unlink( $tempFilenameSvg );
419
420 $png = null;
421 if ( $res === true ) {
422 $png = file_get_contents( $tempFilenamePng );
423 unlink( $tempFilenamePng );
424 }
425
426 return $png ?: false;
427 }
428 }
429}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
$wgSVGConverter
Pick a converter defined in $wgSVGConverters.
$wgSVGConverterPath
If not in the executable PATH, specify the SVG converter path.
wfTempDir()
Tries to get the system directory for temporary files.
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
wfAppendQuery( $url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...
$basePath
Definition addSite.php:5
$command
Definition cdb.php:65
static encodeStringAsDataURI( $contents, $type, $ie8Compat=true)
Encode file contents as a data URI with chosen MIME type.
Definition CSSMin.php:142
static makeContentDisposition( $type, $filename='')
Build a Content-Disposition header value per RFC 6266.
MediaWiki exception.
Executes shell commands.
Definition Shell.php:44
Object passed around to modules which contains information about the state of a specific loader reque...
Class encapsulating an image used in a ResourceLoaderImageModule.
rasterize( $svg)
Convert passed image data, which is assumed to be SVG, to PNG.
variantize( $variantConf, ResourceLoaderContext $context)
Convert this image, which is assumed to be SVG, to given variant.
getUrl(ResourceLoaderContext $context, $script, $variant, $format)
Get the load.php URL that will produce this image.
getPath(ResourceLoaderContext $context)
Get the path to image file for given context.
massageSvgPathdata( $svg)
Massage the SVG image data for converters which don't understand some path data syntax.
getMimeType( $format='original')
Get the MIME type of the image.
getModule()
Get name of the module this image belongs to.
getExtension( $format='original')
Get the extension of the image.
__construct( $name, $module, $descriptor, $basePath, $variants, $defaultColor=null)
getDataUri(ResourceLoaderContext $context, $variant, $format)
Get the data: URI that will produce this image.
sendResponseHeaders(ResourceLoaderContext $context)
Send response headers (using the header() function) that are necessary to correctly serve the image d...
getName()
Get name of this image.
getVariants()
Get the list of variants this image can be converted to.
static array $fileTypes
Map of allowed file extensions to their MIME types.
getImageData(ResourceLoaderContext $context, $variant=false, $format=false)
Get actual image data for this image.
static getMetadata( $filename)
Handler for SVG images.
rasterize( $srcPath, $dstPath, $width, $height, $lang=false)
Transform an SVG file to PNG This function can be called outside of thumbnail contexts.
$res
Definition database.txt:21
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
$data
Utility to generate mapping file used in mw.Title (phpCharToUpper.json)
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check set to true or false to override the $wgMaxImageArea check result gives extension the possibility to transform it themselves $handler
Definition hooks.txt:894
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition hooks.txt:2848
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:271
and how to run hooks for an and one after Each event has a name
Definition hooks.txt:12
null for the local wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify $query
Definition hooks.txt:1617
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition injection.txt:37
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
if(!is_readable( $file)) $ext
Definition router.php:48
if(!isset( $args[0])) $lang