MediaWiki  master
ResourceLoaderImage.php
Go to the documentation of this file.
1 <?php
24 
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  $defaultColor = null
70  ) {
71  $this->name = $name;
72  $this->module = $module;
73  $this->descriptor = $descriptor;
74  $this->basePath = $basePath;
75  $this->variants = $variants;
76  $this->defaultColor = $defaultColor;
77 
78  // Expand shorthands:
79  // [ "en,de,fr" => "foo.svg" ]
80  // → [ "en" => "foo.svg", "de" => "foo.svg", "fr" => "foo.svg" ]
81  if ( is_array( $this->descriptor ) && isset( $this->descriptor['lang'] ) ) {
82  foreach ( array_keys( $this->descriptor['lang'] ) as $langList ) {
83  if ( strpos( $langList, ',' ) !== false ) {
84  $this->descriptor['lang'] += array_fill_keys(
85  explode( ',', $langList ),
86  $this->descriptor['lang'][$langList]
87  );
88  unset( $this->descriptor['lang'][$langList] );
89  }
90  }
91  }
92  // Remove 'deprecated' key
93  if ( is_array( $this->descriptor ) ) {
94  unset( $this->descriptor['deprecated'] );
95  }
96 
97  // Ensure that all files have common extension.
98  $extensions = [];
99  $descriptor = is_array( $this->descriptor ) ? $this->descriptor : [ $this->descriptor ];
100  array_walk_recursive( $descriptor, function ( $path ) use ( &$extensions ) {
101  $extensions[] = pathinfo( $this->getLocalPath( $path ), PATHINFO_EXTENSION );
102  } );
103  $extensions = array_unique( $extensions );
104  if ( count( $extensions ) !== 1 ) {
105  throw new InvalidArgumentException(
106  "File type for different image files of '$name' not the same in module '$module'"
107  );
108  }
109  $ext = $extensions[0];
110  if ( !isset( self::$fileTypes[$ext] ) ) {
111  throw new InvalidArgumentException(
112  "Invalid file type for image files of '$name' (valid: svg, png, gif, jpg) in module '$module'"
113  );
114  }
115  $this->extension = $ext;
116  }
117 
123  public function getName() {
124  return $this->name;
125  }
126 
132  public function getModule() {
133  return $this->module;
134  }
135 
141  public function getVariants() : array {
142  return array_keys( $this->variants );
143  }
144 
150  protected function getLangFallbacks( string $lang ) : array {
151  return MediaWikiServices::getInstance()
152  ->getLanguageFallback()
153  ->getAll( $lang, LanguageFallback::STRICT );
154  }
155 
163  public function getPath( ResourceLoaderContext $context ) {
164  $desc = $this->descriptor;
165  if ( !is_array( $desc ) ) {
166  return $this->getLocalPath( $desc );
167  }
168  if ( isset( $desc['lang'] ) ) {
169  $contextLang = $context->getLanguage();
170  if ( isset( $desc['lang'][$contextLang] ) ) {
171  return $this->getLocalPath( $desc['lang'][$contextLang] );
172  }
173  $fallbacks = $this->getLangFallbacks( $contextLang );
174  foreach ( $fallbacks as $lang ) {
175  if ( isset( $desc['lang'][$lang] ) ) {
176  return $this->getLocalPath( $desc['lang'][$lang] );
177  }
178  }
179  }
180  if ( isset( $desc[$context->getDirection()] ) ) {
181  return $this->getLocalPath( $desc[$context->getDirection()] );
182  }
183  if ( isset( $desc['default'] ) ) {
184  return $this->getLocalPath( $desc['default'] );
185  } else {
186  throw new MWException( 'No matching path found' );
187  }
188  }
189 
194  protected function getLocalPath( $path ) {
195  if ( $path instanceof ResourceLoaderFilePath ) {
196  return $path->getLocalPath();
197  }
198 
199  return "{$this->basePath}/$path";
200  }
201 
208  public function getExtension( $format = 'original' ) {
209  if ( $format === 'rasterized' && $this->extension === 'svg' ) {
210  return 'png';
211  }
212  return $this->extension;
213  }
214 
221  public function getMimeType( $format = 'original' ) {
222  $ext = $this->getExtension( $format );
223  return self::$fileTypes[$ext];
224  }
225 
235  public function getUrl( ResourceLoaderContext $context, $script, $variant, $format ) {
236  $query = [
237  'modules' => $this->getModule(),
238  'image' => $this->getName(),
239  'variant' => $variant,
240  'format' => $format,
241  ];
242  if ( $this->varyOnLanguage() ) {
243  $query['lang'] = $context->getLanguage();
244  }
245  // The following parameters are at the end to keep the original order of the parameters.
246  $query['skin'] = $context->getSkin();
247  $rl = $context->getResourceLoader();
248  $query['version'] = $rl->makeVersionQuery( $context, [ $this->getModule() ] );
249 
250  return wfAppendQuery( $script, $query );
251  }
252 
261  public function getDataUri( ResourceLoaderContext $context, $variant, $format ) {
262  $type = $this->getMimeType( $format );
263  $contents = $this->getImageData( $context, $variant, $format );
264  return CSSMin::encodeStringAsDataURI( $contents, $type );
265  }
266 
283  public function getImageData( ResourceLoaderContext $context, $variant = false, $format = false ) {
284  if ( $variant === false ) {
285  $variant = $context->getVariant();
286  }
287  if ( $format === false ) {
288  $format = $context->getFormat();
289  }
290 
291  $path = $this->getPath( $context );
292  if ( !file_exists( $path ) ) {
293  throw new MWException( "File '$path' does not exist" );
294  }
295 
296  if ( $this->getExtension() !== 'svg' ) {
297  return file_get_contents( $path );
298  }
299 
300  if ( $variant && isset( $this->variants[$variant] ) ) {
301  $data = $this->variantize( $this->variants[$variant], $context );
302  } else {
304  $data = $defaultColor ?
305  $this->variantize( [ 'color' => $defaultColor ], $context ) :
306  file_get_contents( $path );
307  }
308 
309  if ( $format === 'rasterized' ) {
310  $data = $this->rasterize( $data );
311  if ( !$data ) {
312  wfDebugLog( 'ResourceLoaderImage', __METHOD__ . " failed to rasterize for $path" );
313  }
314  }
315 
316  return $data;
317  }
318 
327  public function sendResponseHeaders( ResourceLoaderContext $context ) : void {
328  $format = $context->getFormat();
329  $mime = $this->getMimeType( $format );
330  $filename = $this->getName() . '.' . $this->getExtension( $format );
331 
332  header( 'Content-Type: ' . $mime );
333  header( 'Content-Disposition: ' .
334  FileBackend::makeContentDisposition( 'inline', $filename ) );
335  }
336 
344  protected function variantize( array $variantConf, ResourceLoaderContext $context ) {
345  $dom = new DOMDocument;
346  $dom->loadXML( file_get_contents( $this->getPath( $context ) ) );
347  $root = $dom->documentElement;
348  $titleNode = null;
349  $wrapper = $dom->createElementNS( 'http://www.w3.org/2000/svg', 'g' );
350  // Reattach all direct children of the `<svg>` root node to the `<g>` wrapper
351  while ( $root->firstChild ) {
352  $node = $root->firstChild;
353  // @phan-suppress-next-line PhanUndeclaredProperty False positive
354  if ( !$titleNode && $node->nodeType === XML_ELEMENT_NODE && $node->tagName === 'title' ) {
355  // Remember the first encountered `<title>` node
356  $titleNode = $node;
357  }
358  $wrapper->appendChild( $node );
359  }
360  if ( $titleNode ) {
361  // Reattach the `<title>` node to the `<svg>` root node rather than the `<g>` wrapper
362  $root->appendChild( $titleNode );
363  }
364  $root->appendChild( $wrapper );
365  $wrapper->setAttribute( 'fill', $variantConf['color'] );
366  return $dom->saveXML();
367  }
368 
379  protected function massageSvgPathdata( $svg ) {
380  $dom = new DOMDocument;
381  $dom->loadXML( $svg );
382  foreach ( $dom->getElementsByTagName( 'path' ) as $node ) {
383  $pathData = $node->getAttribute( 'd' );
384  // Make sure there is at least one space between numbers, and that leading zero is not omitted.
385  // rsvg has issues with syntax like "M-1-2" and "M.445.483" and especially "M-.445-.483".
386  $pathData = preg_replace( '/(-?)(\d*\.\d+|\d+)/', ' ${1}0$2 ', $pathData );
387  // Strip unnecessary leading zeroes for prettiness, not strictly necessary
388  $pathData = preg_replace( '/([ -])0(\d)/', '$1$2', $pathData );
389  $node->setAttribute( 'd', $pathData );
390  }
391  return $dom->saveXML();
392  }
393 
400  protected function rasterize( $svg ) {
402 
403  // This code should be factored out to a separate method on SvgHandler, or perhaps a separate
404  // class, with a separate set of configuration settings.
405  //
406  // This is a distinct use case from regular SVG rasterization:
407  // * We can skip many sanity and security checks (as the images come from a trusted source,
408  // rather than from the user).
409  // * We need to provide extra options to some converters to achieve acceptable quality for very
410  // small images, which might cause performance issues in the general case.
411  // * We want to directly pass image data to the converter, rather than a file path.
412  //
413  // See https://phabricator.wikimedia.org/T76473#801446 for examples of what happens with the
414  // default settings.
415  //
416  // For now, we special-case rsvg (used in WMF production) and do a messy workaround for other
417  // converters.
418 
419  $svg = $this->massageSvgPathdata( $svg );
420 
421  // Sometimes this might be 'rsvg-secure'. Long as it's rsvg.
422  if ( strpos( $wgSVGConverter, 'rsvg' ) === 0 ) {
423  $command = 'rsvg-convert';
424  if ( $wgSVGConverterPath ) {
425  $command = Shell::escape( "$wgSVGConverterPath/" ) . $command;
426  }
427 
428  $process = proc_open(
429  $command,
430  [ 0 => [ 'pipe', 'r' ], 1 => [ 'pipe', 'w' ] ],
431  $pipes
432  );
433 
434  if ( is_resource( $process ) ) {
435  fwrite( $pipes[0], $svg );
436  fclose( $pipes[0] );
437  $png = stream_get_contents( $pipes[1] );
438  fclose( $pipes[1] );
439  proc_close( $process );
440 
441  return $png ?: false;
442  }
443  return false;
444 
445  } else {
446  // Write input to and read output from a temporary file
447  $tempFilenameSvg = tempnam( wfTempDir(), 'ResourceLoaderImage' );
448  $tempFilenamePng = tempnam( wfTempDir(), 'ResourceLoaderImage' );
449 
450  file_put_contents( $tempFilenameSvg, $svg );
451 
452  $svgReader = new SVGReader( $tempFilenameSvg );
453  $metadata = $svgReader->getMetadata();
454  if ( !isset( $metadata['width'] ) || !isset( $metadata['height'] ) ) {
455  unlink( $tempFilenameSvg );
456  return false;
457  }
458 
459  $handler = new SvgHandler;
460  $res = $handler->rasterize(
461  $tempFilenameSvg,
462  $tempFilenamePng,
463  $metadata['width'],
464  $metadata['height']
465  );
466  unlink( $tempFilenameSvg );
467 
468  $png = null;
469  if ( $res === true ) {
470  $png = file_get_contents( $tempFilenamePng );
471  unlink( $tempFilenamePng );
472  }
473 
474  return $png ?: false;
475  }
476  }
477 
483  private function varyOnLanguage() {
484  return is_array( $this->descriptor ) && (
485  isset( $this->descriptor['ltr'] ) ||
486  isset( $this->descriptor['rtl'] ) ||
487  isset( $this->descriptor['lang'] ) );
488  }
489 }
SVGReader
Definition: SVGReader.php:31
MediaWiki\Shell\Shell
Executes shell commands.
Definition: Shell.php:44
ResourceLoaderContext
Context object that contains information about the state of a specific ResourceLoader web request.
Definition: ResourceLoaderContext.php:33
ResourceLoaderImage\$name
string $name
Definition: ResourceLoaderImage.php:44
ResourceLoaderContext\getDirection
getDirection()
Definition: ResourceLoaderContext.php:174
CSSMin\encodeStringAsDataURI
static encodeStringAsDataURI( $contents, $type, $ie8Compat=true)
Encode file contents as a data URI with chosen MIME type.
Definition: CSSMin.php:141
ResourceLoaderImage\variantize
variantize(array $variantConf, ResourceLoaderContext $context)
Convert this image, which is assumed to be SVG, to given variant.
Definition: ResourceLoaderImage.php:344
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:163
$lang
if(!isset( $args[0])) $lang
Definition: testCompression.php:37
ResourceLoaderContext\getResourceLoader
getResourceLoader()
Definition: ResourceLoaderContext.php:123
ResourceLoaderFilePath
An object to represent a path to a JavaScript/CSS file, along with a remote and local base path,...
Definition: ResourceLoaderFilePath.php:28
MediaWiki\Languages\LanguageFallback
Definition: LanguageFallback.php:31
$res
$res
Definition: testCompression.php:57
ResourceLoaderImage\$descriptor
string array $descriptor
Definition: ResourceLoaderImage.php:48
ResourceLoaderImage\$extension
string $extension
Definition: ResourceLoaderImage.php:56
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:989
ResourceLoaderImage\getLangFallbacks
getLangFallbacks(string $lang)
Definition: ResourceLoaderImage.php:150
ResourceLoaderImage\getVariants
getVariants()
Get the list of variants this image can be converted to.
Definition: ResourceLoaderImage.php:141
ResourceLoaderContext\getVariant
getVariant()
Definition: ResourceLoaderContext.php:272
ResourceLoaderContext\getFormat
getFormat()
Definition: ResourceLoaderContext.php:279
ResourceLoaderImage\getMimeType
getMimeType( $format='original')
Get the MIME type of the image.
Definition: ResourceLoaderImage.php:221
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:438
ResourceLoaderImage\$module
string $module
Definition: ResourceLoaderImage.php:46
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:1291
MWException
MediaWiki exception.
Definition: MWException.php:29
ResourceLoaderImage\varyOnLanguage
varyOnLanguage()
Check if the image depends on the language.
Definition: ResourceLoaderImage.php:483
SvgHandler
Handler for SVG images.
Definition: SvgHandler.php:33
ResourceLoaderImage\rasterize
rasterize( $svg)
Convert passed image data, which is assumed to be SVG, to PNG.
Definition: ResourceLoaderImage.php:400
ResourceLoaderImage\getModule
getModule()
Get name of the module this image belongs to.
Definition: ResourceLoaderImage.php:132
ResourceLoaderContext\getLanguage
getLanguage()
Definition: ResourceLoaderContext.php:156
ResourceLoaderImage
Class encapsulating an image used in a ResourceLoaderImageModule.
Definition: ResourceLoaderImage.php:31
ResourceLoaderImage\$defaultColor
string null $defaultColor
Definition: ResourceLoaderImage.php:54
ResourceLoaderImage\$variants
array $variants
Definition: ResourceLoaderImage.php:52
ResourceLoaderImage\getPath
getPath(ResourceLoaderContext $context)
Get the path to image file for given context.
Definition: ResourceLoaderImage.php:163
ResourceLoaderImage\getLocalPath
getLocalPath( $path)
Definition: ResourceLoaderImage.php:194
ResourceLoaderContext\getSkin
getSkin()
Definition: ResourceLoaderContext.php:188
$command
$command
Definition: mcc.php:125
wfTempDir
wfTempDir()
Tries to get the system directory for temporary files.
Definition: GlobalFunctions.php:1878
ResourceLoaderImage\massageSvgPathdata
massageSvgPathdata( $svg)
Massage the SVG image data for converters which don't understand some path data syntax.
Definition: ResourceLoaderImage.php:379
ResourceLoaderImage\$basePath
string $basePath
Definition: ResourceLoaderImage.php:50
ResourceLoaderImage\getExtension
getExtension( $format='original')
Get the extension of the image.
Definition: ResourceLoaderImage.php:208
$path
$path
Definition: NoLocalSettings.php:25
ResourceLoaderImage\getDataUri
getDataUri(ResourceLoaderContext $context, $variant, $format)
Get the data: URI that will produce this image.
Definition: ResourceLoaderImage.php:261
$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:283
$mime
$mime
Definition: router.php:60
ResourceLoaderImage\getName
getName()
Get name of this image.
Definition: ResourceLoaderImage.php:123
ResourceLoaderImage\__construct
__construct( $name, $module, $descriptor, $basePath, array $variants, $defaultColor=null)
Definition: ResourceLoaderImage.php:68
ResourceLoaderImage\getUrl
getUrl(ResourceLoaderContext $context, $script, $variant, $format)
Get the load.php URL that will produce this image.
Definition: ResourceLoaderImage.php:235
$wgSVGConverter
$wgSVGConverter
Pick a converter defined in $wgSVGConverters.
Definition: DefaultSettings.php:1286
ResourceLoaderImage\sendResponseHeaders
sendResponseHeaders(ResourceLoaderContext $context)
Send response headers (using the header() function) that are necessary to correctly serve the image d...
Definition: ResourceLoaderImage.php:327
$type
$type
Definition: testCompression.php:52
FileBackend\makeContentDisposition
static makeContentDisposition( $type, $filename='')
Build a Content-Disposition header value per RFC 6266.
Definition: FileBackend.php:1637