MediaWiki  REL1_20
SVGMetadataExtractor.php
Go to the documentation of this file.
00001 <?php
00031 class SVGMetadataExtractor {
00032         static function getMetadata( $filename ) {
00033                 $svg = new SVGReader( $filename );
00034                 return $svg->getMetadata();
00035         }
00036 }
00037 
00041 class SVGReader {
00042         const DEFAULT_WIDTH = 512;
00043         const DEFAULT_HEIGHT = 512;
00044         const NS_SVG = 'http://www.w3.org/2000/svg';
00045 
00046         private $reader = null;
00047         private $mDebug = false;
00048         private $metadata = Array();
00049 
00056         function __construct( $source ) {
00057                 global $wgSVGMetadataCutoff;
00058                 $this->reader = new XMLReader();
00059 
00060                 // Don't use $file->getSize() since file object passed to SVGHandler::getMetadata is bogus.
00061                 $size = filesize( $source );
00062                 if ( $size === false ) {
00063                         throw new MWException( "Error getting filesize of SVG." );
00064                 }
00065 
00066                 if ( $size > $wgSVGMetadataCutoff ) {
00067                         $this->debug( "SVG is $size bytes, which is bigger than $wgSVGMetadataCutoff. Truncating." );
00068                         $contents = file_get_contents( $source, false, null, -1, $wgSVGMetadataCutoff );
00069                         if ($contents === false) {
00070                                 throw new MWException( 'Error reading SVG file.' );
00071                         }
00072                         $this->reader->XML( $contents, null, LIBXML_NOERROR | LIBXML_NOWARNING );
00073                 } else {
00074                         $this->reader->open( $source, null, LIBXML_NOERROR | LIBXML_NOWARNING );
00075                 }
00076 
00077                 // Expand entities, since Adobe Illustrator uses them for xmlns
00078                 // attributes (bug 31719). Note that libxml2 has some protection
00079                 // against large recursive entity expansions so this is not as
00080                 // insecure as it might appear to be. However, it is still extremely
00081                 // insecure. It's necessary to wrap any read() calls with
00082                 // libxml_disable_entity_loader() to avoid arbitrary local file
00083                 // inclusion, or even arbitrary code execution if the expect
00084                 // extension is installed (bug 46859).
00085                 $oldDisable = libxml_disable_entity_loader( true );
00086                 $this->reader->setParserProperty( XMLReader::SUBST_ENTITIES, true );
00087 
00088                 $this->metadata['width'] = self::DEFAULT_WIDTH;
00089                 $this->metadata['height'] = self::DEFAULT_HEIGHT;
00090 
00091                 // The size in the units specified by the SVG file
00092                 // (for the metadata box)
00093                 // Per the SVG spec, if unspecified, default to '100%'
00094                 $this->metadata['originalWidth'] = '100%';
00095                 $this->metadata['originalHeight'] = '100%';
00096 
00097                 // Because we cut off the end of the svg making an invalid one. Complicated
00098                 // try catch thing to make sure warnings get restored. Seems like there should
00099                 // be a better way.
00100                 wfSuppressWarnings();
00101                 try {
00102                         $this->read();
00103                 } catch( Exception $e ) {
00104                         // Note, if this happens, the width/height will be taken to be 0x0.
00105                         // Should we consider it the default 512x512 instead?
00106                         wfRestoreWarnings();
00107                         libxml_disable_entity_loader( $oldDisable );
00108                         throw $e;
00109                 }
00110                 wfRestoreWarnings();
00111                 libxml_disable_entity_loader( $oldDisable );
00112         }
00113 
00117         public function getMetadata() {
00118                 return $this->metadata;
00119         }
00120 
00125         protected function read() {
00126                 $keepReading = $this->reader->read();
00127 
00128                 /* Skip until first element */
00129                 while( $keepReading && $this->reader->nodeType != XmlReader::ELEMENT ) {
00130                         $keepReading = $this->reader->read();
00131                 }
00132 
00133                 if ( $this->reader->localName != 'svg' || $this->reader->namespaceURI != self::NS_SVG ) {
00134                         throw new MWException( "Expected <svg> tag, got ".
00135                                 $this->reader->localName . " in NS " . $this->reader->namespaceURI );
00136                 }
00137                 $this->debug( "<svg> tag is correct." );
00138                 $this->handleSVGAttribs();
00139 
00140                 $exitDepth =  $this->reader->depth;
00141                 $keepReading = $this->reader->read();
00142                 while ( $keepReading ) {
00143                         $tag = $this->reader->localName;
00144                         $type = $this->reader->nodeType;
00145                         $isSVG = ($this->reader->namespaceURI == self::NS_SVG);
00146 
00147                         $this->debug( "$tag" );
00148 
00149                         if ( $isSVG && $tag == 'svg' && $type == XmlReader::END_ELEMENT && $this->reader->depth <= $exitDepth ) {
00150                                 break;
00151                         } elseif ( $isSVG && $tag == 'title' ) {
00152                                 $this->readField( $tag, 'title' );
00153                         } elseif ( $isSVG && $tag == 'desc' ) {
00154                                 $this->readField( $tag, 'description' );
00155                         } elseif ( $isSVG && $tag == 'metadata' && $type == XmlReader::ELEMENT ) {
00156                                 $this->readXml( $tag, 'metadata' );
00157                         } elseif ( $isSVG && $tag == 'script' ) {
00158                                 // We normally do not allow scripted svgs.
00159                                 // However its possible to configure MW to let them
00160                                 // in, and such files should be considered animated.
00161                                 $this->metadata['animated'] = true;
00162                         } elseif ( $tag !== '#text' ) {
00163                                 $this->debug( "Unhandled top-level XML tag $tag" );
00164 
00165                                 if ( !isset( $this->metadata['animated'] ) ) {
00166                                         // Recurse into children of current tag, looking for animation.
00167                                         $this->animateFilter( $tag );
00168                                 }
00169                         }
00170 
00171                         // Goto next element, which is sibling of current (Skip children).
00172                         $keepReading = $this->reader->next();
00173                 }
00174 
00175                 $this->reader->close();
00176 
00177                 return true;
00178         }
00179 
00186         private function readField( $name, $metafield=null ) {
00187                 $this->debug ( "Read field $metafield" );
00188                 if( !$metafield || $this->reader->nodeType != XmlReader::ELEMENT ) {
00189                         return;
00190                 }
00191                 $keepReading = $this->reader->read();
00192                 while( $keepReading ) {
00193                         if( $this->reader->localName == $name && $this->reader->namespaceURI == self::NS_SVG && $this->reader->nodeType == XmlReader::END_ELEMENT ) {
00194                                 break;
00195                         } elseif( $this->reader->nodeType == XmlReader::TEXT ){
00196                                 $this->metadata[$metafield] = trim( $this->reader->value );
00197                         }
00198                         $keepReading = $this->reader->read();
00199                 }
00200         }
00201 
00207         private function readXml( $metafield=null ) {
00208                 $this->debug ( "Read top level metadata" );
00209                 if( !$metafield || $this->reader->nodeType != XmlReader::ELEMENT ) {
00210                         return;
00211                 }
00212                 // TODO: find and store type of xml snippet. metadata['metadataType'] = "rdf"
00213                 if( method_exists( $this->reader, 'readInnerXML' ) ) {
00214                         $this->metadata[$metafield] = trim( $this->reader->readInnerXML() );
00215                 } else {
00216                         throw new MWException( "The PHP XMLReader extension does not come with readInnerXML() method. Your libxml is probably out of date (need 2.6.20 or later)." );
00217                 }
00218                 $this->reader->next();
00219         }
00220 
00226         private function animateFilter( $name ) {
00227                 $this->debug ( "animate filter for tag $name" );
00228                 if( $this->reader->nodeType != XmlReader::ELEMENT ) {
00229                         return;
00230                 }
00231                 if ( $this->reader->isEmptyElement ) {
00232                         return;
00233                 }
00234                 $exitDepth =  $this->reader->depth;
00235                 $keepReading = $this->reader->read();
00236                 while( $keepReading ) {
00237                         if( $this->reader->localName == $name && $this->reader->depth <= $exitDepth
00238                                 && $this->reader->nodeType == XmlReader::END_ELEMENT ) {
00239                                 break;
00240                         } elseif ( $this->reader->namespaceURI == self::NS_SVG && $this->reader->nodeType == XmlReader::ELEMENT ) {
00241                                 switch( $this->reader->localName ) {
00242                                         case 'script':
00243                                                 // Normally we disallow files with
00244                                                 // <script>, but its possible
00245                                                 // to configure MW to disable
00246                                                 // such checks.
00247                                         case 'animate':
00248                                         case 'set':
00249                                         case 'animateMotion':
00250                                         case 'animateColor':
00251                                         case 'animateTransform':
00252                                                 $this->debug( "HOUSTON WE HAVE ANIMATION" );
00253                                                 $this->metadata['animated'] = true;
00254                                                 break;
00255                                 }
00256                         }
00257                         $keepReading = $this->reader->read();
00258                 }
00259         }
00260 
00261         private function throwXmlError( $err ) {
00262                 $this->debug( "FAILURE: $err" );
00263                 wfDebug( "SVGReader XML error: $err\n" );
00264         }
00265 
00266         private function debug( $data ) {
00267                 if( $this->mDebug ) {
00268                         wfDebug( "SVGReader: $data\n" );
00269                 }
00270         }
00271 
00272         private function warn( $data ) {
00273                 wfDebug( "SVGReader: $data\n" );
00274         }
00275 
00276         private function notice( $data ) {
00277                 wfDebug( "SVGReader WARN: $data\n" );
00278         }
00279 
00285         private function handleSVGAttribs( ) {
00286                 $defaultWidth = self::DEFAULT_WIDTH;
00287                 $defaultHeight = self::DEFAULT_HEIGHT;
00288                 $aspect = 1.0;
00289                 $width = null;
00290                 $height = null;
00291 
00292                 if( $this->reader->getAttribute('viewBox') ) {
00293                         // min-x min-y width height
00294                         $viewBox = preg_split( '/\s+/', trim( $this->reader->getAttribute('viewBox') ) );
00295                         if( count( $viewBox ) == 4 ) {
00296                                 $viewWidth = $this->scaleSVGUnit( $viewBox[2] );
00297                                 $viewHeight = $this->scaleSVGUnit( $viewBox[3] );
00298                                 if( $viewWidth > 0 && $viewHeight > 0 ) {
00299                                         $aspect = $viewWidth / $viewHeight;
00300                                         $defaultHeight = $defaultWidth / $aspect;
00301                                 }
00302                         }
00303                 }
00304                 if( $this->reader->getAttribute('width') ) {
00305                         $width = $this->scaleSVGUnit( $this->reader->getAttribute('width'), $defaultWidth );
00306                         $this->metadata['originalWidth'] = $this->reader->getAttribute( 'width' );
00307                 }
00308                 if( $this->reader->getAttribute('height') ) {
00309                         $height = $this->scaleSVGUnit( $this->reader->getAttribute('height'), $defaultHeight );
00310                         $this->metadata['originalHeight'] = $this->reader->getAttribute( 'height' );
00311                 }
00312 
00313                 if( !isset( $width ) && !isset( $height ) ) {
00314                         $width = $defaultWidth;
00315                         $height = $width / $aspect;
00316                 } elseif( isset( $width ) && !isset( $height ) ) {
00317                         $height = $width / $aspect;
00318                 } elseif( isset( $height ) && !isset( $width ) ) {
00319                         $width = $height * $aspect;
00320                 }
00321 
00322                 if( $width > 0 && $height > 0 ) {
00323                         $this->metadata['width'] = intval( round( $width ) );
00324                         $this->metadata['height'] = intval( round( $height ) );
00325                 }
00326         }
00327 
00336         static function scaleSVGUnit( $length, $viewportSize=512 ) {
00337                 static $unitLength = array(
00338                         'px' => 1.0,
00339                         'pt' => 1.25,
00340                         'pc' => 15.0,
00341                         'mm' => 3.543307,
00342                         'cm' => 35.43307,
00343                         'in' => 90.0,
00344                         'em' => 16.0, // fake it?
00345                         'ex' => 12.0, // fake it?
00346                         ''   => 1.0, // "User units" pixels by default
00347                         );
00348                 $matches = array();
00349                 if( preg_match( '/^\s*(\d+(?:\.\d+)?)(em|ex|px|pt|pc|cm|mm|in|%|)\s*$/', $length, $matches ) ) {
00350                         $length = floatval( $matches[1] );
00351                         $unit = $matches[2];
00352                         if( $unit == '%' ) {
00353                                 return $length * 0.01 * $viewportSize;
00354                         } else {
00355                                 return $length * $unitLength[$unit];
00356                         }
00357                 } else {
00358                         // Assume pixels
00359                         return floatval( $length );
00360                 }
00361         }
00362 }