MediaWiki  master
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 
44  private $name;
46  private $module;
48  private $descriptor;
50  private $basePath;
52  private $variants;
54  private $defaultColor;
56  private $extension;
57 
69  ) {
70  $this->name = $name;
71  $this->module = $module;
72  $this->descriptor = $descriptor;
73  $this->basePath = $basePath;
74  $this->variants = $variants;
75  $this->defaultColor = $defaultColor;
76 
77  // Expand shorthands:
78  // [ "en,de,fr" => "foo.svg" ]
79  // → [ "en" => "foo.svg", "de" => "foo.svg", "fr" => "foo.svg" ]
80  if ( is_array( $this->descriptor ) && isset( $this->descriptor['lang'] ) ) {
81  foreach ( array_keys( $this->descriptor['lang'] ) as $langList ) {
82  if ( strpos( $langList, ',' ) !== false ) {
83  $this->descriptor['lang'] += array_fill_keys(
84  explode( ',', $langList ),
85  $this->descriptor['lang'][$langList]
86  );
87  unset( $this->descriptor['lang'][$langList] );
88  }
89  }
90  }
91  // Remove 'deprecated' key
92  if ( is_array( $this->descriptor ) ) {
93  unset( $this->descriptor['deprecated'] );
94  }
95 
96  // Ensure that all files have common extension.
97  $extensions = [];
98  $descriptor = is_array( $this->descriptor ) ? $this->descriptor : [ $this->descriptor ];
99  array_walk_recursive( $descriptor, function ( $path ) use ( &$extensions ) {
100  $extensions[] = pathinfo( $this->getLocalPath( $path ), PATHINFO_EXTENSION );
101  } );
102  $extensions = array_unique( $extensions );
103  if ( count( $extensions ) !== 1 ) {
104  throw new InvalidArgumentException(
105  "File type for different image files of '$name' not the same in module '$module'"
106  );
107  }
108  $ext = $extensions[0];
109  if ( !isset( self::$fileTypes[$ext] ) ) {
110  throw new InvalidArgumentException(
111  "Invalid file type for image files of '$name' (valid: svg, png, gif, jpg) in module '$module'"
112  );
113  }
114  $this->extension = $ext;
115  }
116 
122  public function getName() {
123  return $this->name;
124  }
125 
131  public function getModule() {
132  return $this->module;
133  }
134 
140  public function getVariants() {
141  return array_keys( $this->variants );
142  }
143 
152  $desc = $this->descriptor;
153  if ( !is_array( $desc ) ) {
154  return $this->getLocalPath( $desc );
155  }
156  if ( isset( $desc['lang'] ) ) {
157  $contextLang = $context->getLanguage();
158  if ( isset( $desc['lang'][$contextLang] ) ) {
159  return $this->getLocalPath( $desc['lang'][$contextLang] );
160  }
161  $fallbacks = Language::getFallbacksFor( $contextLang, Language::STRICT_FALLBACKS );
162  foreach ( $fallbacks as $lang ) {
163  if ( isset( $desc['lang'][$lang] ) ) {
164  return $this->getLocalPath( $desc['lang'][$lang] );
165  }
166  }
167  }
168  if ( isset( $desc[$context->getDirection()] ) ) {
169  return $this->getLocalPath( $desc[$context->getDirection()] );
170  }
171  if ( isset( $desc['default'] ) ) {
172  return $this->getLocalPath( $desc['default'] );
173  } else {
174  throw new MWException( 'No matching path found' );
175  }
176  }
177 
182  protected function getLocalPath( $path ) {
183  if ( $path instanceof ResourceLoaderFilePath ) {
184  return $path->getLocalPath();
185  }
186 
187  return "{$this->basePath}/$path";
188  }
189 
196  public function getExtension( $format = 'original' ) {
197  if ( $format === 'rasterized' && $this->extension === 'svg' ) {
198  return 'png';
199  }
200  return $this->extension;
201  }
202 
209  public function getMimeType( $format = 'original' ) {
210  $ext = $this->getExtension( $format );
211  return self::$fileTypes[$ext];
212  }
213 
223  public function getUrl( ResourceLoaderContext $context, $script, $variant, $format ) {
224  $query = [
225  'modules' => $this->getModule(),
226  'image' => $this->getName(),
227  'variant' => $variant,
228  'format' => $format,
229  ];
230  if ( $this->varyOnLanguage() ) {
231  $query['lang'] = $context->getLanguage();
232  }
233  // The following parameters are at the end to keep the original order of the parameters.
234  $query['skin'] = $context->getSkin();
235  $query['version'] = $context->getVersion();
236 
237  return wfAppendQuery( $script, $query );
238  }
239 
248  public function getDataUri( ResourceLoaderContext $context, $variant, $format ) {
249  $type = $this->getMimeType( $format );
250  $contents = $this->getImageData( $context, $variant, $format );
251  return CSSMin::encodeStringAsDataURI( $contents, $type );
252  }
253 
270  public function getImageData( ResourceLoaderContext $context, $variant = false, $format = false ) {
271  if ( $variant === false ) {
272  $variant = $context->getVariant();
273  }
274  if ( $format === false ) {
275  $format = $context->getFormat();
276  }
277 
278  $path = $this->getPath( $context );
279  if ( !file_exists( $path ) ) {
280  throw new MWException( "File '$path' does not exist" );
281  }
282 
283  if ( $this->getExtension() !== 'svg' ) {
284  return file_get_contents( $path );
285  }
286 
287  if ( $variant && isset( $this->variants[$variant] ) ) {
288  $data = $this->variantize( $this->variants[$variant], $context );
289  } else {
291  $data = $defaultColor ?
292  $this->variantize( [ 'color' => $defaultColor ], $context ) :
293  file_get_contents( $path );
294  }
295 
296  if ( $format === 'rasterized' ) {
297  $data = $this->rasterize( $data );
298  if ( !$data ) {
299  wfDebugLog( 'ResourceLoaderImage', __METHOD__ . " failed to rasterize for $path" );
300  }
301  }
302 
303  return $data;
304  }
305 
315  $format = $context->getFormat();
316  $mime = $this->getMimeType( $format );
317  $filename = $this->getName() . '.' . $this->getExtension( $format );
318 
319  header( 'Content-Type: ' . $mime );
320  header( 'Content-Disposition: ' .
321  FileBackend::makeContentDisposition( 'inline', $filename ) );
322  }
323 
331  protected function variantize( $variantConf, ResourceLoaderContext $context ) {
332  $dom = new DOMDocument;
333  $dom->loadXML( file_get_contents( $this->getPath( $context ) ) );
334  $root = $dom->documentElement;
335  $titleNode = null;
336  $wrapper = $dom->createElementNS( 'http://www.w3.org/2000/svg', 'g' );
337  // Reattach all direct children of the `<svg>` root node to the `<g>` wrapper
338  while ( $root->firstChild ) {
339  $node = $root->firstChild;
340  if ( !$titleNode && $node->nodeType === XML_ELEMENT_NODE && $node->tagName === 'title' ) {
341  // Remember the first encountered `<title>` node
342  $titleNode = $node;
343  }
344  $wrapper->appendChild( $node );
345  }
346  if ( $titleNode ) {
347  // Reattach the `<title>` node to the `<svg>` root node rather than the `<g>` wrapper
348  $root->appendChild( $titleNode );
349  }
350  $root->appendChild( $wrapper );
351  $wrapper->setAttribute( 'fill', $variantConf['color'] );
352  return $dom->saveXML();
353  }
354 
365  protected function massageSvgPathdata( $svg ) {
366  $dom = new DOMDocument;
367  $dom->loadXML( $svg );
368  foreach ( $dom->getElementsByTagName( 'path' ) as $node ) {
369  $pathData = $node->getAttribute( 'd' );
370  // Make sure there is at least one space between numbers, and that leading zero is not omitted.
371  // rsvg has issues with syntax like "M-1-2" and "M.445.483" and especially "M-.445-.483".
372  $pathData = preg_replace( '/(-?)(\d*\.\d+|\d+)/', ' ${1}0$2 ', $pathData );
373  // Strip unnecessary leading zeroes for prettiness, not strictly necessary
374  $pathData = preg_replace( '/([ -])0(\d)/', '$1$2', $pathData );
375  $node->setAttribute( 'd', $pathData );
376  }
377  return $dom->saveXML();
378  }
379 
386  protected function rasterize( $svg ) {
406 
407  $svg = $this->massageSvgPathdata( $svg );
408 
409  // Sometimes this might be 'rsvg-secure'. Long as it's rsvg.
410  if ( strpos( $wgSVGConverter, 'rsvg' ) === 0 ) {
411  $command = 'rsvg-convert';
412  if ( $wgSVGConverterPath ) {
413  $command = Shell::escape( "$wgSVGConverterPath/" ) . $command;
414  }
415 
416  $process = proc_open(
417  $command,
418  [ 0 => [ 'pipe', 'r' ], 1 => [ 'pipe', 'w' ] ],
419  $pipes
420  );
421 
422  if ( is_resource( $process ) ) {
423  fwrite( $pipes[0], $svg );
424  fclose( $pipes[0] );
425  $png = stream_get_contents( $pipes[1] );
426  fclose( $pipes[1] );
427  proc_close( $process );
428 
429  return $png ?: false;
430  }
431  return false;
432 
433  } else {
434  // Write input to and read output from a temporary file
435  $tempFilenameSvg = tempnam( wfTempDir(), 'ResourceLoaderImage' );
436  $tempFilenamePng = tempnam( wfTempDir(), 'ResourceLoaderImage' );
437 
438  file_put_contents( $tempFilenameSvg, $svg );
439 
440  $svgReader = new SVGReader( $tempFilenameSvg );
441  $metadata = $svgReader->getMetadata();
442  if ( !isset( $metadata['width'] ) || !isset( $metadata['height'] ) ) {
443  unlink( $tempFilenameSvg );
444  return false;
445  }
446 
447  $handler = new SvgHandler;
448  $res = $handler->rasterize(
449  $tempFilenameSvg,
450  $tempFilenamePng,
451  $metadata['width'],
452  $metadata['height']
453  );
454  unlink( $tempFilenameSvg );
455 
456  $png = null;
457  if ( $res === true ) {
458  $png = file_get_contents( $tempFilenamePng );
459  unlink( $tempFilenamePng );
460  }
461 
462  return $png ?: false;
463  }
464  }
465 
471  private function varyOnLanguage() {
472  return is_array( $this->descriptor ) && (
473  isset( $this->descriptor['ltr'] ) ||
474  isset( $this->descriptor['rtl'] ) ||
475  isset( $this->descriptor['lang'] ) );
476  }
477 }
return true to allow those checks to and false if checking is done remove or add to the links of a group of changes in EnhancedChangesList Hook subscribers can return false to omit this line from recentchanges use this to change the tables headers change it to an object instance and return false override the list derivative used $groups Array of ChangesListFilterGroup objects(added in 1.34) 'FileDeleteComplete' 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:1535
Class encapsulating an image used in a ResourceLoaderImageModule.
varyOnLanguage()
Check if the image depends on the language.
massageSvgPathdata( $svg)
Massage the SVG image data for converters which don&#39;t understand some path data syntax.
getImageData(ResourceLoaderContext $context, $variant=false, $format=false)
Get actual image data for this image.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
$command
Definition: cdb.php:65
if(!isset( $args[0])) $lang
static array string $name
__construct( $name, $module, $descriptor, $basePath, $variants, $defaultColor=null)
rasterize( $svg)
Convert passed image data, which is assumed to be SVG, to PNG.
getUrl(ResourceLoaderContext $context, $script, $variant, $format)
Get the load.php URL that will produce this image.
and how to run hooks for an and one after Each event has a name
Definition: hooks.txt:6
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:773
wfAppendQuery( $url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...
wfTempDir()
Tries to get the system directory for temporary files.
$wgSVGConverterPath
If not in the executable PATH, specify the SVG converter path.
getDataUri(ResourceLoaderContext $context, $variant, $format)
Get the data: URI that will produce this image.
const STRICT_FALLBACKS
Return a strict fallback chain in getFallbacksFor.
Definition: Language.php:95
$res
Definition: database.txt:21
static encodeStringAsDataURI( $contents, $type, $ie8Compat=true)
Encode file contents as a data URI with chosen MIME type.
Definition: CSSMin.php:142
getVariants()
Get the list of variants this image can be converted to.
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 null
Definition: hooks.txt:773
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
static array $fileTypes
Map of allowed file extensions to their MIME types.
An object to represent a path to a JavaScript/CSS file, along with a remote and local base path...
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
getName()
Get name of this image.
getMimeType( $format='original')
Get the MIME type of the image.
sendResponseHeaders(ResourceLoaderContext $context)
Send response headers (using the header() function) that are necessary to correctly serve the image d...
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not...
variantize( $variantConf, ResourceLoaderContext $context)
Convert this image, which is assumed to be SVG, to given variant.
static getFallbacksFor( $code, $mode=self::MESSAGES_FALLBACKS)
Get the ordered list of fallback languages.
Definition: Language.php:4514
if(!is_readable( $file)) $ext
Definition: router.php:48
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:2627
getModule()
Get name of the module this image belongs to.
getPath(ResourceLoaderContext $context)
Get the path to image file for given context.
$wgSVGConverter
Pick a converter defined in $wgSVGConverters.
Handler for SVG images.
Definition: SvgHandler.php:32
static makeContentDisposition( $type, $filename='')
Build a Content-Disposition header value per RFC 6266.
Object passed around to modules which contains information about the state of a specific loader reque...
getExtension( $format='original')
Get the extension of the image.