MediaWiki  1.30.0
SVGMetadataExtractor.php
Go to the documentation of this file.
1 <?php
32  static function getMetadata( $filename ) {
33  $svg = new SVGReader( $filename );
34 
35  return $svg->getMetadata();
36  }
37 }
38 
42 class SVGReader {
43  const DEFAULT_WIDTH = 512;
44  const DEFAULT_HEIGHT = 512;
45  const NS_SVG = 'http://www.w3.org/2000/svg';
46  const LANG_PREFIX_MATCH = 1;
47  const LANG_FULL_MATCH = 2;
48 
50  private $reader = null;
51 
53  private $mDebug = false;
54 
56  private $metadata = [];
57  private $languages = [];
58  private $languagePrefixes = [];
59 
65  function __construct( $source ) {
67  $this->reader = new XMLReader();
68 
69  // Don't use $file->getSize() since file object passed to SVGHandler::getMetadata is bogus.
70  $size = filesize( $source );
71  if ( $size === false ) {
72  throw new MWException( "Error getting filesize of SVG." );
73  }
74 
75  if ( $size > $wgSVGMetadataCutoff ) {
76  $this->debug( "SVG is $size bytes, which is bigger than $wgSVGMetadataCutoff. Truncating." );
77  $contents = file_get_contents( $source, false, null, -1, $wgSVGMetadataCutoff );
78  if ( $contents === false ) {
79  throw new MWException( 'Error reading SVG file.' );
80  }
81  $this->reader->XML( $contents, null, LIBXML_NOERROR | LIBXML_NOWARNING );
82  } else {
83  $this->reader->open( $source, null, LIBXML_NOERROR | LIBXML_NOWARNING );
84  }
85 
86  // Expand entities, since Adobe Illustrator uses them for xmlns
87  // attributes (T33719). Note that libxml2 has some protection
88  // against large recursive entity expansions so this is not as
89  // insecure as it might appear to be. However, it is still extremely
90  // insecure. It's necessary to wrap any read() calls with
91  // libxml_disable_entity_loader() to avoid arbitrary local file
92  // inclusion, or even arbitrary code execution if the expect
93  // extension is installed (T48859).
94  $oldDisable = libxml_disable_entity_loader( true );
95  $this->reader->setParserProperty( XMLReader::SUBST_ENTITIES, true );
96 
97  $this->metadata['width'] = self::DEFAULT_WIDTH;
98  $this->metadata['height'] = self::DEFAULT_HEIGHT;
99 
100  // The size in the units specified by the SVG file
101  // (for the metadata box)
102  // Per the SVG spec, if unspecified, default to '100%'
103  $this->metadata['originalWidth'] = '100%';
104  $this->metadata['originalHeight'] = '100%';
105 
106  // Because we cut off the end of the svg making an invalid one. Complicated
107  // try catch thing to make sure warnings get restored. Seems like there should
108  // be a better way.
109  MediaWiki\suppressWarnings();
110  try {
111  $this->read();
112  } catch ( Exception $e ) {
113  // Note, if this happens, the width/height will be taken to be 0x0.
114  // Should we consider it the default 512x512 instead?
115  MediaWiki\restoreWarnings();
116  libxml_disable_entity_loader( $oldDisable );
117  throw $e;
118  }
119  MediaWiki\restoreWarnings();
120  libxml_disable_entity_loader( $oldDisable );
121  }
122 
126  public function getMetadata() {
127  return $this->metadata;
128  }
129 
135  protected function read() {
136  $keepReading = $this->reader->read();
137 
138  /* Skip until first element */
139  while ( $keepReading && $this->reader->nodeType != XMLReader::ELEMENT ) {
140  $keepReading = $this->reader->read();
141  }
142 
143  if ( $this->reader->localName != 'svg' || $this->reader->namespaceURI != self::NS_SVG ) {
144  throw new MWException( "Expected <svg> tag, got " .
145  $this->reader->localName . " in NS " . $this->reader->namespaceURI );
146  }
147  $this->debug( "<svg> tag is correct." );
148  $this->handleSVGAttribs();
149 
150  $exitDepth = $this->reader->depth;
151  $keepReading = $this->reader->read();
152  while ( $keepReading ) {
153  $tag = $this->reader->localName;
154  $type = $this->reader->nodeType;
155  $isSVG = ( $this->reader->namespaceURI == self::NS_SVG );
156 
157  $this->debug( "$tag" );
158 
159  if ( $isSVG && $tag == 'svg' && $type == XMLReader::END_ELEMENT
160  && $this->reader->depth <= $exitDepth
161  ) {
162  break;
163  } elseif ( $isSVG && $tag == 'title' ) {
164  $this->readField( $tag, 'title' );
165  } elseif ( $isSVG && $tag == 'desc' ) {
166  $this->readField( $tag, 'description' );
167  } elseif ( $isSVG && $tag == 'metadata' && $type == XMLReader::ELEMENT ) {
168  $this->readXml( $tag, 'metadata' );
169  } elseif ( $isSVG && $tag == 'script' ) {
170  // We normally do not allow scripted svgs.
171  // However its possible to configure MW to let them
172  // in, and such files should be considered animated.
173  $this->metadata['animated'] = true;
174  } elseif ( $tag !== '#text' ) {
175  $this->debug( "Unhandled top-level XML tag $tag" );
176 
177  // Recurse into children of current tag, looking for animation and languages.
178  $this->animateFilterAndLang( $tag );
179  }
180 
181  // Goto next element, which is sibling of current (Skip children).
182  $keepReading = $this->reader->next();
183  }
184 
185  $this->reader->close();
186 
187  $this->metadata['translations'] = $this->languages + $this->languagePrefixes;
188 
189  return true;
190  }
191 
198  private function readField( $name, $metafield = null ) {
199  $this->debug( "Read field $metafield" );
200  if ( !$metafield || $this->reader->nodeType != XMLReader::ELEMENT ) {
201  return;
202  }
203  $keepReading = $this->reader->read();
204  while ( $keepReading ) {
205  if ( $this->reader->localName == $name
206  && $this->reader->namespaceURI == self::NS_SVG
207  && $this->reader->nodeType == XMLReader::END_ELEMENT
208  ) {
209  break;
210  } elseif ( $this->reader->nodeType == XMLReader::TEXT ) {
211  $this->metadata[$metafield] = trim( $this->reader->value );
212  }
213  $keepReading = $this->reader->read();
214  }
215  }
216 
223  private function readXml( $metafield = null ) {
224  $this->debug( "Read top level metadata" );
225  if ( !$metafield || $this->reader->nodeType != XMLReader::ELEMENT ) {
226  return;
227  }
228  // @todo Find and store type of xml snippet. metadata['metadataType'] = "rdf"
229  if ( method_exists( $this->reader, 'readInnerXML' ) ) {
230  $this->metadata[$metafield] = trim( $this->reader->readInnerXml() );
231  } else {
232  throw new MWException( "The PHP XMLReader extension does not come " .
233  "with readInnerXML() method. Your libxml is probably out of " .
234  "date (need 2.6.20 or later)." );
235  }
236  $this->reader->next();
237  }
238 
245  private function animateFilterAndLang( $name ) {
246  $this->debug( "animate filter for tag $name" );
247  if ( $this->reader->nodeType != XMLReader::ELEMENT ) {
248  return;
249  }
250  if ( $this->reader->isEmptyElement ) {
251  return;
252  }
253  $exitDepth = $this->reader->depth;
254  $keepReading = $this->reader->read();
255  while ( $keepReading ) {
256  if ( $this->reader->localName == $name && $this->reader->depth <= $exitDepth
257  && $this->reader->nodeType == XMLReader::END_ELEMENT
258  ) {
259  break;
260  } elseif ( $this->reader->namespaceURI == self::NS_SVG
261  && $this->reader->nodeType == XMLReader::ELEMENT
262  ) {
263  $sysLang = $this->reader->getAttribute( 'systemLanguage' );
264  if ( !is_null( $sysLang ) && $sysLang !== '' ) {
265  // See https://www.w3.org/TR/SVG/struct.html#SystemLanguageAttribute
266  $langList = explode( ',', $sysLang );
267  foreach ( $langList as $langItem ) {
268  $langItem = trim( $langItem );
269  if ( Language::isWellFormedLanguageTag( $langItem ) ) {
270  $this->languages[$langItem] = self::LANG_FULL_MATCH;
271  }
272  // Note, the standard says that any prefix should work,
273  // here we do only the initial prefix, since that will catch
274  // 99% of cases, and we are going to compare against fallbacks.
275  // This differs mildly from how the spec says languages should be
276  // handled, however it matches better how the MediaWiki language
277  // preference is generally handled.
278  $dash = strpos( $langItem, '-' );
279  // Intentionally checking both !false and > 0 at the same time.
280  if ( $dash ) {
281  $itemPrefix = substr( $langItem, 0, $dash );
282  if ( Language::isWellFormedLanguageTag( $itemPrefix ) ) {
283  $this->languagePrefixes[$itemPrefix] = self::LANG_PREFIX_MATCH;
284  }
285  }
286  }
287  }
288  switch ( $this->reader->localName ) {
289  case 'script':
290  // Normally we disallow files with
291  // <script>, but its possible
292  // to configure MW to disable
293  // such checks.
294  case 'animate':
295  case 'set':
296  case 'animateMotion':
297  case 'animateColor':
298  case 'animateTransform':
299  $this->debug( "HOUSTON WE HAVE ANIMATION" );
300  $this->metadata['animated'] = true;
301  break;
302  }
303  }
304  $keepReading = $this->reader->read();
305  }
306  }
307 
308  private function debug( $data ) {
309  if ( $this->mDebug ) {
310  wfDebug( "SVGReader: $data\n" );
311  }
312  }
313 
319  private function handleSVGAttribs() {
320  $defaultWidth = self::DEFAULT_WIDTH;
321  $defaultHeight = self::DEFAULT_HEIGHT;
322  $aspect = 1.0;
323  $width = null;
324  $height = null;
325 
326  if ( $this->reader->getAttribute( 'viewBox' ) ) {
327  // min-x min-y width height
328  $viewBox = preg_split( '/\s+/', trim( $this->reader->getAttribute( 'viewBox' ) ) );
329  if ( count( $viewBox ) == 4 ) {
330  $viewWidth = $this->scaleSVGUnit( $viewBox[2] );
331  $viewHeight = $this->scaleSVGUnit( $viewBox[3] );
332  if ( $viewWidth > 0 && $viewHeight > 0 ) {
333  $aspect = $viewWidth / $viewHeight;
334  $defaultHeight = $defaultWidth / $aspect;
335  }
336  }
337  }
338  if ( $this->reader->getAttribute( 'width' ) ) {
339  $width = $this->scaleSVGUnit( $this->reader->getAttribute( 'width' ), $defaultWidth );
340  $this->metadata['originalWidth'] = $this->reader->getAttribute( 'width' );
341  }
342  if ( $this->reader->getAttribute( 'height' ) ) {
343  $height = $this->scaleSVGUnit( $this->reader->getAttribute( 'height' ), $defaultHeight );
344  $this->metadata['originalHeight'] = $this->reader->getAttribute( 'height' );
345  }
346 
347  if ( !isset( $width ) && !isset( $height ) ) {
348  $width = $defaultWidth;
349  $height = $width / $aspect;
350  } elseif ( isset( $width ) && !isset( $height ) ) {
351  $height = $width / $aspect;
352  } elseif ( isset( $height ) && !isset( $width ) ) {
353  $width = $height * $aspect;
354  }
355 
356  if ( $width > 0 && $height > 0 ) {
357  $this->metadata['width'] = intval( round( $width ) );
358  $this->metadata['height'] = intval( round( $height ) );
359  }
360  }
361 
370  static function scaleSVGUnit( $length, $viewportSize = 512 ) {
371  static $unitLength = [
372  'px' => 1.0,
373  'pt' => 1.25,
374  'pc' => 15.0,
375  'mm' => 3.543307,
376  'cm' => 35.43307,
377  'in' => 90.0,
378  'em' => 16.0, // fake it?
379  'ex' => 12.0, // fake it?
380  '' => 1.0, // "User units" pixels by default
381  ];
382  $matches = [];
383  if ( preg_match( '/^\s*(\d+(?:\.\d+)?)(em|ex|px|pt|pc|cm|mm|in|%|)\s*$/', $length, $matches ) ) {
384  $length = floatval( $matches[1] );
385  $unit = $matches[2];
386  if ( $unit == '%' ) {
387  return $length * 0.01 * $viewportSize;
388  } else {
389  return $length * $unitLength[$unit];
390  }
391  } else {
392  // Assume pixels
393  return floatval( $length );
394  }
395  }
396 }
SVGReader
Definition: SVGMetadataExtractor.php:42
SVGReader\$languages
$languages
Definition: SVGMetadataExtractor.php:57
SVGReader\LANG_PREFIX_MATCH
const LANG_PREFIX_MATCH
Definition: SVGMetadataExtractor.php:46
SVGMetadataExtractor
Definition: SVGMetadataExtractor.php:31
SVGMetadataExtractor\getMetadata
static getMetadata( $filename)
Definition: SVGMetadataExtractor.php:32
captcha-old.count
count
Definition: captcha-old.py:249
SVGReader\__construct
__construct( $source)
Creates an SVGReader drawing from the source provided.
Definition: SVGMetadataExtractor.php:65
SVGReader\scaleSVGUnit
static scaleSVGUnit( $length, $viewportSize=512)
Return a rounded pixel equivalent for a labeled CSS/SVG length.
Definition: SVGMetadataExtractor.php:370
SVGReader\$reader
null XMLReader $reader
Definition: SVGMetadataExtractor.php:50
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:302
SVGReader\$mDebug
bool $mDebug
Definition: SVGMetadataExtractor.php:53
SVGReader\read
read()
Read the SVG.
Definition: SVGMetadataExtractor.php:135
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
Language\isWellFormedLanguageTag
static isWellFormedLanguageTag( $code, $lenient=false)
Returns true if a language code string is a well-formed language tag according to RFC 5646.
Definition: Language.php:284
SVGReader\readXml
readXml( $metafield=null)
Read an XML snippet from an element.
Definition: SVGMetadataExtractor.php:223
SVGReader\NS_SVG
const NS_SVG
Definition: SVGMetadataExtractor.php:45
SVGReader\DEFAULT_WIDTH
const DEFAULT_WIDTH
Definition: SVGMetadataExtractor.php:43
MWException
MediaWiki exception.
Definition: MWException.php:26
$matches
$matches
Definition: NoLocalSettings.php:24
SVGReader\$metadata
array $metadata
Definition: SVGMetadataExtractor.php:56
SVGReader\LANG_FULL_MATCH
const LANG_FULL_MATCH
Definition: SVGMetadataExtractor.php:47
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
wfDebug
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:1047
$wgSVGMetadataCutoff
$wgSVGMetadataCutoff
Don't read SVG metadata beyond this point.
Definition: DefaultSettings.php:1140
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2141
SVGReader\animateFilterAndLang
animateFilterAndLang( $name)
Filter all children, looking for animated elements.
Definition: SVGMetadataExtractor.php:245
SVGReader\handleSVGAttribs
handleSVGAttribs()
Parse the attributes of an SVG element.
Definition: SVGMetadataExtractor.php:319
SVGReader\$languagePrefixes
$languagePrefixes
Definition: SVGMetadataExtractor.php:58
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
$source
$source
Definition: mwdoc-filter.php:46
SVGReader\debug
debug( $data)
Definition: SVGMetadataExtractor.php:308
SVGReader\getMetadata
getMetadata()
Definition: SVGMetadataExtractor.php:126
SVGReader\readField
readField( $name, $metafield=null)
Read a textelement from an element.
Definition: SVGMetadataExtractor.php:198
SVGReader\DEFAULT_HEIGHT
const DEFAULT_HEIGHT
Definition: SVGMetadataExtractor.php:44
array
the array() calling protocol came about after MediaWiki 1.4rc1.
$type
$type
Definition: testCompression.php:48