MediaWiki  master
XMP.php
Go to the documentation of this file.
00001 <?php
00049 class XMPReader {
00050 
00051         private $curItem = array();        // array to hold the current element (and previous element, and so on)
00052         private $ancestorStruct = false;   // the structure name when processing nested structures.
00053         private $charContent = false;      // temporary holder for character data that appears in xmp doc.
00054         private $mode = array();           // stores the state the xmpreader is in (see MODE_FOO constants)
00055         private $results = array();        // array to hold results
00056         private $processingArray = false;  // if we're doing a seq or bag.
00057         private $itemLang = false;         // used for lang alts only
00058 
00059         private $xmlParser;
00060         private $charset = false;
00061         private $extendedXMPOffset = 0;
00062 
00063         protected $items;
00064 
00074         const MODE_INITIAL = 0;
00075         const MODE_IGNORE  = 1;
00076         const MODE_LI      = 2;
00077         const MODE_LI_LANG = 3;
00078         const MODE_QDESC   = 4;
00079 
00080         // The following MODE constants are also used in the
00081         // $items array to denote what type of property the item is.
00082         const MODE_SIMPLE    = 10;
00083         const MODE_STRUCT    = 11; // structure (associative array)
00084         const MODE_SEQ       = 12; // ordered list
00085         const MODE_BAG       = 13; // unordered list
00086         const MODE_LANG      = 14;
00087         const MODE_ALT       = 15; // non-language alt. Currently not implemented, and not needed atm.
00088         const MODE_BAGSTRUCT = 16; // A BAG of Structs.
00089 
00090         const NS_RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
00091         const NS_XML = 'http://www.w3.org/XML/1998/namespace';
00092 
00093 
00099         function __construct() {
00100 
00101                 if ( !function_exists( 'xml_parser_create_ns' ) ) {
00102                         // this should already be checked by this point
00103                         throw new MWException( 'XMP support requires XML Parser' );
00104                 }
00105 
00106                 $this->items = XMPInfo::getItems();
00107 
00108                 $this->resetXMLParser();
00109 
00110         }
00115         private function resetXMLParser() {
00116 
00117                 if ($this->xmlParser) {
00118                         //is this needed?
00119                         xml_parser_free( $this->xmlParser );
00120                 }
00121 
00122                 $this->xmlParser = xml_parser_create_ns( 'UTF-8', ' ' );
00123                 xml_parser_set_option( $this->xmlParser, XML_OPTION_CASE_FOLDING, 0 );
00124                 xml_parser_set_option( $this->xmlParser, XML_OPTION_SKIP_WHITE, 1 );
00125 
00126                 xml_set_element_handler( $this->xmlParser,
00127                         array( $this, 'startElement' ),
00128                         array( $this, 'endElement' ) );
00129 
00130                 xml_set_character_data_handler( $this->xmlParser, array( $this, 'char' ) );
00131         }
00132 
00137         function __destruct() {
00138                 // not sure if this is needed.
00139                 xml_parser_free( $this->xmlParser );
00140         }
00141 
00148         public function getResults() {
00149                 // xmp-special is for metadata that affects how stuff
00150                 // is extracted. For example xmpNote:HasExtendedXMP.
00151 
00152                 // It is also used to handle photoshop:AuthorsPosition
00153                 // which is weird and really part of another property,
00154                 // see 2:85 in IPTC. See also pg 21 of IPTC4XMP standard.
00155                 // The location fields also use it.
00156 
00157                 $data = $this->results;
00158 
00159                 wfRunHooks('XMPGetResults', Array(&$data));
00160 
00161                 if ( isset( $data['xmp-special']['AuthorsPosition'] )
00162                         && is_string( $data['xmp-special']['AuthorsPosition'] )
00163                         && isset( $data['xmp-general']['Artist'][0] )
00164                 ) {
00165                         // Note, if there is more than one creator,
00166                         // this only applies to first. This also will
00167                         // only apply to the dc:Creator prop, not the
00168                         // exif:Artist prop.
00169 
00170                         $data['xmp-general']['Artist'][0] =
00171                                 $data['xmp-special']['AuthorsPosition'] . ', '
00172                                 . $data['xmp-general']['Artist'][0];
00173                 }
00174 
00175                 // Go through the LocationShown and LocationCreated
00176                 // changing it to the non-hierarchal form used by
00177                 // the other location fields.
00178 
00179                 if ( isset( $data['xmp-special']['LocationShown'][0] )
00180                         && is_array( $data['xmp-special']['LocationShown'][0] )
00181                 ) {
00182                         // the is_array is just paranoia. It should always
00183                         // be an array.
00184                         foreach( $data['xmp-special']['LocationShown'] as $loc ) {
00185                                 if ( !is_array( $loc ) ) {
00186                                         // To avoid copying over the _type meta-fields.
00187                                         continue;
00188                                 }
00189                                 foreach( $loc as $field => $val ) {
00190                                         $data['xmp-general'][$field . 'Dest'][] = $val;
00191                                 }
00192                         }
00193                 }
00194                 if ( isset( $data['xmp-special']['LocationCreated'][0] )
00195                         && is_array( $data['xmp-special']['LocationCreated'][0] )
00196                 ) {
00197                         // the is_array is just paranoia. It should always
00198                         // be an array.
00199                         foreach( $data['xmp-special']['LocationCreated'] as $loc ) {
00200                                 if ( !is_array( $loc ) ) {
00201                                         // To avoid copying over the _type meta-fields.
00202                                         continue;
00203                                 }
00204                                 foreach(  $loc as $field => $val ) {
00205                                         $data['xmp-general'][$field . 'Created'][] = $val;
00206                                 }
00207                         }
00208                 }
00209 
00210 
00211                 // We don't want to return the special values, since they're
00212                 // special and not info to be stored about the file.
00213                 unset( $data['xmp-special'] );
00214 
00215                 // Convert GPSAltitude to negative if below sea level.
00216                 if ( isset( $data['xmp-exif']['GPSAltitudeRef'] )
00217                         && isset( $data['xmp-exif']['GPSAltitude'] )
00218                 ) {
00219 
00220                         // Must convert to a real before multiplying by -1
00221                         // XMPValidate guarantees there will always be a '/' in this value.
00222                         list( $nom, $denom ) = explode( '/', $data['xmp-exif']['GPSAltitude'] );
00223                         $data['xmp-exif']['GPSAltitude'] = $nom / $denom;
00224 
00225                         if ( $data['xmp-exif']['GPSAltitudeRef'] == '1' ) {
00226                                 $data['xmp-exif']['GPSAltitude'] *= -1;
00227                         }
00228                         unset( $data['xmp-exif']['GPSAltitudeRef'] );
00229                 }
00230 
00231                 return $data;
00232         }
00233 
00247         public function parse( $content, $allOfIt = true, $reset = false ) {
00248                 if ( $reset ) {
00249                         $this->resetXMLParser();
00250                 }
00251                 try {
00252 
00253                         // detect encoding by looking for BOM which is supposed to be in processing instruction.
00254                         // see page 12 of http://www.adobe.com/devnet/xmp/pdfs/XMPSpecificationPart3.pdf
00255                         if ( !$this->charset ) {
00256                                 $bom = array();
00257                                 if ( preg_match( '/\xEF\xBB\xBF|\xFE\xFF|\x00\x00\xFE\xFF|\xFF\xFE\x00\x00|\xFF\xFE/',
00258                                          $content, $bom )
00259                                 ) {
00260                                         switch ( $bom[0] ) {
00261                                                 case "\xFE\xFF":
00262                                                         $this->charset = 'UTF-16BE';
00263                                                         break;
00264                                                 case "\xFF\xFE":
00265                                                         $this->charset = 'UTF-16LE';
00266                                                         break;
00267                                                 case "\x00\x00\xFE\xFF":
00268                                                         $this->charset = 'UTF-32BE';
00269                                                         break;
00270                                                 case "\xFF\xFE\x00\x00":
00271                                                         $this->charset = 'UTF-32LE';
00272                                                         break;
00273                                                 case "\xEF\xBB\xBF":
00274                                                         $this->charset = 'UTF-8';
00275                                                         break;
00276                                                 default:
00277                                                         //this should be impossible to get to
00278                                                         throw new MWException("Invalid BOM");
00279                                                         break;
00280 
00281                                         }
00282 
00283                                 } else {
00284                                         // standard specifically says, if no bom assume utf-8
00285                                         $this->charset = 'UTF-8';
00286                                 }
00287                         }
00288                         if ( $this->charset !== 'UTF-8' ) {
00289                                 //don't convert if already utf-8
00290                                 wfSuppressWarnings();
00291                                 $content = iconv( $this->charset, 'UTF-8//IGNORE', $content );
00292                                 wfRestoreWarnings();
00293                         }
00294 
00295                         $ok = xml_parse( $this->xmlParser, $content, $allOfIt );
00296                         if ( !$ok ) {
00297                                 $error = xml_error_string( xml_get_error_code( $this->xmlParser ) );
00298                                 $where = 'line: ' . xml_get_current_line_number( $this->xmlParser )
00299                                         . ' column: ' . xml_get_current_column_number( $this->xmlParser )
00300                                         . ' byte offset: ' . xml_get_current_byte_index( $this->xmlParser );
00301 
00302                                 wfDebugLog( 'XMP', "XMPReader::parse : Error reading XMP content: $error ($where)" );
00303                                 $this->results = array(); // blank if error.
00304                                 return false;
00305                         }
00306                 } catch ( MWException $e ) {
00307                         wfDebugLog( 'XMP', 'XMP parse error: ' . $e );
00308                         $this->results = array();
00309                         return false;
00310                 }
00311                 return true;
00312         }
00313 
00321         public function parseExtended( $content ) {
00322                 // @todo FIXME: This is untested. Hard to find example files
00323                 // or programs that make such files..
00324                 $guid = substr( $content, 0, 32 );
00325                 if ( !isset( $this->results['xmp-special']['HasExtendedXMP'] )
00326                         || $this->results['xmp-special']['HasExtendedXMP'] !== $guid ) {
00327                         wfDebugLog('XMP', __METHOD__ . " Ignoring XMPExtended block due to wrong guid (guid= '$guid' )");
00328                         return false;
00329                 }
00330                 $len  = unpack( 'Nlength/Noffset', substr( $content, 32, 8 ) );
00331 
00332                 if (!$len || $len['length'] < 4 || $len['offset'] < 0 || $len['offset'] > $len['length'] ) {
00333                         wfDebugLog('XMP', __METHOD__ . 'Error reading extended XMP block, invalid length or offset.');
00334                         return false;
00335                 }
00336 
00337 
00338                 // we're not very robust here. we should accept it in the wrong order. To quote
00339                 // the xmp standard:
00340                 // "A JPEG writer should write the ExtendedXMP marker segments in order, immediately following the
00341                 // StandardXMP. However, the JPEG standard does not require preservation of marker segment order. A
00342                 // robust JPEG reader should tolerate the marker segments in any order."
00343                 //
00344                 // otoh the probability that an image will have more than 128k of metadata is rather low...
00345                 // so the probability that it will have > 128k, and be in the wrong order is very low...
00346 
00347                 if ( $len['offset'] !== $this->extendedXMPOffset ) {
00348                         wfDebugLog('XMP', __METHOD__ . 'Ignoring XMPExtended block due to wrong order. (Offset was '
00349                                 . $len['offset'] . ' but expected ' . $this->extendedXMPOffset . ')');
00350                         return false;
00351                 }
00352 
00353                 if ( $len['offset'] === 0 ) {
00354                         // if we're starting the extended block, we've probably already
00355                         // done the XMPStandard block, so reset.
00356                         $this->resetXMLParser();
00357                 }
00358 
00359                 $this->extendedXMPOffset += $len['length'];
00360 
00361                 $actualContent = substr( $content, 40 );
00362 
00363                 if ( $this->extendedXMPOffset === strlen( $actualContent ) ) {
00364                         $atEnd = true;
00365                 } else {
00366                         $atEnd = false;
00367                 }
00368 
00369                 wfDebugLog('XMP', __METHOD__ . 'Parsing a XMPExtended block');
00370                 return $this->parse( $actualContent, $atEnd );
00371         }
00372 
00389         function char( $parser, $data ) {
00390 
00391                 $data = trim( $data );
00392                 if ( trim( $data ) === "" ) {
00393                         return;
00394                 }
00395 
00396                 if ( !isset( $this->mode[0] ) ) {
00397                         throw new MWException( 'Unexpected character data before first rdf:Description element' );
00398                 }
00399 
00400                 if ( $this->mode[0] === self::MODE_IGNORE ) return;
00401 
00402                 if ( $this->mode[0] !== self::MODE_SIMPLE
00403                         && $this->mode[0] !== self::MODE_QDESC
00404                 ) {
00405                         throw new MWException( 'character data where not expected. (mode ' . $this->mode[0] . ')' );
00406                 }
00407 
00408                 // to check, how does this handle w.s.
00409                 if ( $this->charContent === false ) {
00410                         $this->charContent = $data;
00411                 } else {
00412                         $this->charContent .= $data;
00413                 }
00414 
00415         }
00416 
00423         private function endElementModeIgnore ( $elm ) {
00424 
00425                 if ( $this->curItem[0] === $elm ) {
00426                         array_shift( $this->curItem );
00427                         array_shift( $this->mode );
00428                 }
00429                 return;
00430 
00431         }
00432 
00448         private function endElementModeSimple ( $elm ) {
00449                 if ( $this->charContent !== false ) {
00450                         if ( $this->processingArray ) {
00451                                 // if we're processing an array, use the original element
00452                                 // name instead of rdf:li.
00453                                 list( $ns, $tag ) = explode( ' ', $this->curItem[0], 2 );
00454                         } else {
00455                                 list( $ns, $tag ) = explode( ' ', $elm, 2 );
00456                         }
00457                         $this->saveValue( $ns, $tag, $this->charContent );
00458 
00459                         $this->charContent = false; // reset
00460                 }
00461                 array_shift( $this->curItem );
00462                 array_shift( $this->mode );
00463 
00464         }
00465 
00484         private function endElementNested( $elm ) {
00485 
00486                 /* cur item must be the same as $elm, unless if in MODE_STRUCT
00487                    in which case it could also be rdf:Description */
00488                 if ( $this->curItem[0] !== $elm
00489                         && !( $elm === self::NS_RDF . ' Description'
00490                                 && $this->mode[0] === self::MODE_STRUCT )
00491                  ) {
00492                         throw new MWException( "nesting mismatch. got a </$elm> but expected a </" . $this->curItem[0] . '>' );
00493                 }
00494 
00495                 // Validate structures.
00496                 list( $ns, $tag ) = explode( ' ', $elm, 2 );
00497                 if ( isset( $this->items[$ns][$tag]['validate'] ) ) {
00498 
00499                         $info =& $this->items[$ns][$tag];
00500                         $finalName = isset( $info['map_name'] )
00501                                 ? $info['map_name'] : $tag;
00502 
00503                         $validate = is_array( $info['validate'] ) ? $info['validate']
00504                                 : array( 'XMPValidate', $info['validate'] );
00505 
00506                         if ( !isset( $this->results['xmp-' . $info['map_group']][$finalName] ) ) {
00507                                 // This can happen if all the members of the struct failed validation.
00508                                 wfDebugLog( 'XMP', __METHOD__ . " <$ns:$tag> has no valid members." );
00509 
00510                         } elseif ( is_callable( $validate ) ) {
00511                                 $val =& $this->results['xmp-' . $info['map_group']][$finalName];
00512                                 call_user_func_array( $validate, array( $info, &$val, false ) );
00513                                 if ( is_null( $val ) ) {
00514                                         // the idea being the validation function will unset the variable if
00515                                         // its invalid.
00516                                         wfDebugLog( 'XMP', __METHOD__ . " <$ns:$tag> failed validation." );
00517                                         unset( $this->results['xmp-' . $info['map_group']][$finalName] );
00518                                 }
00519                         } else {
00520                                 wfDebugLog( 'XMP', __METHOD__ . " Validation function for $finalName ("
00521                                         . $validate[0] . '::' . $validate[1] . '()) is not callable.' );
00522                         }
00523                 }
00524 
00525                 array_shift( $this->curItem );
00526                 array_shift( $this->mode );
00527                 $this->ancestorStruct = false;
00528                 $this->processingArray = false;
00529                 $this->itemLang = false;
00530         }
00531 
00551         private function endElementModeLi( $elm ) {
00552 
00553                 list( $ns, $tag ) = explode( ' ', $this->curItem[0], 2 );
00554                 $info = $this->items[$ns][$tag];
00555                 $finalName = isset( $info['map_name'] )
00556                         ? $info['map_name'] : $tag;
00557 
00558                 array_shift( $this->mode );
00559 
00560                 if ( !isset( $this->results['xmp-' . $info['map_group']][$finalName] ) ) {
00561                         wfDebugLog( 'XMP', __METHOD__ . " Empty compund element $finalName." );
00562                         return;
00563                 }
00564 
00565                 if ( $elm === self::NS_RDF . ' Seq' ) {
00566                         $this->results['xmp-' . $info['map_group']][$finalName]['_type'] = 'ol';
00567                 } elseif ( $elm === self::NS_RDF . ' Bag' ) {
00568                         $this->results['xmp-' . $info['map_group']][$finalName]['_type'] = 'ul';
00569                 } elseif ( $elm === self::NS_RDF . ' Alt' ) {
00570                         // extra if needed as you could theoretically have a non-language alt.
00571                         if ( $info['mode'] === self::MODE_LANG ) {
00572                                 $this->results['xmp-' . $info['map_group']][$finalName]['_type'] = 'lang';
00573                         }
00574 
00575                 } else {
00576                         throw new MWException( __METHOD__ . " expected </rdf:seq> or </rdf:bag> but instead got $elm." );
00577                 }
00578         }
00579 
00590         private function endElementModeQDesc( $elm ) {
00591 
00592                 if ( $elm === self::NS_RDF . ' value' ) {
00593                         list( $ns, $tag ) = explode( ' ', $this->curItem[0], 2 );
00594                         $this->saveValue( $ns, $tag, $this->charContent );
00595                         return;
00596                 } else {
00597                         array_shift( $this->mode );
00598                         array_shift( $this->curItem );
00599                 }
00600 
00601 
00602         }
00603 
00617         function endElement( $parser, $elm ) {
00618                 if ( $elm === ( self::NS_RDF . ' RDF' )
00619                         || $elm === 'adobe:ns:meta/ xmpmeta'
00620                         || $elm === 'adobe:ns:meta/ xapmeta' )
00621                 {
00622                         // ignore these.
00623                         return;
00624                 }
00625 
00626                 if ( $elm === self::NS_RDF . ' type' ) {
00627                         // these aren't really supported properly yet.
00628                         // However, it appears they almost never used.
00629                         wfDebugLog( 'XMP', __METHOD__ . ' encountered <rdf:type>' );
00630                 }
00631 
00632                 if ( strpos( $elm, ' ' ) === false ) {
00633                         // This probably shouldn't happen.
00634                         // However, there is a bug in an adobe product
00635                         // that forgets the namespace on some things.
00636                         // (Luckily they are unimportant things).
00637                         wfDebugLog( 'XMP', __METHOD__ . " Encountered </$elm> which has no namespace. Skipping." );
00638                         return;
00639                 }
00640 
00641                 if ( count( $this->mode[0] ) === 0 ) {
00642                         // This should never ever happen and means
00643                         // there is a pretty major bug in this class.
00644                         throw new MWException( 'Encountered end element with no mode' );
00645                 }
00646 
00647                 if ( count( $this->curItem ) == 0 && $this->mode[0] !== self::MODE_INITIAL ) {
00648                         // just to be paranoid. Should always have a curItem, except for initially
00649                         // (aka during MODE_INITAL).
00650                         throw new MWException( "Hit end element </$elm> but no curItem" );
00651                 }
00652 
00653                 switch( $this->mode[0] ) {
00654                         case self::MODE_IGNORE:
00655                                 $this->endElementModeIgnore( $elm );
00656                                 break;
00657                         case self::MODE_SIMPLE:
00658                                 $this->endElementModeSimple( $elm );
00659                                 break;
00660                         case self::MODE_STRUCT:
00661                         case self::MODE_SEQ:
00662                         case self::MODE_BAG:
00663                         case self::MODE_LANG:
00664                         case self::MODE_BAGSTRUCT:
00665                                 $this->endElementNested( $elm );
00666                                 break;
00667                         case self::MODE_INITIAL:
00668                                 if ( $elm === self::NS_RDF . ' Description' ) {
00669                                         array_shift( $this->mode );
00670                                 } else {
00671                                         throw new MWException( 'Element ended unexpectedly while in MODE_INITIAL' );
00672                                 }
00673                                 break;
00674                         case self::MODE_LI:
00675                         case self::MODE_LI_LANG:
00676                                 $this->endElementModeLi( $elm );
00677                                 break;
00678                         case self::MODE_QDESC:
00679                                 $this->endElementModeQDesc( $elm );
00680                                 break;
00681                         default:
00682                                 wfDebugLog( 'XMP', __METHOD__ . " no mode (elm = $elm)" );
00683                                 break;
00684                 }
00685         }
00686 
00698         private function startElementModeIgnore( $elm ) {
00699                 if ( $elm === $this->curItem[0] ) {
00700                         array_unshift( $this->curItem, $elm );
00701                         array_unshift( $this->mode, self::MODE_IGNORE );
00702                 }
00703         }
00704 
00712         private function startElementModeBag( $elm ) {
00713                 if ( $elm === self::NS_RDF . ' Bag' ) {
00714                         array_unshift( $this->mode, self::MODE_LI );
00715                 } else {
00716                         throw new MWException( "Expected <rdf:Bag> but got $elm." );
00717                 }
00718 
00719         }
00720 
00728         private function startElementModeSeq( $elm ) {
00729                 if ( $elm === self::NS_RDF . ' Seq' ) {
00730                         array_unshift( $this->mode, self::MODE_LI );
00731                 } elseif ( $elm === self::NS_RDF . ' Bag' ) {
00732                         # bug 27105
00733                         wfDebugLog( 'XMP', __METHOD__ . ' Expected an rdf:Seq, but got an rdf:Bag. Pretending'
00734                                 . ' it is a Seq, since some buggy software is known to screw this up.' );
00735                         array_unshift( $this->mode, self::MODE_LI );
00736                 } else {
00737                         throw new MWException( "Expected <rdf:Seq> but got $elm." );
00738                 }
00739 
00740         }
00741 
00756         private function startElementModeLang( $elm ) {
00757                 if ( $elm === self::NS_RDF . ' Alt' ) {
00758                         array_unshift( $this->mode, self::MODE_LI_LANG );
00759                 } else {
00760                         throw new MWException( "Expected <rdf:Seq> but got $elm." );
00761                 }
00762 
00763         }
00764 
00783         private function startElementModeSimple( $elm, $attribs ) {
00784                 if ( $elm === self::NS_RDF . ' Description' ) {
00785                         // If this value has qualifiers
00786                         array_unshift( $this->mode, self::MODE_QDESC );
00787                         array_unshift( $this->curItem, $this->curItem[0] );
00788 
00789                         if ( isset( $attribs[self::NS_RDF . ' value'] ) ) {
00790                                 list( $ns, $tag ) = explode( ' ', $this->curItem[0], 2 );
00791                                 $this->saveValue( $ns, $tag, $attribs[self::NS_RDF . ' value'] );
00792                         }
00793                 } elseif ( $elm === self::NS_RDF . ' value' ) {
00794                         // This should not be here.
00795                         throw new MWException( __METHOD__ . ' Encountered <rdf:value> where it was unexpected.' );
00796 
00797                 } else {
00798                         // something else we don't recognize, like a qualifier maybe.
00799                         wfDebugLog( 'XMP', __METHOD__ . " Encountered element <$elm> where only expecting character data as value of " . $this->curItem[0] );
00800                         array_unshift( $this->mode, self::MODE_IGNORE );
00801                         array_unshift( $this->curItem, $elm );
00802 
00803                 }
00804 
00805         }
00806 
00821         private function startElementModeQDesc( $elm ) {
00822                 if ( $elm === self::NS_RDF . ' value' ) {
00823                         return; // do nothing
00824                 } else {
00825                         // otherwise its a qualifier, which we ignore
00826                         array_unshift( $this->mode, self::MODE_IGNORE );
00827                         array_unshift( $this->curItem, $elm );
00828                 }
00829         }
00830 
00843         private function startElementModeInitial( $ns, $tag, $attribs ) {
00844                 if ( $ns !== self::NS_RDF ) {
00845 
00846                         if ( isset( $this->items[$ns][$tag] ) ) {
00847                                 if ( isset( $this->items[$ns][$tag]['structPart'] ) ) {
00848                                         // If this element is supposed to appear only as
00849                                         // a child of a structure, but appears here (not as
00850                                         // a child of a struct), then something weird is
00851                                         // happening, so ignore this element and its children.
00852 
00853                                         wfDebugLog( 'XMP', "Encountered <$ns:$tag> outside"
00854                                                 . " of its expected parent. Ignoring." );
00855 
00856                                         array_unshift( $this->mode, self::MODE_IGNORE );
00857                                         array_unshift( $this->curItem, $ns . ' ' . $tag );
00858                                         return;
00859                                 }
00860                                 $mode = $this->items[$ns][$tag]['mode'];
00861                                 array_unshift( $this->mode, $mode );
00862                                 array_unshift( $this->curItem, $ns . ' ' . $tag );
00863                                 if ( $mode === self::MODE_STRUCT ) {
00864                                         $this->ancestorStruct = isset( $this->items[$ns][$tag]['map_name'] )
00865                                                 ? $this->items[$ns][$tag]['map_name'] : $tag;
00866                                 }
00867                                 if ( $this->charContent !== false ) {
00868                                         // Something weird.
00869                                         // Should not happen in valid XMP.
00870                                         throw new MWException( 'tag nested in non-whitespace characters.' );
00871                                 }
00872                         } else {
00873                                 // This element is not on our list of allowed elements so ignore.
00874                                 wfDebugLog( 'XMP', __METHOD__ . " Ignoring unrecognized element <$ns:$tag>." );
00875                                 array_unshift( $this->mode, self::MODE_IGNORE );
00876                                 array_unshift( $this->curItem, $ns . ' ' . $tag );
00877                                 return;
00878                         }
00879 
00880                 }
00881                 // process attributes
00882                 $this->doAttribs( $attribs );
00883         }
00884 
00904         private function startElementModeStruct( $ns, $tag, $attribs ) {
00905                 if ( $ns !== self::NS_RDF ) {
00906 
00907                         if ( isset( $this->items[$ns][$tag] ) ) {
00908                                 if ( isset( $this->items[$ns][$this->ancestorStruct]['children'] )
00909                                         && !isset( $this->items[$ns][$this->ancestorStruct]['children'][$tag] ) )
00910                                 {
00911                                         // This assumes that we don't have inter-namespace nesting
00912                                         // which we don't in all the properties we're interested in.
00913                                         throw new MWException( " <$tag> appeared nested in <" . $this->ancestorStruct
00914                                                 . "> where it is not allowed." );
00915                                 }
00916                                 array_unshift( $this->mode, $this->items[$ns][$tag]['mode'] );
00917                                 array_unshift( $this->curItem, $ns . ' ' . $tag );
00918                                 if ( $this->charContent !== false ) {
00919                                         // Something weird.
00920                                         // Should not happen in valid XMP.
00921                                         throw new MWException( "tag <$tag> nested in non-whitespace characters (" . $this->charContent . ")." );
00922                                 }
00923                         } else {
00924                                 array_unshift( $this->mode, self::MODE_IGNORE );
00925                                 array_unshift( $this->curItem, $elm );
00926                                 return;
00927                         }
00928 
00929                 }
00930 
00931                 if ( $ns === self::NS_RDF && $tag === 'Description' ) {
00932                         $this->doAttribs( $attribs );
00933                         array_unshift( $this->mode, self::MODE_STRUCT );
00934                         array_unshift( $this->curItem, $this->curItem[0] );
00935                 }
00936         }
00937 
00951         private function startElementModeLi( $elm, $attribs ) {
00952                 if ( ( $elm ) !== self::NS_RDF . ' li' ) {
00953                         throw new MWException( "<rdf:li> expected but got $elm." );
00954                 }
00955 
00956                 if ( !isset( $this->mode[1] ) ) {
00957                         // This should never ever ever happen. Checking for it
00958                         // to be paranoid.
00959                         throw new MWException( 'In mode Li, but no 2xPrevious mode!' );
00960                 }
00961 
00962                 if ( $this->mode[1] === self::MODE_BAGSTRUCT ) {
00963                         // This list item contains a compound (STRUCT) value.
00964                         array_unshift( $this->mode, self::MODE_STRUCT );
00965                         array_unshift( $this->curItem, $elm );
00966                         $this->processingArray = true;
00967 
00968                         if ( !isset( $this->curItem[1] ) ) {
00969                                 // be paranoid.
00970                                 throw new MWException( 'Can not find parent of BAGSTRUCT.' );
00971                         }
00972                         list( $curNS, $curTag ) = explode( ' ', $this->curItem[1] );
00973                         $this->ancestorStruct = isset( $this->items[$curNS][$curTag]['map_name'] )
00974                                 ? $this->items[$curNS][$curTag]['map_name'] : $curTag;
00975 
00976                         $this->doAttribs( $attribs );
00977 
00978                 } else {
00979                         // Normal BAG or SEQ containing simple values.
00980                         array_unshift( $this->mode, self::MODE_SIMPLE );
00981                         // need to add curItem[0] on again since one is for the specific item
00982                         // and one is for the entire group.
00983                         array_unshift( $this->curItem, $this->curItem[0] );
00984                         $this->processingArray = true;
00985                 }
00986 
00987         }
00988 
01003         private function startElementModeLiLang( $elm, $attribs ) {
01004                 if ( $elm !== self::NS_RDF . ' li' ) {
01005                         throw new MWException( __METHOD__ . " <rdf:li> expected but got $elm." );
01006                 }
01007                 if ( !isset( $attribs[ self::NS_XML . ' lang'] )
01008                         || !preg_match( '/^[-A-Za-z0-9]{2,}$/D', $attribs[ self::NS_XML . ' lang' ] ) )
01009                 {
01010                         throw new MWException( __METHOD__
01011                                 . " <rdf:li> did not contain, or has invalid xml:lang attribute in lang alternative" );
01012                 }
01013 
01014                 // Lang is case-insensitive.
01015                 $this->itemLang = strtolower( $attribs[ self::NS_XML . ' lang' ] );
01016 
01017                 // need to add curItem[0] on again since one is for the specific item
01018                 // and one is for the entire group.
01019                 array_unshift( $this->curItem, $this->curItem[0] );
01020                 array_unshift( $this->mode, self::MODE_SIMPLE );
01021                 $this->processingArray = true;
01022         }
01023 
01034         function startElement( $parser, $elm, $attribs ) {
01035 
01036                 if ( $elm === self::NS_RDF . ' RDF'
01037                         || $elm === 'adobe:ns:meta/ xmpmeta'
01038                         || $elm === 'adobe:ns:meta/ xapmeta')
01039                 {
01040                         /* ignore. */
01041                         return;
01042                 } elseif ( $elm === self::NS_RDF . ' Description' ) {
01043                         if ( count( $this->mode ) === 0 ) {
01044                                 // outer rdf:desc
01045                                 array_unshift( $this->mode, self::MODE_INITIAL );
01046                         }
01047                 } elseif ( $elm === self::NS_RDF . ' type' ) {
01048                         // This doesn't support rdf:type properly.
01049                         // In practise I have yet to see a file that
01050                         // uses this element, however it is mentioned
01051                         // on page 25 of part 1 of the xmp standard.
01052                         //
01053                         // also it seems as if exiv2 and exiftool do not support
01054                         // this either (That or I misunderstand the standard)
01055                         wfDebugLog( 'XMP', __METHOD__ . ' Encountered <rdf:type> which isn\'t currently supported' );
01056                 }
01057 
01058                 if ( strpos( $elm, ' ' ) === false ) {
01059                         // This probably shouldn't happen.
01060                         wfDebugLog( 'XMP', __METHOD__ . " Encountered <$elm> which has no namespace. Skipping." );
01061                         return;
01062                 }
01063 
01064                 list( $ns, $tag ) = explode( ' ', $elm, 2 );
01065 
01066                 if ( count( $this->mode ) === 0 ) {
01067                         // This should not happen.
01068                         throw new MWException('Error extracting XMP, '
01069                                 . "encountered <$elm> with no mode" );
01070                 }
01071 
01072                 switch( $this->mode[0] ) {
01073                         case self::MODE_IGNORE:
01074                                 $this->startElementModeIgnore( $elm );
01075                                 break;
01076                         case self::MODE_SIMPLE:
01077                                 $this->startElementModeSimple( $elm, $attribs );
01078                                 break;
01079                         case self::MODE_INITIAL:
01080                                 $this->startElementModeInitial( $ns, $tag, $attribs );
01081                                 break;
01082                         case self::MODE_STRUCT:
01083                                 $this->startElementModeStruct( $ns, $tag, $attribs );
01084                                 break;
01085                         case self::MODE_BAG:
01086                         case self::MODE_BAGSTRUCT:
01087                                 $this->startElementModeBag( $elm );
01088                                 break;
01089                         case self::MODE_SEQ:
01090                                 $this->startElementModeSeq( $elm );
01091                                 break;
01092                         case self::MODE_LANG:
01093                                 $this->startElementModeLang( $elm );
01094                                 break;
01095                         case self::MODE_LI_LANG:
01096                                 $this->startElementModeLiLang( $elm, $attribs );
01097                                 break;
01098                         case self::MODE_LI:
01099                                 $this->startElementModeLi( $elm, $attribs );
01100                                 break;
01101                         case self::MODE_QDESC:
01102                                 $this->startElementModeQDesc( $elm );
01103                                 break;
01104                         default:
01105                                 throw new MWException( 'StartElement in unknown mode: ' . $this->mode[0] );
01106                                 break;
01107                 }
01108         }
01109 
01125         private function doAttribs( $attribs ) {
01126 
01127                 // first check for rdf:parseType attribute, as that can change
01128                 // how the attributes are interperted.
01129 
01130                 if ( isset( $attribs[self::NS_RDF . ' parseType'] )
01131                         && $attribs[self::NS_RDF . ' parseType'] === 'Resource'
01132                         && $this->mode[0] === self::MODE_SIMPLE )
01133                 {
01134                         // this is equivalent to having an inner rdf:Description
01135                         $this->mode[0] = self::MODE_QDESC;
01136                 }
01137                 foreach ( $attribs as $name => $val ) {
01138 
01139 
01140                         if ( strpos( $name, ' ' ) === false ) {
01141                                 // This shouldn't happen, but so far some old software forgets namespace
01142                                 // on rdf:about.
01143                                 wfDebugLog( 'XMP', __METHOD__ . ' Encountered non-namespaced attribute: '
01144                                         . " $name=\"$val\". Skipping. " );
01145                                 continue;
01146                         }
01147                         list( $ns, $tag ) = explode( ' ', $name, 2 );
01148                         if ( $ns === self::NS_RDF ) {
01149                                 if ( $tag === 'value' || $tag === 'resource' ) {
01150                                         // resource is for url.
01151                                         // value attribute is a weird way of just putting the contents.
01152                                         $this->char( $this->xmlParser, $val );
01153                                 }
01154                         } elseif ( isset( $this->items[$ns][$tag] ) ) {
01155                                 if ( $this->mode[0] === self::MODE_SIMPLE ) {
01156                                         throw new MWException( __METHOD__
01157                                                 . " $ns:$tag found as attribute where not allowed" );
01158                                 }
01159                                 $this->saveValue( $ns, $tag, $val );
01160                         } else {
01161                                 wfDebugLog( 'XMP', __METHOD__ . " Ignoring unrecognized element <$ns:$tag>." );
01162                         }
01163                 }
01164         }
01165 
01177         private function saveValue( $ns, $tag, $val ) {
01178 
01179                 $info =& $this->items[$ns][$tag];
01180                 $finalName = isset( $info['map_name'] )
01181                         ? $info['map_name'] : $tag;
01182                 if ( isset( $info['validate'] ) ) {
01183                         $validate = is_array( $info['validate'] ) ? $info['validate']
01184                                 : array( 'XMPValidate', $info['validate'] );
01185 
01186                         if ( is_callable( $validate ) ) {
01187                                 call_user_func_array( $validate, array( $info, &$val, true ) );
01188                                 // the reasoning behind using &$val instead of using the return value
01189                                 // is to be consistent between here and validating structures.
01190                                 if ( is_null( $val ) ) {
01191                                         wfDebugLog( 'XMP', __METHOD__ . " <$ns:$tag> failed validation." );
01192                                         return;
01193                                 }
01194                         } else {
01195                                 wfDebugLog( 'XMP', __METHOD__ . " Validation function for $finalName ("
01196                                         . $validate[0] . '::' . $validate[1] . '()) is not callable.' );
01197                         }
01198                 }
01199 
01200                 if ( $this->ancestorStruct && $this->processingArray ) {
01201                         // Aka both an array and a struct. ( self::MODE_BAGSTRUCT )
01202                         $this->results['xmp-' . $info['map_group']][$this->ancestorStruct][][$finalName] = $val;
01203                 } elseif ( $this->ancestorStruct ) {
01204                         $this->results['xmp-' . $info['map_group']][$this->ancestorStruct][$finalName] = $val;
01205                 } elseif ( $this->processingArray ) {
01206                         if ( $this->itemLang === false ) {
01207                                 // normal array
01208                                 $this->results['xmp-' . $info['map_group']][$finalName][] = $val;
01209                         } else {
01210                                 // lang array.
01211                                 $this->results['xmp-' . $info['map_group']][$finalName][$this->itemLang] = $val;
01212                         }
01213                 } else {
01214                         $this->results['xmp-' . $info['map_group']][$finalName] = $val;
01215                 }
01216         }
01217 }