3 * Class for reading xmp data containing properties relevant to
4 * images, and spitting out an array that FormatExif accepts.
6 * Note, this is not meant to recognize every possible thing you can
7 * encode in XMP. It should recognize all the properties we want.
8 * For example it doesn't have support for structures with multiple
9 * nesting levels, as none of the properties we're supporting use that
10 * feature. If it comes across properties it doesn't recognize, it should
13 * The public methods one would call in this class are
15 * Reads in xmp content.
16 * Can potentially be called multiple times with partial data each time.
17 * - parseExtended( $content )
18 * Reads XMPExtended blocks (jpeg files only).
20 * Outputs a results array.
22 * Note XMP kind of looks like rdf. They are not the same thing - XMP is
23 * encoded as a specific subset of rdf. This class can read XMP. It cannot
29 private $curItem = array(); // array to hold the current element (and previous element, and so on)
30 private $ancestorStruct = false; // the structure name when processing nested structures.
31 private $charContent = false; // temporary holder for character data that appears in xmp doc.
32 private $mode = array(); // stores the state the xmpreader is in (see MODE_FOO constants)
33 private $results = array(); // array to hold results
34 private $processingArray = false; // if we're doing a seq or bag.
35 private $itemLang = false; // used for lang alts only
38 private $charset = false;
39 private $extendedXMPOffset = 0;
44 * These are various mode constants.
45 * they are used to figure out what to do
46 * with an element when its encountered.
48 * For example, MODE_IGNORE is used when processing
49 * a property we're not interested in. So if a new
50 * element pops up when we're in that mode, we ignore it.
52 const MODE_INITIAL
= 0;
53 const MODE_IGNORE
= 1;
55 const MODE_LI_LANG
= 3;
58 // The following MODE constants are also used in the
59 // $items array to denote what type of property the item is.
60 const MODE_SIMPLE
= 10;
61 const MODE_STRUCT
= 11; // structure (associative array)
62 const MODE_SEQ
= 12; // ordered list
63 const MODE_BAG
= 13; // unordered list
65 const MODE_ALT
= 15; // non-language alt. Currently not implemented, and not needed atm.
66 const MODE_BAGSTRUCT
= 16; // A BAG of Structs.
68 const NS_RDF
= 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
69 const NS_XML
= 'http://www.w3.org/XML/1998/namespace';
75 * Primary job is to initialize the XMLParser
77 function __construct() {
79 if ( !function_exists( 'xml_parser_create_ns' ) ) {
80 // this should already be checked by this point
81 throw new MWException( 'XMP support requires XML Parser' );
84 $this->items
= XMPInfo
::getItems();
86 $this->resetXMLParser();
90 * Main use is if a single item has multiple xmp documents describing it.
91 * For example in jpeg's with extendedXMP
93 private function resetXMLParser() {
95 if ($this->xmlParser
) {
97 xml_parser_free( $this->xmlParser
);
100 $this->xmlParser
= xml_parser_create_ns( 'UTF-8', ' ' );
101 xml_parser_set_option( $this->xmlParser
, XML_OPTION_CASE_FOLDING
, 0 );
102 xml_parser_set_option( $this->xmlParser
, XML_OPTION_SKIP_WHITE
, 1 );
104 xml_set_element_handler( $this->xmlParser
,
105 array( $this, 'startElement' ),
106 array( $this, 'endElement' ) );
108 xml_set_character_data_handler( $this->xmlParser
, array( $this, 'char' ) );
113 /** Destroy the xml parser
115 * Not sure if this is actually needed.
117 function __destruct() {
118 // not sure if this is needed.
119 xml_parser_free( $this->xmlParser
);
122 /** Get the result array. Do some post-processing before returning
123 * the array, and transform any metadata that is special-cased.
125 * @return Array array of results as an array of arrays suitable for
126 * FormatMetadata::getFormattedData().
128 public function getResults() {
129 // xmp-special is for metadata that affects how stuff
130 // is extracted. For example xmpNote:HasExtendedXMP.
132 // It is also used to handle photoshop:AuthorsPosition
133 // which is weird and really part of another property,
134 // see 2:85 in IPTC. See also pg 21 of IPTC4XMP standard.
135 // The location fields also use it.
137 $data = $this->results
;
139 wfRunHooks('XMPGetResults', Array(&$data));
141 if ( isset( $data['xmp-special']['AuthorsPosition'] )
142 && is_string( $data['xmp-special']['AuthorsPosition'] )
143 && isset( $data['xmp-general']['Artist'][0] )
145 // Note, if there is more than one creator,
146 // this only applies to first. This also will
147 // only apply to the dc:Creator prop, not the
150 $data['xmp-general']['Artist'][0] =
151 $data['xmp-special']['AuthorsPosition'] . ', '
152 . $data['xmp-general']['Artist'][0];
155 // Go through the LocationShown and LocationCreated
156 // changing it to the non-hierarchal form used by
157 // the other location fields.
159 if ( isset( $data['xmp-special']['LocationShown'][0] )
160 && is_array( $data['xmp-special']['LocationShown'][0] )
162 // the is_array is just paranoia. It should always
164 foreach( $data['xmp-special']['LocationShown'] as $loc ) {
165 if ( !is_array( $loc ) ) {
166 // To avoid copying over the _type meta-fields.
169 foreach( $loc as $field => $val ) {
170 $data['xmp-general'][$field . 'Dest'][] = $val;
174 if ( isset( $data['xmp-special']['LocationCreated'][0] )
175 && is_array( $data['xmp-special']['LocationCreated'][0] )
177 // the is_array is just paranoia. It should always
179 foreach( $data['xmp-special']['LocationCreated'] as $loc ) {
180 if ( !is_array( $loc ) ) {
181 // To avoid copying over the _type meta-fields.
184 foreach( $loc as $field => $val ) {
185 $data['xmp-general'][$field . 'Created'][] = $val;
191 // We don't want to return the special values, since they're
192 // special and not info to be stored about the file.
193 unset( $data['xmp-special'] );
195 // Convert GPSAltitude to negative if below sea level.
196 if ( isset( $data['xmp-exif']['GPSAltitudeRef'] ) ) {
197 if ( $data['xmp-exif']['GPSAltitudeRef'] == '1'
198 && isset( $data['xmp-exif']['GPSAltitude'] )
200 $data['xmp-exif']['GPSAltitude'] *= -1;
202 unset( $data['xmp-exif']['GPSAltitudeRef'] );
209 * Main function to call to parse XMP. Use getResults to
212 * Also catches any errors during processing, writes them to
213 * debug log, blanks result array and returns false.
215 * @param String: $content XMP data
216 * @param Boolean: $allOfIt If this is all the data (true) or if its split up (false). Default true
217 * @param Boolean: $reset - does xml parser need to be reset. Default false
218 * @return Boolean success.
220 public function parse( $content, $allOfIt = true, $reset = false ) {
222 $this->resetXMLParser();
226 // detect encoding by looking for BOM which is supposed to be in processing instruction.
227 // see page 12 of http://www.adobe.com/devnet/xmp/pdfs/XMPSpecificationPart3.pdf
228 if ( !$this->charset
) {
230 if ( preg_match( '/\xEF\xBB\xBF|\xFE\xFF|\x00\x00\xFE\xFF|\xFF\xFE\x00\x00|\xFF\xFE/',
235 $this->charset
= 'UTF-16BE';
238 $this->charset
= 'UTF-16LE';
240 case "\x00\x00\xFE\xFF":
241 $this->charset
= 'UTF-32BE';
243 case "\xFF\xFE\x00\x00":
244 $this->charset
= 'UTF-32LE';
247 $this->charset
= 'UTF-8';
250 //this should be impossible to get to
251 throw new MWException("Invalid BOM");
257 // standard specifically says, if no bom assume utf-8
258 $this->charset
= 'UTF-8';
261 if ( $this->charset
!== 'UTF-8' ) {
262 //don't convert if already utf-8
263 wfSuppressWarnings();
264 $content = iconv( $this->charset
, 'UTF-8//IGNORE', $content );
268 $ok = xml_parse( $this->xmlParser
, $content, $allOfIt );
270 $error = xml_error_string( xml_get_error_code( $this->xmlParser
) );
271 $where = 'line: ' . xml_get_current_line_number( $this->xmlParser
)
272 . ' column: ' . xml_get_current_column_number( $this->xmlParser
)
273 . ' byte offset: ' . xml_get_current_byte_index( $this->xmlParser
);
275 wfDebugLog( 'XMP', "XMPReader::parse : Error reading XMP content: $error ($where)" );
276 $this->results
= array(); // blank if error.
279 } catch ( MWException
$e ) {
280 wfDebugLog( 'XMP', 'XMP parse error: ' . $e );
281 $this->results
= array();
287 /** Entry point for XMPExtended blocks in jpeg files
289 * @todo In serious need of testing
290 * @see http://www.adobe.ge/devnet/xmp/pdfs/XMPSpecificationPart3.pdf XMP spec part 3 page 20
291 * @param String $content XMPExtended block minus the namespace signature
292 * @return Boolean If it succeeded.
294 public function parseExtended( $content ) {
295 // FIXME: This is untested. Hard to find example files
296 // or programs that make such files..
297 $guid = substr( $content, 0, 32 );
298 if ( !isset( $this->results
['xmp-special']['HasExtendedXMP'] )
299 ||
$this->results
['xmp-special']['HasExtendedXMP'] !== $guid )
301 wfDebugLog('XMP', __METHOD__
. " Ignoring XMPExtended block due to wrong guid (guid= '$guid' )");
304 $len = unpack( 'Nlength/Noffset', substr( $content, 32, 8 ) );
306 if (!$len ||
$len['length'] < 4 ||
$len['offset'] < 0 ||
$len['offset'] > $len['length'] ) {
307 wfDebugLog('XMP', __METHOD__
. 'Error reading extended XMP block, invalid length or offset.');
312 // we're not very robust here. we should accept it in the wrong order. To quote
314 // "A JPEG writer should write the ExtendedXMP marker segments in order, immediately following the
315 // StandardXMP. However, the JPEG standard does not require preservation of marker segment order. A
316 // robust JPEG reader should tolerate the marker segments in any order."
318 // otoh the probability that an image will have more than 128k of metadata is rather low...
319 // so the probability that it will have > 128k, and be in the wrong order is very low...
321 if ( $len['offset'] !== $this->extendedXMPOffset
) {
322 wfDebugLog('XMP', __METHOD__
. 'Ignoring XMPExtended block due to wrong order. (Offset was '
323 . $len['offset'] . ' but expected ' . $this->extendedXMPOffset
. ')');
327 if ( $len['offset'] === 0 ) {
328 // if we're starting the extended block, we've probably already
329 // done the XMPStandard block, so reset.
330 $this->resetXMLParser();
333 $this->extendedXMPOffset +
= $len['length'];
335 $actualContent = substr( $content, 40 );
337 if ( $this->extendedXMPOffset
=== strlen( $actualContent ) ) {
343 wfDebugLog('XMP', __METHOD__
. 'Parsing a XMPExtended block');
344 return $this->parse( $actualContent, $atEnd );
348 * Character data handler
349 * Called whenever character data is found in the xmp document.
351 * does nothing if we're in MODE_IGNORE or if the data is whitespace
352 * throws an error if we're not in MODE_SIMPLE (as we're not allowed to have character
353 * data in the other modes).
355 * As an example, this happens when we encounter XMP like:
356 * <exif:DigitalZoomRatio>0/10</exif:DigitalZoomRatio>
357 * and are processing the 0/10 bit.
359 * @param $parser XMLParser reference to the xml parser
360 * @param $data String Character data
361 * @throws MWException on invalid data
363 function char( $parser, $data ) {
365 $data = trim( $data );
366 if ( trim( $data ) === "" ) {
370 if ( !isset( $this->mode
[0] ) ) {
371 throw new MWException( 'Unexpected character data before first rdf:Description element' );
374 if ( $this->mode
[0] === self
::MODE_IGNORE
) return;
376 if ( $this->mode
[0] !== self
::MODE_SIMPLE
377 && $this->mode
[0] !== self
::MODE_QDESC
379 throw new MWException( 'character data where not expected. (mode ' . $this->mode
[0] . ')' );
382 // to check, how does this handle w.s.
383 if ( $this->charContent
=== false ) {
384 $this->charContent
= $data;
386 $this->charContent
.= $data;
390 /** When we hit a closing element in MODE_IGNORE
391 * Check to see if this is the element we started to ignore,
392 * in which case we get out of MODE_IGNORE
394 * @param $elm String Namespace of element followed by a space and then tag name of element.
396 private function endElementModeIgnore ( $elm ) {
398 if ( $this->curItem
[0] === $elm ) {
399 array_shift( $this->curItem
);
400 array_shift( $this->mode
);
406 * Hit a closing element when in MODE_SIMPLE.
407 * This generally means that we finished processing a
408 * property value, and now have to save the result to the
411 * For example, when processing:
412 * <exif:DigitalZoomRatio>0/10</exif:DigitalZoomRatio>
413 * this deals with when we hit </exif:DigitalZoomRatio>.
415 * Or it could be if we hit the end element of a property
416 * of a compound data structure (like a member of an array).
418 * @param $elm String namespace, space, and tag name.
420 private function endElementModeSimple ( $elm ) {
421 if ( $this->charContent
!== false ) {
422 if ( $this->processingArray
) {
423 // if we're processing an array, use the original element
424 // name instead of rdf:li.
425 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
427 list( $ns, $tag ) = explode( ' ', $elm, 2 );
429 $this->saveValue( $ns, $tag, $this->charContent
);
431 $this->charContent
= false; // reset
433 array_shift( $this->curItem
);
434 array_shift( $this->mode
);
438 * Hit a closing element in MODE_STRUCT, MODE_SEQ, MODE_BAG
439 * generally means we've finished processing a nested structure.
440 * resets some internal variables to indicate that.
442 * Note this means we hit the </closing element> not the </rdf:Seq>.
444 * For example, when processing:
445 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
446 * </rdf:Seq> </exif:ISOSpeedRatings>
448 * This method is called when we hit the </exif:ISOSpeedRatings> tag.
450 * @param $elm String namespace . space . tag name.
452 private function endElementNested( $elm ) {
454 /* cur item must be the same as $elm, unless if in MODE_STRUCT
455 in which case it could also be rdf:Description */
456 if ( $this->curItem
[0] !== $elm
457 && !( $elm === self
::NS_RDF
. ' Description'
458 && $this->mode
[0] === self
::MODE_STRUCT
)
460 throw new MWException( "nesting mismatch. got a </$elm> but expected a </" . $this->curItem
[0] . '>' );
463 // Validate structures.
464 list( $ns, $tag ) = explode( ' ', $elm, 2 );
465 if ( isset( $this->items
[$ns][$tag]['validate'] ) ) {
467 $info =& $this->items
[$ns][$tag];
468 $finalName = isset( $info['map_name'] )
469 ?
$info['map_name'] : $tag;
471 $validate = is_array( $info['validate'] ) ?
$info['validate']
472 : array( 'XMPValidate', $info['validate'] );
474 if ( !isset( $this->results
['xmp-' . $info['map_group']][$finalName] ) ) {
475 // This can happen if all the members of the struct failed validation.
476 wfDebugLog( 'XMP', __METHOD__
. " <$ns:$tag> has no valid members." );
478 } elseif ( is_callable( $validate ) ) {
479 $val =& $this->results
['xmp-' . $info['map_group']][$finalName];
480 call_user_func_array( $validate, array( $info, &$val, false ) );
481 if ( is_null( $val ) ) {
482 // the idea being the validation function will unset the variable if
484 wfDebugLog( 'XMP', __METHOD__
. " <$ns:$tag> failed validation." );
485 unset( $this->results
['xmp-' . $info['map_group']][$finalName] );
488 wfDebugLog( 'XMP', __METHOD__
. " Validation function for $finalName ("
489 . $validate[0] . '::' . $validate[1] . '()) is not callable.' );
493 array_shift( $this->curItem
);
494 array_shift( $this->mode
);
495 $this->ancestorStruct
= false;
496 $this->processingArray
= false;
497 $this->itemLang
= false;
501 * Hit a closing element in MODE_LI (either rdf:Seq, or rdf:Bag )
502 * Add information about what type of element this is.
504 * Note we still have to hit the outer </property>
506 * For example, when processing:
507 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
508 * </rdf:Seq> </exif:ISOSpeedRatings>
510 * This method is called when we hit the </rdf:Seq>.
511 * (For comparison, we call endElementModeSimple when we
514 * @param $elm String namespace . ' ' . element name
516 private function endElementModeLi( $elm ) {
518 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
519 $info = $this->items
[$ns][$tag];
520 $finalName = isset( $info['map_name'] )
521 ?
$info['map_name'] : $tag;
523 array_shift( $this->mode
);
525 if ( !isset( $this->results
['xmp-' . $info['map_group']][$finalName] ) ) {
526 wfDebugLog( 'XMP', __METHOD__
. " Empty compund element $finalName." );
530 if ( $elm === self
::NS_RDF
. ' Seq' ) {
531 $this->results
['xmp-' . $info['map_group']][$finalName]['_type'] = 'ol';
532 } elseif ( $elm === self
::NS_RDF
. ' Bag' ) {
533 $this->results
['xmp-' . $info['map_group']][$finalName]['_type'] = 'ul';
534 } elseif ( $elm === self
::NS_RDF
. ' Alt' ) {
535 // extra if needed as you could theoretically have a non-language alt.
536 if ( $info['mode'] === self
::MODE_LANG
) {
537 $this->results
['xmp-' . $info['map_group']][$finalName]['_type'] = 'lang';
541 throw new MWException( __METHOD__
. " expected </rdf:seq> or </rdf:bag> but instead got $elm." );
545 * End element while in MODE_QDESC
546 * mostly when ending an element when we have a simple value
547 * that has qualifiers.
549 * Qualifiers aren't all that common, and we don't do anything
552 * @param $elm String namespace and element
554 private function endElementModeQDesc( $elm ) {
556 if ( $elm === self
::NS_RDF
. ' value' ) {
557 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
558 $this->saveValue( $ns, $tag, $this->charContent
);
561 array_shift( $this->mode
);
562 array_shift( $this->curItem
);
568 * Handler for hitting a closing element.
570 * generally just calls a helper function depending on what
573 * Ignores the outer wrapping elements that are optional in
574 * xmp and have no meaning.
576 * @param $parser XMLParser
577 * @param $elm String namespace . ' ' . element name
579 function endElement( $parser, $elm ) {
580 if ( $elm === ( self
::NS_RDF
. ' RDF' )
581 ||
$elm === 'adobe:ns:meta/ xmpmeta'
582 ||
$elm === 'adobe:ns:meta/ xapmeta' )
588 if ( $elm === self
::NS_RDF
. ' type' ) {
589 // these aren't really supported properly yet.
590 // However, it appears they almost never used.
591 wfDebugLog( 'XMP', __METHOD__
. ' encountered <rdf:type>' );
594 if ( strpos( $elm, ' ' ) === false ) {
595 // This probably shouldn't happen.
596 // However, there is a bug in an adobe product
597 // that forgets the namespace on some things.
598 // (Luckily they are unimportant things).
599 wfDebugLog( 'XMP', __METHOD__
. " Encountered </$elm> which has no namespace. Skipping." );
603 if ( count( $this->mode
[0] ) === 0 ) {
604 // This should never ever happen and means
605 // there is a pretty major bug in this class.
606 throw new MWException( 'Encountered end element with no mode' );
609 if ( count( $this->curItem
) == 0 && $this->mode
[0] !== self
::MODE_INITIAL
) {
610 // just to be paranoid. Should always have a curItem, except for initially
611 // (aka during MODE_INITAL).
612 throw new MWException( "Hit end element </$elm> but no curItem" );
615 switch( $this->mode
[0] ) {
616 case self
::MODE_IGNORE
:
617 $this->endElementModeIgnore( $elm );
619 case self
::MODE_SIMPLE
:
620 $this->endElementModeSimple( $elm );
622 case self
::MODE_STRUCT
:
625 case self
::MODE_LANG
:
626 case self
::MODE_BAGSTRUCT
:
627 $this->endElementNested( $elm );
629 case self
::MODE_INITIAL
:
630 if ( $elm === self
::NS_RDF
. ' Description' ) {
631 array_shift( $this->mode
);
633 throw new MWException( 'Element ended unexpectedly while in MODE_INITIAL' );
637 case self
::MODE_LI_LANG
:
638 $this->endElementModeLi( $elm );
640 case self
::MODE_QDESC
:
641 $this->endElementModeQDesc( $elm );
644 wfDebugLog( 'XMP', __METHOD__
. " no mode (elm = $elm)" );
651 * Hit an opening element while in MODE_IGNORE
653 * XMP is extensible, so ignore any tag we don't understand.
655 * Mostly ignores, unless we encounter the element that we are ignoring.
656 * in which case we add it to the item stack, so we can ignore things
657 * that are nested, correctly.
659 * @param $elm String namespace . ' ' . tag name
661 private function startElementModeIgnore( $elm ) {
662 if ( $elm === $this->curItem
[0] ) {
663 array_unshift( $this->curItem
, $elm );
664 array_unshift( $this->mode
, self
::MODE_IGNORE
);
668 * Start element in MODE_BAG (unordered array)
669 * this should always be <rdf:Bag>
671 * @param $elm String namespace . ' ' . tag
672 * @throws MWException if we have an element that's not <rdf:Bag>
674 private function startElementModeBag( $elm ) {
675 if ( $elm === self
::NS_RDF
. ' Bag' ) {
676 array_unshift( $this->mode
, self
::MODE_LI
);
678 throw new MWException( "Expected <rdf:Bag> but got $elm." );
683 * Start element in MODE_SEQ (ordered array)
684 * this should always be <rdf:Seq>
686 * @param $elm String namespace . ' ' . tag
687 * @throws MWException if we have an element that's not <rdf:Seq>
689 private function startElementModeSeq( $elm ) {
690 if ( $elm === self
::NS_RDF
. ' Seq' ) {
691 array_unshift( $this->mode
, self
::MODE_LI
);
692 } else if ( $elm === self
::NS_RDF
. ' Bag' ) {
694 wfDebugLog( 'XMP', __METHOD__
. ' Expected an rdf:Seq, but got an rdf:Bag. Pretending'
695 . ' it is a Seq, since some buggy software is known to screw this up.' );
696 array_unshift( $this->mode
, self
::MODE_LI
);
698 throw new MWException( "Expected <rdf:Seq> but got $elm." );
703 * Start element in MODE_LANG (language alternative)
704 * this should always be <rdf:Alt>
706 * This tag tends to be used for metadata like describe this
707 * picture, which can be translated into multiple languages.
709 * XMP supports non-linguistic alternative selections,
710 * which are really only used for thumbnails, which
711 * we don't care about.
713 * @param $elm String namespace . ' ' . tag
714 * @throws MWException if we have an element that's not <rdf:Alt>
716 private function startElementModeLang( $elm ) {
717 if ( $elm === self
::NS_RDF
. ' Alt' ) {
718 array_unshift( $this->mode
, self
::MODE_LI_LANG
);
720 throw new MWException( "Expected <rdf:Seq> but got $elm." );
725 * Handle an opening element when in MODE_SIMPLE
727 * This should not happen often. This is for if a simple element
728 * already opened has a child element. Could happen for a
732 * <exif:DigitalZoomRatio><rdf:Description><rdf:value>0/10</rdf:value>
733 * <foo:someQualifier>Bar</foo:someQualifier> </rdf:Description>
734 * </exif:DigitalZoomRatio>
736 * This method is called when processing the <rdf:Description> element
738 * @param $elm String namespace and tag names separated by space.
739 * @param $attribs Array Attributes of the element.
741 private function startElementModeSimple( $elm, $attribs ) {
742 if ( $elm === self
::NS_RDF
. ' Description' ) {
743 // If this value has qualifiers
744 array_unshift( $this->mode
, self
::MODE_QDESC
);
745 array_unshift( $this->curItem
, $this->curItem
[0] );
747 if ( isset( $attribs[self
::NS_RDF
. ' value'] ) ) {
748 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
749 $this->saveValue( $ns, $tag, $attribs[self
::NS_RDF
. ' value'] );
751 } elseif ( $elm === self
::NS_RDF
. ' value' ) {
752 // This should not be here.
753 throw new MWException( __METHOD__
. ' Encountered <rdf:value> where it was unexpected.' );
756 // something else we don't recognize, like a qualifier maybe.
757 wfDebugLog( 'XMP', __METHOD__
. " Encountered element <$elm> where only expecting character data as value of " . $this->curItem
[0] );
758 array_unshift( $this->mode
, self
::MODE_IGNORE
);
759 array_unshift( $this->curItem
, $elm );
765 * Start an element when in MODE_QDESC.
766 * This generally happens when a simple element has an inner
767 * rdf:Description to hold qualifier elements.
770 * <exif:DigitalZoomRatio><rdf:Description><rdf:value>0/10</rdf:value>
771 * <foo:someQualifier>Bar</foo:someQualifier> </rdf:Description>
772 * </exif:DigitalZoomRatio>
773 * Called when processing the <rdf:value> or <foo:someQualifier>.
775 * @param $elm String namespace and tag name separated by a space.
778 private function startElementModeQDesc( $elm ) {
779 if ( $elm === self
::NS_RDF
. ' value' ) {
780 return; // do nothing
782 // otherwise its a qualifier, which we ignore
783 array_unshift( $this->mode
, self
::MODE_IGNORE
);
784 array_unshift( $this->curItem
, $elm );
788 * Starting an element when in MODE_INITIAL
789 * This usually happens when we hit an element inside
790 * the outer rdf:Description
792 * This is generally where most properties start.
794 * @param $ns String Namespace
795 * @param $tag String tag name (without namespace prefix)
796 * @param $attribs Array array of attributes
798 private function startElementModeInitial( $ns, $tag, $attribs ) {
799 if ( $ns !== self
::NS_RDF
) {
801 if ( isset( $this->items
[$ns][$tag] ) ) {
802 if ( isset( $this->items
[$ns][$tag]['structPart'] ) ) {
803 // If this element is supposed to appear only as
804 // a child of a structure, but appears here (not as
805 // a child of a struct), then something weird is
806 // happening, so ignore this element and its children.
808 wfDebugLog( 'XMP', "Encountered <$ns:$tag> outside"
809 . " of its expected parent. Ignoring." );
811 array_unshift( $this->mode
, self
::MODE_IGNORE
);
812 array_unshift( $this->curItem
, $ns . ' ' . $tag );
815 $mode = $this->items
[$ns][$tag]['mode'];
816 array_unshift( $this->mode
, $mode );
817 array_unshift( $this->curItem
, $ns . ' ' . $tag );
818 if ( $mode === self
::MODE_STRUCT
) {
819 $this->ancestorStruct
= isset( $this->items
[$ns][$tag]['map_name'] )
820 ?
$this->items
[$ns][$tag]['map_name'] : $tag;
822 if ( $this->charContent
!== false ) {
824 // Should not happen in valid XMP.
825 throw new MWException( 'tag nested in non-whitespace characters.' );
828 // This element is not on our list of allowed elements so ignore.
829 wfDebugLog( 'XMP', __METHOD__
. " Ignoring unrecognized element <$ns:$tag>." );
830 array_unshift( $this->mode
, self
::MODE_IGNORE
);
831 array_unshift( $this->curItem
, $ns . ' ' . $tag );
836 // process attributes
837 $this->doAttribs( $attribs );
840 * Hit an opening element when in a Struct (MODE_STRUCT)
841 * This is generally for fields of a compound property.
843 * Example of a struct (abbreviated; flash has more properties):
845 * <exif:Flash> <rdf:Description> <exif:Fired>True</exif:Fired>
846 * <exif:Mode>1</exif:Mode></rdf:Description></exif:Flash>
850 * <exif:Flash rdf:parseType='Resource'> <exif:Fired>True</exif:Fired>
851 * <exif:Mode>1</exif:Mode></exif:Flash>
853 * @param $ns String namespace
854 * @param $tag String tag name (no ns)
855 * @param $attribs Array array of attribs w/ values.
857 private function startElementModeStruct( $ns, $tag, $attribs ) {
858 if ( $ns !== self
::NS_RDF
) {
860 if ( isset( $this->items
[$ns][$tag] ) ) {
861 if ( isset( $this->items
[$ns][$this->ancestorStruct
]['children'] )
862 && !isset( $this->items
[$ns][$this->ancestorStruct
]['children'][$tag] ) )
864 // This assumes that we don't have inter-namespace nesting
865 // which we don't in all the properties we're interested in.
866 throw new MWException( " <$tag> appeared nested in <" . $this->ancestorStruct
867 . "> where it is not allowed." );
869 array_unshift( $this->mode
, $this->items
[$ns][$tag]['mode'] );
870 array_unshift( $this->curItem
, $ns . ' ' . $tag );
871 if ( $this->charContent
!== false ) {
873 // Should not happen in valid XMP.
874 throw new MWException( "tag <$tag> nested in non-whitespace characters (" . $this->charContent
. ")." );
877 array_unshift( $this->mode
, self
::MODE_IGNORE
);
878 array_unshift( $this->curItem
, $elm );
884 if ( $ns === self
::NS_RDF
&& $tag === 'Description' ) {
885 $this->doAttribs( $attribs );
886 array_unshift( $this->mode
, self
::MODE_STRUCT
);
887 array_unshift( $this->curItem
, $this->curItem
[0] );
891 * opening element in MODE_LI
892 * process elements of arrays.
895 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
896 * </rdf:Seq> </exif:ISOSpeedRatings>
897 * This method is called when we hit the <rdf:li> element.
899 * @param $elm String: namespace . ' ' . tagname
900 * @param $attribs Array: Attributes. (needed for BAGSTRUCTS)
901 * @throws MWException if gets a tag other than <rdf:li>
903 private function startElementModeLi( $elm, $attribs ) {
904 if ( ( $elm ) !== self
::NS_RDF
. ' li' ) {
905 throw new MWException( "<rdf:li> expected but got $elm." );
908 if ( !isset( $this->mode
[1] ) ) {
909 // This should never ever ever happen. Checking for it
911 throw new MWException( 'In mode Li, but no 2xPrevious mode!' );
914 if ( $this->mode
[1] === self
::MODE_BAGSTRUCT
) {
915 // This list item contains a compound (STRUCT) value.
916 array_unshift( $this->mode
, self
::MODE_STRUCT
);
917 array_unshift( $this->curItem
, $elm );
918 $this->processingArray
= true;
920 if ( !isset( $this->curItem
[1] ) ) {
922 throw new MWException( 'Can not find parent of BAGSTRUCT.' );
924 list( $curNS, $curTag ) = explode( ' ', $this->curItem
[1] );
925 $this->ancestorStruct
= isset( $this->items
[$curNS][$curTag]['map_name'] )
926 ?
$this->items
[$curNS][$curTag]['map_name'] : $curTag;
928 $this->doAttribs( $attribs );
931 // Normal BAG or SEQ containing simple values.
932 array_unshift( $this->mode
, self
::MODE_SIMPLE
);
933 // need to add curItem[0] on again since one is for the specific item
934 // and one is for the entire group.
935 array_unshift( $this->curItem
, $this->curItem
[0] );
936 $this->processingArray
= true;
941 * Opening element in MODE_LI_LANG.
942 * process elements of language alternatives
945 * <dc:title> <rdf:Alt> <rdf:li xml:lang="x-default">My house
946 * </rdf:li> </rdf:Alt> </dc:title>
948 * This method is called when we hit the <rdf:li> element.
950 * @param $elm String namespace . ' ' . tag
951 * @param $attribs array array of elements (most importantly xml:lang)
952 * @throws MWException if gets a tag other than <rdf:li> or if no xml:lang
954 private function startElementModeLiLang( $elm, $attribs ) {
955 if ( $elm !== self
::NS_RDF
. ' li' ) {
956 throw new MWException( __METHOD__
. " <rdf:li> expected but got $elm." );
958 if ( !isset( $attribs[ self
::NS_XML
. ' lang'] )
959 ||
!preg_match( '/^[-A-Za-z0-9]{2,}$/D', $attribs[ self
::NS_XML
. ' lang' ] ) )
961 throw new MWException( __METHOD__
962 . " <rdf:li> did not contain, or has invalid xml:lang attribute in lang alternative" );
965 // Lang is case-insensitive.
966 $this->itemLang
= strtolower( $attribs[ self
::NS_XML
. ' lang' ] );
968 // need to add curItem[0] on again since one is for the specific item
969 // and one is for the entire group.
970 array_unshift( $this->curItem
, $this->curItem
[0] );
971 array_unshift( $this->mode
, self
::MODE_SIMPLE
);
972 $this->processingArray
= true;
976 * Hits an opening element.
977 * Generally just calls a helper based on what MODE we're in.
978 * Also does some initial set up for the wrapper element
980 * @param $parser XMLParser
981 * @param $elm String namespace <space> element
982 * @param $attribs Array attribute name => value
984 function startElement( $parser, $elm, $attribs ) {
986 if ( $elm === self
::NS_RDF
. ' RDF'
987 ||
$elm === 'adobe:ns:meta/ xmpmeta'
988 ||
$elm === 'adobe:ns:meta/ xapmeta')
992 } elseif ( $elm === self
::NS_RDF
. ' Description' ) {
993 if ( count( $this->mode
) === 0 ) {
995 array_unshift( $this->mode
, self
::MODE_INITIAL
);
997 } elseif ( $elm === self
::NS_RDF
. ' type' ) {
998 // This doesn't support rdf:type properly.
999 // In practise I have yet to see a file that
1000 // uses this element, however it is mentioned
1001 // on page 25 of part 1 of the xmp standard.
1003 // also it seems as if exiv2 and exiftool do not support
1004 // this either (That or I misunderstand the standard)
1005 wfDebugLog( 'XMP', __METHOD__
. ' Encountered <rdf:type> which isn\'t currently supported' );
1008 if ( strpos( $elm, ' ' ) === false ) {
1009 // This probably shouldn't happen.
1010 wfDebugLog( 'XMP', __METHOD__
. " Encountered <$elm> which has no namespace. Skipping." );
1014 list( $ns, $tag ) = explode( ' ', $elm, 2 );
1016 if ( count( $this->mode
) === 0 ) {
1017 // This should not happen.
1018 throw new MWException('Error extracting XMP, '
1019 . "encountered <$elm> with no mode" );
1022 switch( $this->mode
[0] ) {
1023 case self
::MODE_IGNORE
:
1024 $this->startElementModeIgnore( $elm );
1026 case self
::MODE_SIMPLE
:
1027 $this->startElementModeSimple( $elm, $attribs );
1029 case self
::MODE_INITIAL
:
1030 $this->startElementModeInitial( $ns, $tag, $attribs );
1032 case self
::MODE_STRUCT
:
1033 $this->startElementModeStruct( $ns, $tag, $attribs );
1035 case self
::MODE_BAG
:
1036 case self
::MODE_BAGSTRUCT
:
1037 $this->startElementModeBag( $elm );
1039 case self
::MODE_SEQ
:
1040 $this->startElementModeSeq( $elm );
1042 case self
::MODE_LANG
:
1043 $this->startElementModeLang( $elm );
1045 case self
::MODE_LI_LANG
:
1046 $this->startElementModeLiLang( $elm, $attribs );
1049 $this->startElementModeLi( $elm, $attribs );
1051 case self
::MODE_QDESC
:
1052 $this->startElementModeQDesc( $elm );
1055 throw new MWException( 'StartElement in unknown mode: ' . $this->mode
[0] );
1063 * Process attributes.
1064 * Simple values can be stored as either a tag or attribute
1066 * Often the initial <rdf:Description> tag just has all the simple
1067 * properties as attributes.
1070 * <rdf:Description rdf:about="" xmlns:exif="http://ns.adobe.com/exif/1.0/" exif:DigitalZoomRatio="0/10">
1072 * @param $attribs Array attribute=>value array.
1074 private function doAttribs( $attribs ) {
1076 // first check for rdf:parseType attribute, as that can change
1077 // how the attributes are interperted.
1079 if ( isset( $attribs[self
::NS_RDF
. ' parseType'] )
1080 && $attribs[self
::NS_RDF
. ' parseType'] === 'Resource'
1081 && $this->mode
[0] === self
::MODE_SIMPLE
)
1083 // this is equivalent to having an inner rdf:Description
1084 $this->mode
[0] = self
::MODE_QDESC
;
1086 foreach ( $attribs as $name => $val ) {
1089 if ( strpos( $name, ' ' ) === false ) {
1090 // This shouldn't happen, but so far some old software forgets namespace
1092 wfDebugLog( 'XMP', __METHOD__
. ' Encountered non-namespaced attribute: '
1093 . " $name=\"$val\". Skipping. " );
1096 list( $ns, $tag ) = explode( ' ', $name, 2 );
1097 if ( $ns === self
::NS_RDF
) {
1098 if ( $tag === 'value' ||
$tag === 'resource' ) {
1099 // resource is for url.
1100 // value attribute is a weird way of just putting the contents.
1101 $this->char( $this->xmlParser
, $val );
1103 } elseif ( isset( $this->items
[$ns][$tag] ) ) {
1104 if ( $this->mode
[0] === self
::MODE_SIMPLE
) {
1105 throw new MWException( __METHOD__
1106 . " $ns:$tag found as attribute where not allowed" );
1108 $this->saveValue( $ns, $tag, $val );
1110 wfDebugLog( 'XMP', __METHOD__
. " Ignoring unrecognized element <$ns:$tag>." );
1115 * Given an extracted value, save it to results array
1117 * note also uses $this->ancestorStruct and
1118 * $this->processingArray to determine what name to
1119 * save the value under. (in addition to $tag).
1121 * @param $ns String namespace of tag this is for
1122 * @param $tag String tag name
1123 * @param $val String value to save
1125 private function saveValue( $ns, $tag, $val ) {
1127 $info =& $this->items
[$ns][$tag];
1128 $finalName = isset( $info['map_name'] )
1129 ?
$info['map_name'] : $tag;
1130 if ( isset( $info['validate'] ) ) {
1131 $validate = is_array( $info['validate'] ) ?
$info['validate']
1132 : array( 'XMPValidate', $info['validate'] );
1134 if ( is_callable( $validate ) ) {
1135 call_user_func_array( $validate, array( $info, &$val, true ) );
1136 // the reasoning behind using &$val instead of using the return value
1137 // is to be consistent between here and validating structures.
1138 if ( is_null( $val ) ) {
1139 wfDebugLog( 'XMP', __METHOD__
. " <$ns:$tag> failed validation." );
1143 wfDebugLog( 'XMP', __METHOD__
. " Validation function for $finalName ("
1144 . $validate[0] . '::' . $validate[1] . '()) is not callable.' );
1148 if ( $this->ancestorStruct
&& $this->processingArray
) {
1149 // Aka both an array and a struct. ( self::MODE_BAGSTRUCT )
1150 $this->results
['xmp-' . $info['map_group']][$this->ancestorStruct
][][$finalName] = $val;
1151 } elseif ( $this->ancestorStruct
) {
1152 $this->results
['xmp-' . $info['map_group']][$this->ancestorStruct
][$finalName] = $val;
1153 } elseif ( $this->processingArray
) {
1154 if ( $this->itemLang
=== false ) {
1156 $this->results
['xmp-' . $info['map_group']][$finalName][] = $val;
1159 $this->results
['xmp-' . $info['map_group']][$finalName][$this->itemLang
] = $val;
1162 $this->results
['xmp-' . $info['map_group']][$finalName] = $val;