fd95f3c17c45d4d217cce6f29afa49e913d615e2
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 ) {
300 wfDebugLog('XMP', __METHOD__
. " Ignoring XMPExtended block due to wrong guid (guid= '$guid' )");
303 $len = unpack( 'Nlength/Noffset', substr( $content, 32, 8 ) );
305 if (!$len ||
$len['length'] < 4 ||
$len['offset'] < 0 ||
$len['offset'] > $len['length'] ) {
306 wfDebugLog('XMP', __METHOD__
. 'Error reading extended XMP block, invalid length or offset.');
311 // we're not very robust here. we should accept it in the wrong order. To quote
313 // "A JPEG writer should write the ExtendedXMP marker segments in order, immediately following the
314 // StandardXMP. However, the JPEG standard does not require preservation of marker segment order. A
315 // robust JPEG reader should tolerate the marker segments in any order."
317 // otoh the probability that an image will have more than 128k of metadata is rather low...
318 // so the probability that it will have > 128k, and be in the wrong order is very low...
320 if ( $len['offset'] !== $this->extendedXMPOffset
) {
321 wfDebugLog('XMP', __METHOD__
. 'Ignoring XMPExtended block due to wrong order. (Offset was '
322 . $len['offset'] . ' but expected ' . $this->extendedXMPOffset
. ')');
326 if ( $len['offset'] === 0 ) {
327 // if we're starting the extended block, we've probably already
328 // done the XMPStandard block, so reset.
329 $this->resetXMLParser();
332 $this->extendedXMPOffset +
= $len['length'];
334 $actualContent = substr( $content, 40 );
336 if ( $this->extendedXMPOffset
=== strlen( $actualContent ) ) {
342 wfDebugLog('XMP', __METHOD__
. 'Parsing a XMPExtended block');
343 return $this->parse( $actualContent, $atEnd );
347 * Character data handler
348 * Called whenever character data is found in the xmp document.
350 * does nothing if we're in MODE_IGNORE or if the data is whitespace
351 * throws an error if we're not in MODE_SIMPLE (as we're not allowed to have character
352 * data in the other modes).
354 * As an example, this happens when we encounter XMP like:
355 * <exif:DigitalZoomRatio>0/10</exif:DigitalZoomRatio>
356 * and are processing the 0/10 bit.
358 * @param $parser XMLParser reference to the xml parser
359 * @param $data String Character data
360 * @throws MWException on invalid data
362 function char( $parser, $data ) {
364 $data = trim( $data );
365 if ( trim( $data ) === "" ) {
369 if ( !isset( $this->mode
[0] ) ) {
370 throw new MWException( 'Unexpected character data before first rdf:Description element' );
373 if ( $this->mode
[0] === self
::MODE_IGNORE
) return;
375 if ( $this->mode
[0] !== self
::MODE_SIMPLE
376 && $this->mode
[0] !== self
::MODE_QDESC
378 throw new MWException( 'character data where not expected. (mode ' . $this->mode
[0] . ')' );
381 // to check, how does this handle w.s.
382 if ( $this->charContent
=== false ) {
383 $this->charContent
= $data;
385 $this->charContent
.= $data;
389 /** When we hit a closing element in MODE_IGNORE
390 * Check to see if this is the element we started to ignore,
391 * in which case we get out of MODE_IGNORE
393 * @param $elm String Namespace of element followed by a space and then tag name of element.
395 private function endElementModeIgnore ( $elm ) {
397 if ( $this->curItem
[0] === $elm ) {
398 array_shift( $this->curItem
);
399 array_shift( $this->mode
);
405 * Hit a closing element when in MODE_SIMPLE.
406 * This generally means that we finished processing a
407 * property value, and now have to save the result to the
410 * For example, when processing:
411 * <exif:DigitalZoomRatio>0/10</exif:DigitalZoomRatio>
412 * this deals with when we hit </exif:DigitalZoomRatio>.
414 * Or it could be if we hit the end element of a property
415 * of a compound data structure (like a member of an array).
417 * @param $elm String namespace, space, and tag name.
419 private function endElementModeSimple ( $elm ) {
420 if ( $this->charContent
!== false ) {
421 if ( $this->processingArray
) {
422 // if we're processing an array, use the original element
423 // name instead of rdf:li.
424 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
426 list( $ns, $tag ) = explode( ' ', $elm, 2 );
428 $this->saveValue( $ns, $tag, $this->charContent
);
430 $this->charContent
= false; // reset
432 array_shift( $this->curItem
);
433 array_shift( $this->mode
);
437 * Hit a closing element in MODE_STRUCT, MODE_SEQ, MODE_BAG
438 * generally means we've finished processing a nested structure.
439 * resets some internal variables to indicate that.
441 * Note this means we hit the </closing element> not the </rdf:Seq>.
443 * For example, when processing:
444 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
445 * </rdf:Seq> </exif:ISOSpeedRatings>
447 * This method is called when we hit the </exif:ISOSpeedRatings> tag.
449 * @param $elm String namespace . space . tag name.
451 private function endElementNested( $elm ) {
453 /* cur item must be the same as $elm, unless if in MODE_STRUCT
454 in which case it could also be rdf:Description */
455 if ( $this->curItem
[0] !== $elm
456 && !( $elm === self
::NS_RDF
. ' Description'
457 && $this->mode
[0] === self
::MODE_STRUCT
)
459 throw new MWException( "nesting mismatch. got a </$elm> but expected a </" . $this->curItem
[0] . '>' );
462 // Validate structures.
463 list( $ns, $tag ) = explode( ' ', $elm, 2 );
464 if ( isset( $this->items
[$ns][$tag]['validate'] ) ) {
466 $info =& $this->items
[$ns][$tag];
467 $finalName = isset( $info['map_name'] )
468 ?
$info['map_name'] : $tag;
470 $validate = is_array( $info['validate'] ) ?
$info['validate']
471 : array( 'XMPValidate', $info['validate'] );
473 if ( !isset( $this->results
['xmp-' . $info['map_group']][$finalName] ) ) {
474 // This can happen if all the members of the struct failed validation.
475 wfDebugLog( 'XMP', __METHOD__
. " <$ns:$tag> has no valid members." );
477 } elseif ( is_callable( $validate ) ) {
478 $val =& $this->results
['xmp-' . $info['map_group']][$finalName];
479 call_user_func_array( $validate, array( $info, &$val, false ) );
480 if ( is_null( $val ) ) {
481 // the idea being the validation function will unset the variable if
483 wfDebugLog( 'XMP', __METHOD__
. " <$ns:$tag> failed validation." );
484 unset( $this->results
['xmp-' . $info['map_group']][$finalName] );
487 wfDebugLog( 'XMP', __METHOD__
. " Validation function for $finalName ("
488 . $validate[0] . '::' . $validate[1] . '()) is not callable.' );
492 array_shift( $this->curItem
);
493 array_shift( $this->mode
);
494 $this->ancestorStruct
= false;
495 $this->processingArray
= false;
496 $this->itemLang
= false;
500 * Hit a closing element in MODE_LI (either rdf:Seq, or rdf:Bag )
501 * Add information about what type of element this is.
503 * Note we still have to hit the outer </property>
505 * For example, when processing:
506 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
507 * </rdf:Seq> </exif:ISOSpeedRatings>
509 * This method is called when we hit the </rdf:Seq>.
510 * (For comparison, we call endElementModeSimple when we
513 * @param $elm String namespace . ' ' . element name
515 private function endElementModeLi( $elm ) {
517 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
518 $info = $this->items
[$ns][$tag];
519 $finalName = isset( $info['map_name'] )
520 ?
$info['map_name'] : $tag;
522 array_shift( $this->mode
);
524 if ( !isset( $this->results
['xmp-' . $info['map_group']][$finalName] ) ) {
525 wfDebugLog( 'XMP', __METHOD__
. " Empty compund element $finalName." );
529 if ( $elm === self
::NS_RDF
. ' Seq' ) {
530 $this->results
['xmp-' . $info['map_group']][$finalName]['_type'] = 'ol';
531 } elseif ( $elm === self
::NS_RDF
. ' Bag' ) {
532 $this->results
['xmp-' . $info['map_group']][$finalName]['_type'] = 'ul';
533 } elseif ( $elm === self
::NS_RDF
. ' Alt' ) {
534 // extra if needed as you could theoretically have a non-language alt.
535 if ( $info['mode'] === self
::MODE_LANG
) {
536 $this->results
['xmp-' . $info['map_group']][$finalName]['_type'] = 'lang';
540 throw new MWException( __METHOD__
. " expected </rdf:seq> or </rdf:bag> but instead got $elm." );
544 * End element while in MODE_QDESC
545 * mostly when ending an element when we have a simple value
546 * that has qualifiers.
548 * Qualifiers aren't all that common, and we don't do anything
551 * @param $elm String namespace and element
553 private function endElementModeQDesc( $elm ) {
555 if ( $elm === self
::NS_RDF
. ' value' ) {
556 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
557 $this->saveValue( $ns, $tag, $this->charContent
);
560 array_shift( $this->mode
);
561 array_shift( $this->curItem
);
567 * Handler for hitting a closing element.
569 * generally just calls a helper function depending on what
572 * Ignores the outer wrapping elements that are optional in
573 * xmp and have no meaning.
575 * @param $parser XMLParser
576 * @param $elm String namespace . ' ' . element name
578 function endElement( $parser, $elm ) {
579 if ( $elm === ( self
::NS_RDF
. ' RDF' )
580 ||
$elm === 'adobe:ns:meta/ xmpmeta'
581 ||
$elm === 'adobe:ns:meta/ xapmeta' )
587 if ( $elm === self
::NS_RDF
. ' type' ) {
588 // these aren't really supported properly yet.
589 // However, it appears they almost never used.
590 wfDebugLog( 'XMP', __METHOD__
. ' encountered <rdf:type>' );
593 if ( strpos( $elm, ' ' ) === false ) {
594 // This probably shouldn't happen.
595 // However, there is a bug in an adobe product
596 // that forgets the namespace on some things.
597 // (Luckily they are unimportant things).
598 wfDebugLog( 'XMP', __METHOD__
. " Encountered </$elm> which has no namespace. Skipping." );
602 if ( count( $this->mode
[0] ) === 0 ) {
603 // This should never ever happen and means
604 // there is a pretty major bug in this class.
605 throw new MWException( 'Encountered end element with no mode' );
608 if ( count( $this->curItem
) == 0 && $this->mode
[0] !== self
::MODE_INITIAL
) {
609 // just to be paranoid. Should always have a curItem, except for initially
610 // (aka during MODE_INITAL).
611 throw new MWException( "Hit end element </$elm> but no curItem" );
614 switch( $this->mode
[0] ) {
615 case self
::MODE_IGNORE
:
616 $this->endElementModeIgnore( $elm );
618 case self
::MODE_SIMPLE
:
619 $this->endElementModeSimple( $elm );
621 case self
::MODE_STRUCT
:
624 case self
::MODE_LANG
:
625 case self
::MODE_BAGSTRUCT
:
626 $this->endElementNested( $elm );
628 case self
::MODE_INITIAL
:
629 if ( $elm === self
::NS_RDF
. ' Description' ) {
630 array_shift( $this->mode
);
632 throw new MWException( 'Element ended unexpectedly while in MODE_INITIAL' );
636 case self
::MODE_LI_LANG
:
637 $this->endElementModeLi( $elm );
639 case self
::MODE_QDESC
:
640 $this->endElementModeQDesc( $elm );
643 wfDebugLog( 'XMP', __METHOD__
. " no mode (elm = $elm)" );
649 * Hit an opening element while in MODE_IGNORE
651 * XMP is extensible, so ignore any tag we don't understand.
653 * Mostly ignores, unless we encounter the element that we are ignoring.
654 * in which case we add it to the item stack, so we can ignore things
655 * that are nested, correctly.
657 * @param $elm String namespace . ' ' . tag name
659 private function startElementModeIgnore( $elm ) {
660 if ( $elm === $this->curItem
[0] ) {
661 array_unshift( $this->curItem
, $elm );
662 array_unshift( $this->mode
, self
::MODE_IGNORE
);
667 * Start element in MODE_BAG (unordered array)
668 * this should always be <rdf:Bag>
670 * @param $elm String namespace . ' ' . tag
671 * @throws MWException if we have an element that's not <rdf:Bag>
673 private function startElementModeBag( $elm ) {
674 if ( $elm === self
::NS_RDF
. ' Bag' ) {
675 array_unshift( $this->mode
, self
::MODE_LI
);
677 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." );
704 * Start element in MODE_LANG (language alternative)
705 * this should always be <rdf:Alt>
707 * This tag tends to be used for metadata like describe this
708 * picture, which can be translated into multiple languages.
710 * XMP supports non-linguistic alternative selections,
711 * which are really only used for thumbnails, which
712 * we don't care about.
714 * @param $elm String namespace . ' ' . tag
715 * @throws MWException if we have an element that's not <rdf:Alt>
717 private function startElementModeLang( $elm ) {
718 if ( $elm === self
::NS_RDF
. ' Alt' ) {
719 array_unshift( $this->mode
, self
::MODE_LI_LANG
);
721 throw new MWException( "Expected <rdf:Seq> but got $elm." );
727 * Handle an opening element when in MODE_SIMPLE
729 * This should not happen often. This is for if a simple element
730 * already opened has a child element. Could happen for a
734 * <exif:DigitalZoomRatio><rdf:Description><rdf:value>0/10</rdf:value>
735 * <foo:someQualifier>Bar</foo:someQualifier> </rdf:Description>
736 * </exif:DigitalZoomRatio>
738 * This method is called when processing the <rdf:Description> element
740 * @param $elm String namespace and tag names separated by space.
741 * @param $attribs Array Attributes of the element.
743 private function startElementModeSimple( $elm, $attribs ) {
744 if ( $elm === self
::NS_RDF
. ' Description' ) {
745 // If this value has qualifiers
746 array_unshift( $this->mode
, self
::MODE_QDESC
);
747 array_unshift( $this->curItem
, $this->curItem
[0] );
749 if ( isset( $attribs[self
::NS_RDF
. ' value'] ) ) {
750 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
751 $this->saveValue( $ns, $tag, $attribs[self
::NS_RDF
. ' value'] );
753 } elseif ( $elm === self
::NS_RDF
. ' value' ) {
754 // This should not be here.
755 throw new MWException( __METHOD__
. ' Encountered <rdf:value> where it was unexpected.' );
758 // something else we don't recognize, like a qualifier maybe.
759 wfDebugLog( 'XMP', __METHOD__
. " Encountered element <$elm> where only expecting character data as value of " . $this->curItem
[0] );
760 array_unshift( $this->mode
, self
::MODE_IGNORE
);
761 array_unshift( $this->curItem
, $elm );
768 * Start an element when in MODE_QDESC.
769 * This generally happens when a simple element has an inner
770 * rdf:Description to hold qualifier elements.
773 * <exif:DigitalZoomRatio><rdf:Description><rdf:value>0/10</rdf:value>
774 * <foo:someQualifier>Bar</foo:someQualifier> </rdf:Description>
775 * </exif:DigitalZoomRatio>
776 * Called when processing the <rdf:value> or <foo:someQualifier>.
778 * @param $elm String namespace and tag name separated by a space.
781 private function startElementModeQDesc( $elm ) {
782 if ( $elm === self
::NS_RDF
. ' value' ) {
783 return; // do nothing
785 // otherwise its a qualifier, which we ignore
786 array_unshift( $this->mode
, self
::MODE_IGNORE
);
787 array_unshift( $this->curItem
, $elm );
792 * Starting an element when in MODE_INITIAL
793 * This usually happens when we hit an element inside
794 * the outer rdf:Description
796 * This is generally where most properties start.
798 * @param $ns String Namespace
799 * @param $tag String tag name (without namespace prefix)
800 * @param $attribs Array array of attributes
802 private function startElementModeInitial( $ns, $tag, $attribs ) {
803 if ( $ns !== self
::NS_RDF
) {
805 if ( isset( $this->items
[$ns][$tag] ) ) {
806 if ( isset( $this->items
[$ns][$tag]['structPart'] ) ) {
807 // If this element is supposed to appear only as
808 // a child of a structure, but appears here (not as
809 // a child of a struct), then something weird is
810 // happening, so ignore this element and its children.
812 wfDebugLog( 'XMP', "Encountered <$ns:$tag> outside"
813 . " of its expected parent. Ignoring." );
815 array_unshift( $this->mode
, self
::MODE_IGNORE
);
816 array_unshift( $this->curItem
, $ns . ' ' . $tag );
819 $mode = $this->items
[$ns][$tag]['mode'];
820 array_unshift( $this->mode
, $mode );
821 array_unshift( $this->curItem
, $ns . ' ' . $tag );
822 if ( $mode === self
::MODE_STRUCT
) {
823 $this->ancestorStruct
= isset( $this->items
[$ns][$tag]['map_name'] )
824 ?
$this->items
[$ns][$tag]['map_name'] : $tag;
826 if ( $this->charContent
!== false ) {
828 // Should not happen in valid XMP.
829 throw new MWException( 'tag nested in non-whitespace characters.' );
832 // This element is not on our list of allowed elements so ignore.
833 wfDebugLog( 'XMP', __METHOD__
. " Ignoring unrecognized element <$ns:$tag>." );
834 array_unshift( $this->mode
, self
::MODE_IGNORE
);
835 array_unshift( $this->curItem
, $ns . ' ' . $tag );
840 // process attributes
841 $this->doAttribs( $attribs );
845 * Hit an opening element when in a Struct (MODE_STRUCT)
846 * This is generally for fields of a compound property.
848 * Example of a struct (abbreviated; flash has more properties):
850 * <exif:Flash> <rdf:Description> <exif:Fired>True</exif:Fired>
851 * <exif:Mode>1</exif:Mode></rdf:Description></exif:Flash>
855 * <exif:Flash rdf:parseType='Resource'> <exif:Fired>True</exif:Fired>
856 * <exif:Mode>1</exif:Mode></exif:Flash>
858 * @param $ns String namespace
859 * @param $tag String tag name (no ns)
860 * @param $attribs Array array of attribs w/ values.
862 private function startElementModeStruct( $ns, $tag, $attribs ) {
863 if ( $ns !== self
::NS_RDF
) {
865 if ( isset( $this->items
[$ns][$tag] ) ) {
866 if ( isset( $this->items
[$ns][$this->ancestorStruct
]['children'] )
867 && !isset( $this->items
[$ns][$this->ancestorStruct
]['children'][$tag] ) )
869 // This assumes that we don't have inter-namespace nesting
870 // which we don't in all the properties we're interested in.
871 throw new MWException( " <$tag> appeared nested in <" . $this->ancestorStruct
872 . "> where it is not allowed." );
874 array_unshift( $this->mode
, $this->items
[$ns][$tag]['mode'] );
875 array_unshift( $this->curItem
, $ns . ' ' . $tag );
876 if ( $this->charContent
!== false ) {
878 // Should not happen in valid XMP.
879 throw new MWException( "tag <$tag> nested in non-whitespace characters (" . $this->charContent
. ")." );
882 array_unshift( $this->mode
, self
::MODE_IGNORE
);
883 array_unshift( $this->curItem
, $elm );
889 if ( $ns === self
::NS_RDF
&& $tag === 'Description' ) {
890 $this->doAttribs( $attribs );
891 array_unshift( $this->mode
, self
::MODE_STRUCT
);
892 array_unshift( $this->curItem
, $this->curItem
[0] );
897 * opening element in MODE_LI
898 * process elements of arrays.
901 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
902 * </rdf:Seq> </exif:ISOSpeedRatings>
903 * This method is called when we hit the <rdf:li> element.
905 * @param $elm String: namespace . ' ' . tagname
906 * @param $attribs Array: Attributes. (needed for BAGSTRUCTS)
907 * @throws MWException if gets a tag other than <rdf:li>
909 private function startElementModeLi( $elm, $attribs ) {
910 if ( ( $elm ) !== self
::NS_RDF
. ' li' ) {
911 throw new MWException( "<rdf:li> expected but got $elm." );
914 if ( !isset( $this->mode
[1] ) ) {
915 // This should never ever ever happen. Checking for it
917 throw new MWException( 'In mode Li, but no 2xPrevious mode!' );
920 if ( $this->mode
[1] === self
::MODE_BAGSTRUCT
) {
921 // This list item contains a compound (STRUCT) value.
922 array_unshift( $this->mode
, self
::MODE_STRUCT
);
923 array_unshift( $this->curItem
, $elm );
924 $this->processingArray
= true;
926 if ( !isset( $this->curItem
[1] ) ) {
928 throw new MWException( 'Can not find parent of BAGSTRUCT.' );
930 list( $curNS, $curTag ) = explode( ' ', $this->curItem
[1] );
931 $this->ancestorStruct
= isset( $this->items
[$curNS][$curTag]['map_name'] )
932 ?
$this->items
[$curNS][$curTag]['map_name'] : $curTag;
934 $this->doAttribs( $attribs );
937 // Normal BAG or SEQ containing simple values.
938 array_unshift( $this->mode
, self
::MODE_SIMPLE
);
939 // need to add curItem[0] on again since one is for the specific item
940 // and one is for the entire group.
941 array_unshift( $this->curItem
, $this->curItem
[0] );
942 $this->processingArray
= true;
948 * Opening element in MODE_LI_LANG.
949 * process elements of language alternatives
952 * <dc:title> <rdf:Alt> <rdf:li xml:lang="x-default">My house
953 * </rdf:li> </rdf:Alt> </dc:title>
955 * This method is called when we hit the <rdf:li> element.
957 * @param $elm String namespace . ' ' . tag
958 * @param $attribs array array of elements (most importantly xml:lang)
959 * @throws MWException if gets a tag other than <rdf:li> or if no xml:lang
961 private function startElementModeLiLang( $elm, $attribs ) {
962 if ( $elm !== self
::NS_RDF
. ' li' ) {
963 throw new MWException( __METHOD__
. " <rdf:li> expected but got $elm." );
965 if ( !isset( $attribs[ self
::NS_XML
. ' lang'] )
966 ||
!preg_match( '/^[-A-Za-z0-9]{2,}$/D', $attribs[ self
::NS_XML
. ' lang' ] ) )
968 throw new MWException( __METHOD__
969 . " <rdf:li> did not contain, or has invalid xml:lang attribute in lang alternative" );
972 // Lang is case-insensitive.
973 $this->itemLang
= strtolower( $attribs[ self
::NS_XML
. ' lang' ] );
975 // need to add curItem[0] on again since one is for the specific item
976 // and one is for the entire group.
977 array_unshift( $this->curItem
, $this->curItem
[0] );
978 array_unshift( $this->mode
, self
::MODE_SIMPLE
);
979 $this->processingArray
= true;
983 * Hits an opening element.
984 * Generally just calls a helper based on what MODE we're in.
985 * Also does some initial set up for the wrapper element
987 * @param $parser XMLParser
988 * @param $elm String namespace <space> element
989 * @param $attribs Array attribute name => value
991 function startElement( $parser, $elm, $attribs ) {
993 if ( $elm === self
::NS_RDF
. ' RDF'
994 ||
$elm === 'adobe:ns:meta/ xmpmeta'
995 ||
$elm === 'adobe:ns:meta/ xapmeta')
999 } elseif ( $elm === self
::NS_RDF
. ' Description' ) {
1000 if ( count( $this->mode
) === 0 ) {
1002 array_unshift( $this->mode
, self
::MODE_INITIAL
);
1004 } elseif ( $elm === self
::NS_RDF
. ' type' ) {
1005 // This doesn't support rdf:type properly.
1006 // In practise I have yet to see a file that
1007 // uses this element, however it is mentioned
1008 // on page 25 of part 1 of the xmp standard.
1010 // also it seems as if exiv2 and exiftool do not support
1011 // this either (That or I misunderstand the standard)
1012 wfDebugLog( 'XMP', __METHOD__
. ' Encountered <rdf:type> which isn\'t currently supported' );
1015 if ( strpos( $elm, ' ' ) === false ) {
1016 // This probably shouldn't happen.
1017 wfDebugLog( 'XMP', __METHOD__
. " Encountered <$elm> which has no namespace. Skipping." );
1021 list( $ns, $tag ) = explode( ' ', $elm, 2 );
1023 if ( count( $this->mode
) === 0 ) {
1024 // This should not happen.
1025 throw new MWException('Error extracting XMP, '
1026 . "encountered <$elm> with no mode" );
1029 switch( $this->mode
[0] ) {
1030 case self
::MODE_IGNORE
:
1031 $this->startElementModeIgnore( $elm );
1033 case self
::MODE_SIMPLE
:
1034 $this->startElementModeSimple( $elm, $attribs );
1036 case self
::MODE_INITIAL
:
1037 $this->startElementModeInitial( $ns, $tag, $attribs );
1039 case self
::MODE_STRUCT
:
1040 $this->startElementModeStruct( $ns, $tag, $attribs );
1042 case self
::MODE_BAG
:
1043 case self
::MODE_BAGSTRUCT
:
1044 $this->startElementModeBag( $elm );
1046 case self
::MODE_SEQ
:
1047 $this->startElementModeSeq( $elm );
1049 case self
::MODE_LANG
:
1050 $this->startElementModeLang( $elm );
1052 case self
::MODE_LI_LANG
:
1053 $this->startElementModeLiLang( $elm, $attribs );
1056 $this->startElementModeLi( $elm, $attribs );
1058 case self
::MODE_QDESC
:
1059 $this->startElementModeQDesc( $elm );
1062 throw new MWException( 'StartElement in unknown mode: ' . $this->mode
[0] );
1067 * Process attributes.
1068 * Simple values can be stored as either a tag or attribute
1070 * Often the initial <rdf:Description> tag just has all the simple
1071 * properties as attributes.
1074 * <rdf:Description rdf:about="" xmlns:exif="http://ns.adobe.com/exif/1.0/" exif:DigitalZoomRatio="0/10">
1076 * @param $attribs Array attribute=>value array.
1078 private function doAttribs( $attribs ) {
1080 // first check for rdf:parseType attribute, as that can change
1081 // how the attributes are interperted.
1083 if ( isset( $attribs[self
::NS_RDF
. ' parseType'] )
1084 && $attribs[self
::NS_RDF
. ' parseType'] === 'Resource'
1085 && $this->mode
[0] === self
::MODE_SIMPLE
)
1087 // this is equivalent to having an inner rdf:Description
1088 $this->mode
[0] = self
::MODE_QDESC
;
1090 foreach ( $attribs as $name => $val ) {
1093 if ( strpos( $name, ' ' ) === false ) {
1094 // This shouldn't happen, but so far some old software forgets namespace
1096 wfDebugLog( 'XMP', __METHOD__
. ' Encountered non-namespaced attribute: '
1097 . " $name=\"$val\". Skipping. " );
1100 list( $ns, $tag ) = explode( ' ', $name, 2 );
1101 if ( $ns === self
::NS_RDF
) {
1102 if ( $tag === 'value' ||
$tag === 'resource' ) {
1103 // resource is for url.
1104 // value attribute is a weird way of just putting the contents.
1105 $this->char( $this->xmlParser
, $val );
1107 } elseif ( isset( $this->items
[$ns][$tag] ) ) {
1108 if ( $this->mode
[0] === self
::MODE_SIMPLE
) {
1109 throw new MWException( __METHOD__
1110 . " $ns:$tag found as attribute where not allowed" );
1112 $this->saveValue( $ns, $tag, $val );
1114 wfDebugLog( 'XMP', __METHOD__
. " Ignoring unrecognized element <$ns:$tag>." );
1119 * Given an extracted value, save it to results array
1121 * note also uses $this->ancestorStruct and
1122 * $this->processingArray to determine what name to
1123 * save the value under. (in addition to $tag).
1125 * @param $ns String namespace of tag this is for
1126 * @param $tag String tag name
1127 * @param $val String value to save
1129 private function saveValue( $ns, $tag, $val ) {
1131 $info =& $this->items
[$ns][$tag];
1132 $finalName = isset( $info['map_name'] )
1133 ?
$info['map_name'] : $tag;
1134 if ( isset( $info['validate'] ) ) {
1135 $validate = is_array( $info['validate'] ) ?
$info['validate']
1136 : array( 'XMPValidate', $info['validate'] );
1138 if ( is_callable( $validate ) ) {
1139 call_user_func_array( $validate, array( $info, &$val, true ) );
1140 // the reasoning behind using &$val instead of using the return value
1141 // is to be consistent between here and validating structures.
1142 if ( is_null( $val ) ) {
1143 wfDebugLog( 'XMP', __METHOD__
. " <$ns:$tag> failed validation." );
1147 wfDebugLog( 'XMP', __METHOD__
. " Validation function for $finalName ("
1148 . $validate[0] . '::' . $validate[1] . '()) is not callable.' );
1152 if ( $this->ancestorStruct
&& $this->processingArray
) {
1153 // Aka both an array and a struct. ( self::MODE_BAGSTRUCT )
1154 $this->results
['xmp-' . $info['map_group']][$this->ancestorStruct
][][$finalName] = $val;
1155 } elseif ( $this->ancestorStruct
) {
1156 $this->results
['xmp-' . $info['map_group']][$this->ancestorStruct
][$finalName] = $val;
1157 } elseif ( $this->processingArray
) {
1158 if ( $this->itemLang
=== false ) {
1160 $this->results
['xmp-' . $info['map_group']][$finalName][] = $val;
1163 $this->results
['xmp-' . $info['map_group']][$finalName][$this->itemLang
] = $val;
1166 $this->results
['xmp-' . $info['map_group']][$finalName] = $val;