MediaWiki  master
ResourceLoaderImage.php
Go to the documentation of this file.
1 <?php
24 
32 
37  protected static $fileTypes = [
38  'svg' => 'image/svg+xml',
39  'png' => 'image/png',
40  'gif' => 'image/gif',
41  'jpg' => 'image/jpg',
42  ];
43 
45  private $name;
47  private $module;
49  private $descriptor;
51  private $basePath;
53  private $variants;
55  private $defaultColor;
57  private $extension;
58 
70  $defaultColor = null
71  ) {
72  $this->name = $name;
73  $this->module = $module;
74  $this->descriptor = $descriptor;
75  $this->basePath = $basePath;
76  $this->variants = $variants;
77  $this->defaultColor = $defaultColor;
78 
79  // Expand shorthands:
80  // [ "en,de,fr" => "foo.svg" ]
81  // → [ "en" => "foo.svg", "de" => "foo.svg", "fr" => "foo.svg" ]
82  if ( is_array( $this->descriptor ) && isset( $this->descriptor['lang'] ) ) {
83  foreach ( array_keys( $this->descriptor['lang'] ) as $langList ) {
84  if ( strpos( $langList, ',' ) !== false ) {
85  $this->descriptor['lang'] += array_fill_keys(
86  explode( ',', $langList ),
87  $this->descriptor['lang'][$langList]
88  );
89  unset( $this->descriptor['lang'][$langList] );
90  }
91  }
92  }
93  // Remove 'deprecated' key
94  if ( is_array( $this->descriptor ) ) {
95  unset( $this->descriptor['deprecated'] );
96  }
97 
98  // Ensure that all files have common extension.
99  $extensions = [];
100  $descriptor = is_array( $this->descriptor ) ? $this->descriptor : [ $this->descriptor ];
101  array_walk_recursive( $descriptor, function ( $path ) use ( &$extensions ) {
102  $extensions[] = pathinfo( $this->getLocalPath( $path ), PATHINFO_EXTENSION );
103  } );
104  $extensions = array_unique( $extensions );
105  if ( count( $extensions ) !== 1 ) {
106  throw new InvalidArgumentException(
107  "File type for different image files of '$name' not the same in module '$module'"
108  );
109  }
110  $ext = $extensions[0];
111  if ( !isset( self::$fileTypes[$ext] ) ) {
112  throw new InvalidArgumentException(
113  "Invalid file type for image files of '$name' (valid: svg, png, gif, jpg) in module '$module'"
114  );
115  }
116  $this->extension = $ext;
117  }
118 
124  public function getName() {
125  return $this->name;
126  }
127 
133  public function getModule() {
134  return $this->module;
135  }
136 
142  public function getVariants() {
143  return array_keys( $this->variants );
144  }
145 
151  protected function getLangFallbacks( string $lang ) : array {
152  return MediaWikiServices::getInstance()
153  ->getLanguageFallback()
154  ->getAll( $lang, LanguageFallback::STRICT );
155  }
156 
165  $desc = $this->descriptor;
166  if ( !is_array( $desc ) ) {
167  return $this->getLocalPath( $desc );
168  }
169  if ( isset( $desc['lang'] ) ) {
170  $contextLang = $context->getLanguage();
171  if ( isset( $desc['lang'][$contextLang] ) ) {
172  return $this->getLocalPath( $desc['lang'][$contextLang] );
173  }
174  $fallbacks = $this->getLangFallbacks( $contextLang );
175  foreach ( $fallbacks as $lang ) {
176  if ( isset( $desc['lang'][$lang] ) ) {
177  return $this->getLocalPath( $desc['lang'][$lang] );
178  }
179  }
180  }
181  if ( isset( $desc[$context->getDirection()] ) ) {
182  return $this->getLocalPath( $desc[$context->getDirection()] );
183  }
184  if ( isset( $desc['default'] ) ) {
185  return $this->getLocalPath( $desc['default'] );
186  } else {
187  throw new MWException( 'No matching path found' );
188  }
189  }
190 
195  protected function getLocalPath( $path ) {
196  if ( $path instanceof ResourceLoaderFilePath ) {
197  return $path->getLocalPath();
198  }
199 
200  return "{$this->basePath}/$path";
201  }
202 
209  public function getExtension( $format = 'original' ) {
210  if ( $format === 'rasterized' && $this->extension === 'svg' ) {
211  return 'png';
212  }
213  return $this->extension;
214  }
215 
222  public function getMimeType( $format = 'original' ) {
223  $ext = $this->getExtension( $format );
224  return self::$fileTypes[$ext];
225  }
226 
236  public function getUrl( ResourceLoaderContext $context, $script, $variant, $format ) {
237  $query = [
238  'modules' => $this->getModule(),
239  'image' => $this->getName(),
240  'variant' => $variant,
241  'format' => $format,
242  ];
243  if ( $this->varyOnLanguage() ) {
244  $query['lang'] = $context->getLanguage();
245  }
246  // The following parameters are at the end to keep the original order of the parameters.
247  $query['skin'] = $context->getSkin();
248  $rl = $context->getResourceLoader();
249  $query['version'] = $rl->makeVersionQuery( $context, [ $this->getModule() ] );
250 
251  return wfAppendQuery( $script, $query );
252  }
253 
262  public function getDataUri( ResourceLoaderContext $context, $variant, $format ) {
263  $type = $this->getMimeType( $format );
264  $contents = $this->getImageData( $context, $variant, $format );
265  return CSSMin::encodeStringAsDataURI( $contents, $type );
266  }
267 
284  public function getImageData( ResourceLoaderContext $context, $variant = false, $format = false ) {
285  if ( $variant === false ) {
286  $variant = $context->getVariant();
287  }
288  if ( $format === false ) {
289  $format = $context->getFormat();
290  }
291 
292  $path = $this->getPath( $context );
293  if ( !file_exists( $path ) ) {
294  throw new MWException( "File '$path' does not exist" );
295  }
296 
297  if ( $this->getExtension() !== 'svg' ) {
298  return file_get_contents( $path );
299  }
300 
301  if ( $variant && isset( $this->variants[$variant] ) ) {
302  $data = $this->variantize( $this->variants[$variant], $context );
303  } else {
305  $data = $defaultColor ?
306  $this->variantize( [ 'color' => $defaultColor ], $context ) :
307  file_get_contents( $path );
308  }
309 
310  if ( $format === 'rasterized' ) {
311  $data = $this->rasterize( $data );
312  if ( !$data ) {
313  wfDebugLog( 'ResourceLoaderImage', __METHOD__ . " failed to rasterize for $path" );
314  }
315  }
316 
317  return $data;
318  }
319 
329  $format = $context->getFormat();
330  $mime = $this->getMimeType( $format );
331  $filename = $this->getName() . '.' . $this->getExtension( $format );
332 
333  header( 'Content-Type: ' . $mime );
334  header( 'Content-Disposition: ' .
335  FileBackend::makeContentDisposition( 'inline', $filename ) );
336  }
337 
345  protected function variantize( array $variantConf, ResourceLoaderContext $context ) {
346  $dom = new DOMDocument;
347  $dom->loadXML( file_get_contents( $this->getPath( $context ) ) );
348  $root = $dom->documentElement;
349  $titleNode = null;
350  $wrapper = $dom->createElementNS( 'http://www.w3.org/2000/svg', 'g' );
351  // Reattach all direct children of the `<svg>` root node to the `<g>` wrapper
352  while ( $root->firstChild ) {
353  $node = $root->firstChild;
354  // @phan-suppress-next-line PhanUndeclaredProperty False positive
355  if ( !$titleNode && $node->nodeType === XML_ELEMENT_NODE && $node->tagName === 'title' ) {
356  // Remember the first encountered `<title>` node
357  $titleNode = $node;
358  }
359  $wrapper->appendChild( $node );
360  }
361  if ( $titleNode ) {
362  // Reattach the `<title>` node to the `<svg>` root node rather than the `<g>` wrapper
363  $root->appendChild( $titleNode );
364  }
365  $root->appendChild( $wrapper );
366  $wrapper->setAttribute( 'fill', $variantConf['color'] );
367  return $dom->saveXML();
368  }
369 
380  protected function massageSvgPathdata( $svg ) {
381  $dom = new DOMDocument;
382  $dom->loadXML( $svg );
383  foreach ( $dom->getElementsByTagName( 'path' ) as $node ) {
384  $pathData = $node->getAttribute( 'd' );
385  // Make sure there is at least one space between numbers, and that leading zero is not omitted.
386  // rsvg has issues with syntax like "M-1-2" and "M.445.483" and especially "M-.445-.483".
387  $pathData = preg_replace( '/(-?)(\d*\.\d+|\d+)/', ' ${1}0$2 ', $pathData );
388  // Strip unnecessary leading zeroes for prettiness, not strictly necessary
389  $pathData = preg_replace( '/([ -])0(\d)/', '$1$2', $pathData );
390  $node->setAttribute( 'd', $pathData );
391  }
392  return $dom->saveXML();
393  }
394 
401  protected function rasterize( $svg ) {
421 
422  $svg = $this->massageSvgPathdata( $svg );
423 
424  // Sometimes this might be 'rsvg-secure'. Long as it's rsvg.
425  if ( strpos( $wgSVGConverter, 'rsvg' ) === 0 ) {
426  $command = 'rsvg-convert';
427  if ( $wgSVGConverterPath ) {
428  $command = Shell::escape( "$wgSVGConverterPath/" ) . $command;
429  }
430 
431  $process = proc_open(
432  $command,
433  [ 0 => [ 'pipe', 'r' ], 1 => [ 'pipe', 'w' ] ],
434  $pipes
435  );
436 
437  if ( is_resource( $process ) ) {
438  fwrite( $pipes[0], $svg );
439  fclose( $pipes[0] );
440  $png = stream_get_contents( $pipes[1] );
441  fclose( $pipes[1] );
442  proc_close( $process );
443 
444  return $png ?: false;
445  }
446  return false;
447 
448  } else {
449  // Write input to and read output from a temporary file
450  $tempFilenameSvg = tempnam( wfTempDir(), 'ResourceLoaderImage' );
451  $tempFilenamePng = tempnam( wfTempDir(), 'ResourceLoaderImage' );
452 
453  file_put_contents( $tempFilenameSvg, $svg );
454 
455  $svgReader = new SVGReader( $tempFilenameSvg );
456  $metadata = $svgReader->getMetadata();
457  if ( !isset( $metadata['width'] ) || !isset( $metadata['height'] ) ) {
458  unlink( $tempFilenameSvg );
459  return false;
460  }
461 
462  $handler = new SvgHandler;
463  $res = $handler->rasterize(
464  $tempFilenameSvg,
465  $tempFilenamePng,
466  $metadata['width'],
467  $metadata['height']
468  );
469  unlink( $tempFilenameSvg );
470 
471  $png = null;
472  if ( $res === true ) {
473  $png = file_get_contents( $tempFilenamePng );
474  unlink( $tempFilenamePng );
475  }
476 
477  return $png ?: false;
478  }
479  }
480 
486  private function varyOnLanguage() {
487  return is_array( $this->descriptor ) && (
488  isset( $this->descriptor['ltr'] ) ||
489  isset( $this->descriptor['rtl'] ) ||
490  isset( $this->descriptor['lang'] ) );
491  }
492 }
Class encapsulating an image used in a ResourceLoaderImageModule.
varyOnLanguage()
Check if the image depends on the language.
$context
Definition: load.php:40
getLangFallbacks(string $lang)
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.
if(!isset( $args[0])) $lang
static array string $name
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.
__construct( $name, $module, $descriptor, $basePath, array $variants, $defaultColor=null)
$command
Definition: mcc.php:125
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.
static encodeStringAsDataURI( $contents, $type, $ie8Compat=true)
Encode file contents as a data URI with chosen MIME type.
Definition: CSSMin.php:141
getVariants()
Get the list of variants this image can be converted to.
variantize(array $variantConf, ResourceLoaderContext $context)
Convert this image, which is assumed to be SVG, to given variant.
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...
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...
if(!is_readable( $file)) $ext
Definition: router.php:48
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.
Context object that contains information about the state of a specific ResourceLoader web request...
getExtension( $format='original')
Get the extension of the image.