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