MediaWiki  REL1_19
SVGMetadataExtractor.php
Go to the documentation of this file.
00001 <?php
00028 class SVGMetadataExtractor {
00029         static function getMetadata( $filename ) {
00030                 $svg = new SVGReader( $filename );
00031                 return $svg->getMetadata();
00032         }
00033 }
00034 
00035 class SVGReader {
00036         const DEFAULT_WIDTH = 512;
00037         const DEFAULT_HEIGHT = 512;
00038         const NS_SVG = 'http://www.w3.org/2000/svg';
00039 
00040         private $reader = null;
00041         private $mDebug = false;
00042         private $metadata = Array();
00043 
00050         function __construct( $source ) {
00051                 global $wgSVGMetadataCutoff;
00052                 $this->reader = new XMLReader();
00053 
00054                 // Don't use $file->getSize() since file object passed to SVGHandler::getMetadata is bogus.
00055                 $size = filesize( $source );
00056                 if ( $size === false ) {
00057                         throw new MWException( "Error getting filesize of SVG." );
00058                 }
00059 
00060                 if ( $size > $wgSVGMetadataCutoff ) {
00061                         $this->debug( "SVG is $size bytes, which is bigger than $wgSVGMetadataCutoff. Truncating." );
00062                         $contents = file_get_contents( $source, false, null, -1, $wgSVGMetadataCutoff );
00063                         if ($contents === false) {
00064                                 throw new MWException( 'Error reading SVG file.' );
00065                         }
00066                         $this->reader->XML( $contents, null, LIBXML_NOERROR | LIBXML_NOWARNING );
00067                 } else {
00068                         $this->reader->open( $source, null, LIBXML_NOERROR | LIBXML_NOWARNING );
00069                 }
00070 
00071                 // Expand entities, since Adobe Illustrator uses them for xmlns
00072                 // attributes (bug 31719). Note that libxml2 has some protection
00073                 // against large recursive entity expansions so this is not as
00074                 // insecure as it might appear to be. However, it is still extremely
00075                 // insecure. It's necessary to wrap any read() calls with
00076                 // libxml_disable_entity_loader() to avoid arbitrary local file
00077                 // inclusion, or even arbitrary code execution if the expect
00078                 // extension is installed (bug 46859).
00079                 $oldDisable = libxml_disable_entity_loader( true );
00080                 $this->reader->setParserProperty( XMLReader::SUBST_ENTITIES, true );
00081 
00082                 $this->metadata['width'] = self::DEFAULT_WIDTH;
00083                 $this->metadata['height'] = self::DEFAULT_HEIGHT;
00084 
00085                 // Because we cut off the end of the svg making an invalid one. Complicated
00086                 // try catch thing to make sure warnings get restored. Seems like there should
00087                 // be a better way.
00088                 wfSuppressWarnings();
00089                 try {
00090                         $this->read();
00091                 } catch( Exception $e ) {
00092                         wfRestoreWarnings();
00093                         libxml_disable_entity_loader( $oldDisable );
00094                         throw $e;
00095                 }
00096                 wfRestoreWarnings();
00097                 libxml_disable_entity_loader( $oldDisable );
00098         }
00099 
00103         public function getMetadata() {
00104                 return $this->metadata;
00105         }
00106 
00110         protected function read() {
00111                 $keepReading = $this->reader->read();
00112 
00113                 /* Skip until first element */
00114                 while( $keepReading && $this->reader->nodeType != XmlReader::ELEMENT ) {
00115                         $keepReading = $this->reader->read();
00116                 }
00117 
00118                 if ( $this->reader->localName != 'svg' || $this->reader->namespaceURI != self::NS_SVG ) {
00119                         throw new MWException( "Expected <svg> tag, got ".
00120                                 $this->reader->localName . " in NS " . $this->reader->namespaceURI );
00121                 }
00122                 $this->debug( "<svg> tag is correct." );
00123                 $this->handleSVGAttribs();
00124 
00125                 $exitDepth =  $this->reader->depth;
00126                 $keepReading = $this->reader->read();
00127                 while ( $keepReading ) {
00128                         $tag = $this->reader->localName;
00129                         $type = $this->reader->nodeType;
00130                         $isSVG = ($this->reader->namespaceURI == self::NS_SVG);
00131 
00132                         $this->debug( "$tag" );
00133 
00134                         if ( $isSVG && $tag == 'svg' && $type == XmlReader::END_ELEMENT && $this->reader->depth <= $exitDepth ) {
00135                                 break;
00136                         } elseif ( $isSVG && $tag == 'title' ) {
00137                                 $this->readField( $tag, 'title' );
00138                         } elseif ( $isSVG && $tag == 'desc' ) {
00139                                 $this->readField( $tag, 'description' );
00140                         } elseif ( $isSVG && $tag == 'metadata' && $type == XmlReader::ELEMENT ) {
00141                                 $this->readXml( $tag, 'metadata' );
00142                         } elseif ( $tag !== '#text' ) {
00143                                 $this->debug( "Unhandled top-level XML tag $tag" );
00144 
00145                                 if ( !isset( $this->metadata['animated'] ) ) {
00146                                         // Recurse into children of current tag, looking for animation.
00147                                         $this->animateFilter( $tag );
00148                                 }
00149                         }
00150 
00151                         // Goto next element, which is sibling of current (Skip children).
00152                         $keepReading = $this->reader->next();
00153                 }
00154 
00155                 $this->reader->close();
00156 
00157                 return true;
00158         }
00159 
00166         private function readField( $name, $metafield=null ) {
00167                 $this->debug ( "Read field $metafield" );
00168                 if( !$metafield || $this->reader->nodeType != XmlReader::ELEMENT ) {
00169                         return;
00170                 }
00171                 $keepReading = $this->reader->read();
00172                 while( $keepReading ) {
00173                         if( $this->reader->localName == $name && $this->reader->namespaceURI == self::NS_SVG && $this->reader->nodeType == XmlReader::END_ELEMENT ) {
00174                                 break;
00175                         } elseif( $this->reader->nodeType == XmlReader::TEXT ){
00176                                 $this->metadata[$metafield] = trim( $this->reader->value );
00177                         }
00178                         $keepReading = $this->reader->read();
00179                 }
00180         }
00181 
00187         private function readXml( $metafield=null ) {
00188                 $this->debug ( "Read top level metadata" );
00189                 if( !$metafield || $this->reader->nodeType != XmlReader::ELEMENT ) {
00190                         return;
00191                 }
00192                 // TODO: find and store type of xml snippet. metadata['metadataType'] = "rdf"
00193                 if( method_exists( $this->reader, 'readInnerXML' ) ) {
00194                         $this->metadata[$metafield] = trim( $this->reader->readInnerXML() );
00195                 } else {
00196                         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)." );
00197                 }
00198                 $this->reader->next();
00199         }
00200 
00206         private function animateFilter( $name ) {
00207                 $this->debug ( "animate filter for tag $name" );
00208                 if( $this->reader->nodeType != XmlReader::ELEMENT ) {
00209                         return;
00210                 }
00211                 if ( $this->reader->isEmptyElement ) {
00212                         return;
00213                 }
00214                 $exitDepth =  $this->reader->depth;
00215                 $keepReading = $this->reader->read();
00216                 while( $keepReading ) {
00217                         if( $this->reader->localName == $name && $this->reader->depth <= $exitDepth
00218                                 && $this->reader->nodeType == XmlReader::END_ELEMENT ) {
00219                                 break;
00220                         } elseif ( $this->reader->namespaceURI == self::NS_SVG && $this->reader->nodeType == XmlReader::ELEMENT ) {
00221                                 switch( $this->reader->localName ) {
00222                                         case 'animate':
00223                                         case 'set':
00224                                         case 'animateMotion':
00225                                         case 'animateColor':
00226                                         case 'animateTransform':
00227                                                 $this->debug( "HOUSTON WE HAVE ANIMATION" );
00228                                                 $this->metadata['animated'] = true;
00229                                                 break;
00230                                 }
00231                         }
00232                         $keepReading = $this->reader->read();
00233                 }
00234         }
00235 
00236         private function throwXmlError( $err ) {
00237                 $this->debug( "FAILURE: $err" );
00238                 wfDebug( "SVGReader XML error: $err\n" );
00239         }
00240 
00241         private function debug( $data ) {
00242                 if( $this->mDebug ) {
00243                         wfDebug( "SVGReader: $data\n" );
00244                 }
00245         }
00246 
00247         private function warn( $data ) {
00248                 wfDebug( "SVGReader: $data\n" );
00249         }
00250 
00251         private function notice( $data ) {
00252                 wfDebug( "SVGReader WARN: $data\n" );
00253         }
00254 
00260         private function handleSVGAttribs( ) {
00261                 $defaultWidth = self::DEFAULT_WIDTH;
00262                 $defaultHeight = self::DEFAULT_HEIGHT;
00263                 $aspect = 1.0;
00264                 $width = null;
00265                 $height = null;
00266 
00267                 if( $this->reader->getAttribute('viewBox') ) {
00268                         // min-x min-y width height
00269                         $viewBox = preg_split( '/\s+/', trim( $this->reader->getAttribute('viewBox') ) );
00270                         if( count( $viewBox ) == 4 ) {
00271                                 $viewWidth = $this->scaleSVGUnit( $viewBox[2] );
00272                                 $viewHeight = $this->scaleSVGUnit( $viewBox[3] );
00273                                 if( $viewWidth > 0 && $viewHeight > 0 ) {
00274                                         $aspect = $viewWidth / $viewHeight;
00275                                         $defaultHeight = $defaultWidth / $aspect;
00276                                 }
00277                         }
00278                 }
00279                 if( $this->reader->getAttribute('width') ) {
00280                         $width = $this->scaleSVGUnit( $this->reader->getAttribute('width'), $defaultWidth );
00281                 }
00282                 if( $this->reader->getAttribute('height') ) {
00283                         $height = $this->scaleSVGUnit( $this->reader->getAttribute('height'), $defaultHeight );
00284                 }
00285 
00286                 if( !isset( $width ) && !isset( $height ) ) {
00287                         $width = $defaultWidth;
00288                         $height = $width / $aspect;
00289                 } elseif( isset( $width ) && !isset( $height ) ) {
00290                         $height = $width / $aspect;
00291                 } elseif( isset( $height ) && !isset( $width ) ) {
00292                         $width = $height * $aspect;
00293                 }
00294 
00295                 if( $width > 0 && $height > 0 ) {
00296                         $this->metadata['width'] = intval( round( $width ) );
00297                         $this->metadata['height'] = intval( round( $height ) );
00298                 }
00299         }
00300 
00309         static function scaleSVGUnit( $length, $viewportSize=512 ) {
00310                 static $unitLength = array(
00311                         'px' => 1.0,
00312                         'pt' => 1.25,
00313                         'pc' => 15.0,
00314                         'mm' => 3.543307,
00315                         'cm' => 35.43307,
00316                         'in' => 90.0,
00317                         'em' => 16.0, // fake it?
00318                         'ex' => 12.0, // fake it?
00319                         ''   => 1.0, // "User units" pixels by default
00320                         );
00321                 $matches = array();
00322                 if( preg_match( '/^\s*(\d+(?:\.\d+)?)(em|ex|px|pt|pc|cm|mm|in|%|)\s*$/', $length, $matches ) ) {
00323                         $length = floatval( $matches[1] );
00324                         $unit = $matches[2];
00325                         if( $unit == '%' ) {
00326                                 return $length * 0.01 * $viewportSize;
00327                         } else {
00328                                 return $length * $unitLength[$unit];
00329                         }
00330                 } else {
00331                         // Assume pixels
00332                         return floatval( $length );
00333                 }
00334         }
00335 }