MediaWiki  1.29.1
ResourceLoaderImage.php
Go to the documentation of this file.
1 <?php
29 
34  protected static $fileTypes = [
35  'svg' => 'image/svg+xml',
36  'png' => 'image/png',
37  'gif' => 'image/gif',
38  'jpg' => 'image/jpg',
39  ];
40 
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  // Expand shorthands:
57  // [ "en,de,fr" => "foo.svg" ]
58  // → [ "en" => "foo.svg", "de" => "foo.svg", "fr" => "foo.svg" ]
59  if ( is_array( $this->descriptor ) && isset( $this->descriptor['lang'] ) ) {
60  foreach ( array_keys( $this->descriptor['lang'] ) as $langList ) {
61  if ( strpos( $langList, ',' ) !== false ) {
62  $this->descriptor['lang'] += array_fill_keys(
63  explode( ',', $langList ),
64  $this->descriptor['lang'][$langList]
65  );
66  unset( $this->descriptor['lang'][$langList] );
67  }
68  }
69  }
70  // Remove 'deprecated' key
71  if ( is_array( $this->descriptor ) ) {
72  unset( $this->descriptor[ 'deprecated' ] );
73  }
74 
75  // Ensure that all files have common extension.
76  $extensions = [];
77  $descriptor = (array)$this->descriptor;
78  array_walk_recursive( $descriptor, function ( $path ) use ( &$extensions ) {
79  $extensions[] = pathinfo( $path, PATHINFO_EXTENSION );
80  } );
81  $extensions = array_unique( $extensions );
82  if ( count( $extensions ) !== 1 ) {
83  throw new InvalidArgumentException(
84  "File type for different image files of '$name' not the same in module '$module'"
85  );
86  }
87  $ext = $extensions[0];
88  if ( !isset( self::$fileTypes[$ext] ) ) {
89  throw new InvalidArgumentException(
90  "Invalid file type for image files of '$name' (valid: svg, png, gif, jpg) in module '$module'"
91  );
92  }
93  $this->extension = $ext;
94  }
95 
101  public function getName() {
102  return $this->name;
103  }
104 
110  public function getModule() {
111  return $this->module;
112  }
113 
119  public function getVariants() {
120  return array_keys( $this->variants );
121  }
122 
130  $desc = $this->descriptor;
131  if ( is_string( $desc ) ) {
132  return $this->basePath . '/' . $desc;
133  } elseif ( isset( $desc['lang'][$context->getLanguage()] ) ) {
134  return $this->basePath . '/' . $desc['lang'][$context->getLanguage()];
135  } elseif ( isset( $desc[$context->getDirection()] ) ) {
136  return $this->basePath . '/' . $desc[$context->getDirection()];
137  } else {
138  return $this->basePath . '/' . $desc['default'];
139  }
140  }
141 
148  public function getExtension( $format = 'original' ) {
149  if ( $format === 'rasterized' && $this->extension === 'svg' ) {
150  return 'png';
151  } else {
152  return $this->extension;
153  }
154  }
155 
162  public function getMimeType( $format = 'original' ) {
163  $ext = $this->getExtension( $format );
164  return self::$fileTypes[$ext];
165  }
166 
176  public function getUrl( ResourceLoaderContext $context, $script, $variant, $format ) {
177  $query = [
178  'modules' => $this->getModule(),
179  'image' => $this->getName(),
180  'variant' => $variant,
181  'format' => $format,
182  'lang' => $context->getLanguage(),
183  'skin' => $context->getSkin(),
184  'version' => $context->getVersion(),
185  ];
186 
187  return wfAppendQuery( $script, $query );
188  }
189 
198  public function getDataUri( ResourceLoaderContext $context, $variant, $format ) {
199  $type = $this->getMimeType( $format );
200  $contents = $this->getImageData( $context, $variant, $format );
201  return CSSMin::encodeStringAsDataURI( $contents, $type );
202  }
203 
220  public function getImageData( ResourceLoaderContext $context, $variant = false, $format = false ) {
221  if ( $variant === false ) {
222  $variant = $context->getVariant();
223  }
224  if ( $format === false ) {
225  $format = $context->getFormat();
226  }
227 
228  $path = $this->getPath( $context );
229  if ( !file_exists( $path ) ) {
230  throw new MWException( "File '$path' does not exist" );
231  }
232 
233  if ( $this->getExtension() !== 'svg' ) {
234  return file_get_contents( $path );
235  }
236 
237  if ( $variant && isset( $this->variants[$variant] ) ) {
238  $data = $this->variantize( $this->variants[$variant], $context );
239  } else {
240  $data = file_get_contents( $path );
241  }
242 
243  if ( $format === 'rasterized' ) {
244  $data = $this->rasterize( $data );
245  if ( !$data ) {
246  wfDebugLog( 'ResourceLoaderImage', __METHOD__ . " failed to rasterize for $path" );
247  }
248  }
249 
250  return $data;
251  }
252 
262  $format = $context->getFormat();
263  $mime = $this->getMimeType( $format );
264  $filename = $this->getName() . '.' . $this->getExtension( $format );
265 
266  header( 'Content-Type: ' . $mime );
267  header( 'Content-Disposition: ' .
268  FileBackend::makeContentDisposition( 'inline', $filename ) );
269  }
270 
278  protected function variantize( $variantConf, ResourceLoaderContext $context ) {
279  $dom = new DomDocument;
280  $dom->loadXML( file_get_contents( $this->getPath( $context ) ) );
281  $root = $dom->documentElement;
282  $wrapper = $dom->createElement( 'g' );
283  while ( $root->firstChild ) {
284  $wrapper->appendChild( $root->firstChild );
285  }
286  $root->appendChild( $wrapper );
287  $wrapper->setAttribute( 'fill', $variantConf['color'] );
288  return $dom->saveXML();
289  }
290 
301  protected function massageSvgPathdata( $svg ) {
302  $dom = new DomDocument;
303  $dom->loadXML( $svg );
304  foreach ( $dom->getElementsByTagName( 'path' ) as $node ) {
305  $pathData = $node->getAttribute( 'd' );
306  // Make sure there is at least one space between numbers, and that leading zero is not omitted.
307  // rsvg has issues with syntax like "M-1-2" and "M.445.483" and especially "M-.445-.483".
308  $pathData = preg_replace( '/(-?)(\d*\.\d+|\d+)/', ' ${1}0$2 ', $pathData );
309  // Strip unnecessary leading zeroes for prettiness, not strictly necessary
310  $pathData = preg_replace( '/([ -])0(\d)/', '$1$2', $pathData );
311  $node->setAttribute( 'd', $pathData );
312  }
313  return $dom->saveXML();
314  }
315 
322  protected function rasterize( $svg ) {
342 
343  $svg = $this->massageSvgPathdata( $svg );
344 
345  // Sometimes this might be 'rsvg-secure'. Long as it's rsvg.
346  if ( strpos( $wgSVGConverter, 'rsvg' ) === 0 ) {
347  $command = 'rsvg-convert';
348  if ( $wgSVGConverterPath ) {
349  $command = wfEscapeShellArg( "$wgSVGConverterPath/" ) . $command;
350  }
351 
352  $process = proc_open(
353  $command,
354  [ 0 => [ 'pipe', 'r' ], 1 => [ 'pipe', 'w' ] ],
355  $pipes
356  );
357 
358  if ( is_resource( $process ) ) {
359  fwrite( $pipes[0], $svg );
360  fclose( $pipes[0] );
361  $png = stream_get_contents( $pipes[1] );
362  fclose( $pipes[1] );
363  proc_close( $process );
364 
365  return $png ?: false;
366  }
367  return false;
368 
369  } else {
370  // Write input to and read output from a temporary file
371  $tempFilenameSvg = tempnam( wfTempDir(), 'ResourceLoaderImage' );
372  $tempFilenamePng = tempnam( wfTempDir(), 'ResourceLoaderImage' );
373 
374  file_put_contents( $tempFilenameSvg, $svg );
375 
376  $metadata = SVGMetadataExtractor::getMetadata( $tempFilenameSvg );
377  if ( !isset( $metadata['width'] ) || !isset( $metadata['height'] ) ) {
378  unlink( $tempFilenameSvg );
379  return false;
380  }
381 
382  $handler = new SvgHandler;
383  $res = $handler->rasterize(
384  $tempFilenameSvg,
385  $tempFilenamePng,
386  $metadata['width'],
387  $metadata['height']
388  );
389  unlink( $tempFilenameSvg );
390 
391  $png = null;
392  if ( $res === true ) {
393  $png = file_get_contents( $tempFilenamePng );
394  unlink( $tempFilenamePng );
395  }
396 
397  return $png ?: false;
398  }
399  }
400 }
ResourceLoaderContext
Object passed around to modules which contains information about the state of a specific loader reque...
Definition: ResourceLoaderContext.php:32
$context
error also a ContextSource you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition: hooks.txt:2612
CSSMin\encodeStringAsDataURI
static encodeStringAsDataURI( $contents, $type, $ie8Compat=true)
Encode file contents as a data URI with chosen MIME type.
Definition: CSSMin.php:133
ResourceLoaderImage\variantize
variantize( $variantConf, ResourceLoaderContext $context)
Convert this image, which is assumed to be SVG, to given variant.
Definition: ResourceLoaderImage.php:278
SVGMetadataExtractor\getMetadata
static getMetadata( $filename)
Definition: SVGMetadataExtractor.php:32
captcha-old.count
count
Definition: captcha-old.py:225
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
$res
$res
Definition: database.txt:21
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:304
$type
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled allows for interception of redirect as a string mapping parameter names to values & $type
Definition: hooks.txt:2536
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:1092
ResourceLoaderImage\getVariants
getVariants()
Get the list of variants this image can be converted to.
Definition: ResourceLoaderImage.php:119
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:162
ContextSource\getLanguage
getLanguage()
Get the Language object.
Definition: ContextSource.php:143
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:500
$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:1572
ResourceLoaderImage\$fileTypes
static array $fileTypes
Map of allowed file extensions to their MIME types.
Definition: ResourceLoaderImage.php:34
$wgSVGConverterPath
$wgSVGConverterPath
If not in the executable PATH, specify the SVG converter path.
Definition: DefaultSettings.php:1110
MWException
MediaWiki exception.
Definition: MWException.php:26
ContextSource\getSkin
getSkin()
Get the Skin object.
Definition: ContextSource.php:153
SvgHandler
Handler for SVG images.
Definition: SVG.php:30
ResourceLoaderImage\rasterize
rasterize( $svg)
Convert passed image data, which is assumed to be SVG, to PNG.
Definition: ResourceLoaderImage.php:322
ResourceLoaderImage\getModule
getModule()
Get name of the module this image belongs to.
Definition: ResourceLoaderImage.php:110
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
ResourceLoaderImage
Class encapsulating an image used in a ResourceLoaderImageModule.
Definition: ResourceLoaderImage.php:28
$mime
if( $ext=='php'|| $ext=='php5') $mime
Definition: router.php:65
$command
$command
Definition: cdb.php:64
ResourceLoaderImage\__construct
__construct( $name, $module, $descriptor, $basePath, $variants)
Definition: ResourceLoaderImage.php:49
wfEscapeShellArg
wfEscapeShellArg()
Version of escapeshellarg() that works better on Windows.
Definition: GlobalFunctions.php:2195
ResourceLoaderImage\getPath
getPath(ResourceLoaderContext $context)
Get the path to image file for given context.
Definition: ResourceLoaderImage.php:129
$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 probably a stub 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:783
wfTempDir
wfTempDir()
Tries to get the system directory for temporary files.
Definition: GlobalFunctions.php:2061
ResourceLoaderImage\massageSvgPathdata
massageSvgPathdata( $svg)
Massage the SVG image data for converters which don't understand some path data syntax.
Definition: ResourceLoaderImage.php:301
$ext
$ext
Definition: NoLocalSettings.php:25
ResourceLoaderImage\getExtension
getExtension( $format='original')
Get the extension of the image.
Definition: ResourceLoaderImage.php:148
$path
$path
Definition: NoLocalSettings.php:26
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:198
name
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at name
Definition: design.txt:12
ResourceLoaderImage\getImageData
getImageData(ResourceLoaderContext $context, $variant=false, $format=false)
Get actual image data for this image.
Definition: ResourceLoaderImage.php:220
ResourceLoaderImage\getName
getName()
Get name of this image.
Definition: ResourceLoaderImage.php:101
ResourceLoaderImage\getUrl
getUrl(ResourceLoaderContext $context, $script, $variant, $format)
Get the load.php URL that will produce this image.
Definition: ResourceLoaderImage.php:176
$wgSVGConverter
$wgSVGConverter
Pick a converter defined in $wgSVGConverters.
Definition: DefaultSettings.php:1105
ResourceLoaderImage\sendResponseHeaders
sendResponseHeaders(ResourceLoaderContext $context)
Send response headers (using the header() function) that are necessary to correctly serve the image d...
Definition: ResourceLoaderImage.php:261
array
the array() calling protocol came about after MediaWiki 1.4rc1.
FileBackend\makeContentDisposition
static makeContentDisposition( $type, $filename='')
Build a Content-Disposition header value per RFC 6266.
Definition: FileBackend.php:1540