MediaWiki  1.33.1
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;
412  $res = $handler->rasterize(
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 }
MediaWiki\Shell\Shell
Executes shell commands.
Definition: Shell.php:44
ResourceLoaderContext
Object passed around to modules which contains information about the state of a specific loader reque...
Definition: ResourceLoaderContext.php:32
ResourceLoaderImage\variantize
variantize( $variantConf, ResourceLoaderContext $context)
Convert this image, which is assumed to be SVG, to given variant.
Definition: ResourceLoaderImage.php:296
$context
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:2644
$lang
if(!isset( $args[0])) $lang
Definition: testCompression.php:33
SVGMetadataExtractor\getMetadata
static getMetadata( $filename)
Definition: SVGMetadataExtractor.php:32
captcha-old.count
count
Definition: captcha-old.py:249
$res
$res
Definition: database.txt:21
wfDebugLog
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
Definition: GlobalFunctions.php:1043
ResourceLoaderImage\getVariants
getVariants()
Get the list of variants this image can be converted to.
Definition: ResourceLoaderImage.php:125
php
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:35
ResourceLoaderImage\getMimeType
getMimeType( $format='original')
Get the MIME type of the image.
Definition: ResourceLoaderImage.php:177
wfAppendQuery
wfAppendQuery( $url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...
Definition: GlobalFunctions.php:463
$query
null for the 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:1588
name
and how to run hooks for an and one after Each event has a name
Definition: hooks.txt:6
$data
$data
Utility to generate mapping file used in mw.Title (phpCharToUpper.json)
Definition: generatePhpCharToUpperMappings.php:13
ResourceLoaderImage\$fileTypes
static array $fileTypes
Map of allowed file extensions to their MIME types.
Definition: ResourceLoaderImage.php:36
$wgSVGConverterPath
$wgSVGConverterPath
If not in the executable PATH, specify the SVG converter path.
Definition: DefaultSettings.php:1203
MWException
MediaWiki exception.
Definition: MWException.php:26
$handler
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:780
SvgHandler
Handler for SVG images.
Definition: SvgHandler.php:32
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
ResourceLoaderImage\rasterize
rasterize( $svg)
Convert passed image data, which is assumed to be SVG, to PNG.
Definition: ResourceLoaderImage.php:351
ResourceLoaderImage\getModule
getModule()
Get name of the module this image belongs to.
Definition: ResourceLoaderImage.php:116
array
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))
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
ResourceLoaderImage
Class encapsulating an image used in a ResourceLoaderImageModule.
Definition: ResourceLoaderImage.php:30
$command
$command
Definition: cdb.php:65
ResourceLoaderImage\getPath
getPath(ResourceLoaderContext $context)
Get the path to image file for given context.
Definition: ResourceLoaderImage.php:135
wfTempDir
wfTempDir()
Tries to get the system directory for temporary files.
Definition: GlobalFunctions.php:1989
ResourceLoaderImage\massageSvgPathdata
massageSvgPathdata( $svg)
Massage the SVG image data for converters which don't understand some path data syntax.
Definition: ResourceLoaderImage.php:330
ResourceLoaderImage\getExtension
getExtension( $format='original')
Get the extension of the image.
Definition: ResourceLoaderImage.php:164
$path
$path
Definition: NoLocalSettings.php:25
as
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
Definition: distributors.txt:9
$basePath
$basePath
Definition: addSite.php:5
ResourceLoaderImage\getDataUri
getDataUri(ResourceLoaderContext $context, $variant, $format)
Get the data: URI that will produce this image.
Definition: ResourceLoaderImage.php:213
$ext
if(!is_readable( $file)) $ext
Definition: router.php:48
ResourceLoaderImage\getImageData
getImageData(ResourceLoaderContext $context, $variant=false, $format=false)
Get actual image data for this image.
Definition: ResourceLoaderImage.php:235
ResourceLoaderImage\getName
getName()
Get name of this image.
Definition: ResourceLoaderImage.php:107
ResourceLoaderImage\getUrl
getUrl(ResourceLoaderContext $context, $script, $variant, $format)
Get the load.php URL that will produce this image.
Definition: ResourceLoaderImage.php:191
$wgSVGConverter
$wgSVGConverter
Pick a converter defined in $wgSVGConverters.
Definition: DefaultSettings.php:1198
Language\STRICT_FALLBACKS
const STRICT_FALLBACKS
Return a strict fallback chain in getFallbacksFor.
Definition: Language.php:94
Language\getFallbacksFor
static getFallbacksFor( $code, $mode=self::MESSAGES_FALLBACKS)
Get the ordered list of fallback languages.
Definition: Language.php:4528
ResourceLoaderImage\sendResponseHeaders
sendResponseHeaders(ResourceLoaderContext $context)
Send response headers (using the header() function) that are necessary to correctly serve the image d...
Definition: ResourceLoaderImage.php:279
ResourceLoaderImage\__construct
__construct( $name, $module, $descriptor, $basePath, $variants, $defaultColor=null)
Definition: ResourceLoaderImage.php:52
$type
$type
Definition: testCompression.php:48
FileBackend\makeContentDisposition
static makeContentDisposition( $type, $filename='')
Build a Content-Disposition header value per RFC 6266.
Definition: FileBackend.php:1523