3 * Reader for XMP data containing properties relevant to images.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * Class for reading xmp data containing properties relevant to
26 * images, and spitting out an array that FormatExif accepts.
28 * Note, this is not meant to recognize every possible thing you can
29 * encode in XMP. It should recognize all the properties we want.
30 * For example it doesn't have support for structures with multiple
31 * nesting levels, as none of the properties we're supporting use that
32 * feature. If it comes across properties it doesn't recognize, it should
35 * The public methods one would call in this class are
37 * Reads in xmp content.
38 * Can potentially be called multiple times with partial data each time.
39 * - parseExtended( $content )
40 * Reads XMPExtended blocks (jpeg files only).
42 * Outputs a results array.
44 * Note XMP kind of looks like rdf. They are not the same thing - XMP is
45 * encoded as a specific subset of rdf. This class can read XMP. It cannot
51 private $curItem = array(); // array to hold the current element (and previous element, and so on)
52 private $ancestorStruct = false; // the structure name when processing nested structures.
53 private $charContent = false; // temporary holder for character data that appears in xmp doc.
54 private $mode = array(); // stores the state the xmpreader is in (see MODE_FOO constants)
55 private $results = array(); // array to hold results
56 private $processingArray = false; // if we're doing a seq or bag.
57 private $itemLang = false; // used for lang alts only
60 private $charset = false;
61 private $extendedXMPOffset = 0;
66 * These are various mode constants.
67 * they are used to figure out what to do
68 * with an element when its encountered.
70 * For example, MODE_IGNORE is used when processing
71 * a property we're not interested in. So if a new
72 * element pops up when we're in that mode, we ignore it.
74 const MODE_INITIAL
= 0;
75 const MODE_IGNORE
= 1;
77 const MODE_LI_LANG
= 3;
80 // The following MODE constants are also used in the
81 // $items array to denote what type of property the item is.
82 const MODE_SIMPLE
= 10;
83 const MODE_STRUCT
= 11; // structure (associative array)
84 const MODE_SEQ
= 12; // ordered list
85 const MODE_BAG
= 13; // unordered list
87 const MODE_ALT
= 15; // non-language alt. Currently not implemented, and not needed atm.
88 const MODE_BAGSTRUCT
= 16; // A BAG of Structs.
90 const NS_RDF
= 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
91 const NS_XML
= 'http://www.w3.org/XML/1998/namespace';
96 * Primary job is to initialize the XMLParser
98 function __construct() {
100 if ( !function_exists( 'xml_parser_create_ns' ) ) {
101 // this should already be checked by this point
102 throw new MWException( 'XMP support requires XML Parser' );
105 $this->items
= XMPInfo
::getItems();
107 $this->resetXMLParser();
111 * Main use is if a single item has multiple xmp documents describing it.
112 * For example in jpeg's with extendedXMP
114 private function resetXMLParser() {
116 if ( $this->xmlParser
) {
118 xml_parser_free( $this->xmlParser
);
121 $this->xmlParser
= xml_parser_create_ns( 'UTF-8', ' ' );
122 xml_parser_set_option( $this->xmlParser
, XML_OPTION_CASE_FOLDING
, 0 );
123 xml_parser_set_option( $this->xmlParser
, XML_OPTION_SKIP_WHITE
, 1 );
125 xml_set_element_handler( $this->xmlParser
,
126 array( $this, 'startElement' ),
127 array( $this, 'endElement' ) );
129 xml_set_character_data_handler( $this->xmlParser
, array( $this, 'char' ) );
132 /** Destroy the xml parser
134 * Not sure if this is actually needed.
136 function __destruct() {
137 // not sure if this is needed.
138 xml_parser_free( $this->xmlParser
);
141 /** Get the result array. Do some post-processing before returning
142 * the array, and transform any metadata that is special-cased.
144 * @return Array array of results as an array of arrays suitable for
145 * FormatMetadata::getFormattedData().
147 public function getResults() {
148 // xmp-special is for metadata that affects how stuff
149 // is extracted. For example xmpNote:HasExtendedXMP.
151 // It is also used to handle photoshop:AuthorsPosition
152 // which is weird and really part of another property,
153 // see 2:85 in IPTC. See also pg 21 of IPTC4XMP standard.
154 // The location fields also use it.
156 $data = $this->results
;
158 wfRunHooks( 'XMPGetResults', Array( &$data ) );
160 if ( isset( $data['xmp-special']['AuthorsPosition'] )
161 && is_string( $data['xmp-special']['AuthorsPosition'] )
162 && isset( $data['xmp-general']['Artist'][0] )
164 // Note, if there is more than one creator,
165 // this only applies to first. This also will
166 // only apply to the dc:Creator prop, not the
169 $data['xmp-general']['Artist'][0] =
170 $data['xmp-special']['AuthorsPosition'] . ', '
171 . $data['xmp-general']['Artist'][0];
174 // Go through the LocationShown and LocationCreated
175 // changing it to the non-hierarchal form used by
176 // the other location fields.
178 if ( isset( $data['xmp-special']['LocationShown'][0] )
179 && is_array( $data['xmp-special']['LocationShown'][0] )
181 // the is_array is just paranoia. It should always
183 foreach( $data['xmp-special']['LocationShown'] as $loc ) {
184 if ( !is_array( $loc ) ) {
185 // To avoid copying over the _type meta-fields.
188 foreach( $loc as $field => $val ) {
189 $data['xmp-general'][$field . 'Dest'][] = $val;
193 if ( isset( $data['xmp-special']['LocationCreated'][0] )
194 && is_array( $data['xmp-special']['LocationCreated'][0] )
196 // the is_array is just paranoia. It should always
198 foreach( $data['xmp-special']['LocationCreated'] as $loc ) {
199 if ( !is_array( $loc ) ) {
200 // To avoid copying over the _type meta-fields.
203 foreach( $loc as $field => $val ) {
204 $data['xmp-general'][$field . 'Created'][] = $val;
209 // We don't want to return the special values, since they're
210 // special and not info to be stored about the file.
211 unset( $data['xmp-special'] );
213 // Convert GPSAltitude to negative if below sea level.
214 if ( isset( $data['xmp-exif']['GPSAltitudeRef'] )
215 && isset( $data['xmp-exif']['GPSAltitude'] )
218 // Must convert to a real before multiplying by -1
219 // XMPValidate guarantees there will always be a '/' in this value.
220 list( $nom, $denom ) = explode( '/', $data['xmp-exif']['GPSAltitude'] );
221 $data['xmp-exif']['GPSAltitude'] = $nom / $denom;
223 if ( $data['xmp-exif']['GPSAltitudeRef'] == '1' ) {
224 $data['xmp-exif']['GPSAltitude'] *= -1;
226 unset( $data['xmp-exif']['GPSAltitudeRef'] );
233 * Main function to call to parse XMP. Use getResults to
236 * Also catches any errors during processing, writes them to
237 * debug log, blanks result array and returns false.
239 * @param string $content XMP data
240 * @param $allOfIt Boolean: If this is all the data (true) or if its split up (false). Default true
241 * @param $reset Boolean: does xml parser need to be reset. Default false
242 * @throws MWException
243 * @return Boolean success.
245 public function parse( $content, $allOfIt = true, $reset = false ) {
247 $this->resetXMLParser();
251 // detect encoding by looking for BOM which is supposed to be in processing instruction.
252 // see page 12 of http://www.adobe.com/devnet/xmp/pdfs/XMPSpecificationPart3.pdf
253 if ( !$this->charset
) {
255 if ( preg_match( '/\xEF\xBB\xBF|\xFE\xFF|\x00\x00\xFE\xFF|\xFF\xFE\x00\x00|\xFF\xFE/',
260 $this->charset
= 'UTF-16BE';
263 $this->charset
= 'UTF-16LE';
265 case "\x00\x00\xFE\xFF":
266 $this->charset
= 'UTF-32BE';
268 case "\xFF\xFE\x00\x00":
269 $this->charset
= 'UTF-32LE';
272 $this->charset
= 'UTF-8';
275 //this should be impossible to get to
276 throw new MWException( "Invalid BOM" );
279 // standard specifically says, if no bom assume utf-8
280 $this->charset
= 'UTF-8';
283 if ( $this->charset
!== 'UTF-8' ) {
284 //don't convert if already utf-8
285 wfSuppressWarnings();
286 $content = iconv( $this->charset
, 'UTF-8//IGNORE', $content );
290 $ok = xml_parse( $this->xmlParser
, $content, $allOfIt );
292 $error = xml_error_string( xml_get_error_code( $this->xmlParser
) );
293 $where = 'line: ' . xml_get_current_line_number( $this->xmlParser
)
294 . ' column: ' . xml_get_current_column_number( $this->xmlParser
)
295 . ' byte offset: ' . xml_get_current_byte_index( $this->xmlParser
);
297 wfDebugLog( 'XMP', "XMPReader::parse : Error reading XMP content: $error ($where)" );
298 $this->results
= array(); // blank if error.
301 } catch ( MWException
$e ) {
302 wfDebugLog( 'XMP', 'XMP parse error: ' . $e );
303 $this->results
= array();
309 /** Entry point for XMPExtended blocks in jpeg files
311 * @todo In serious need of testing
312 * @see http://www.adobe.ge/devnet/xmp/pdfs/XMPSpecificationPart3.pdf XMP spec part 3 page 20
313 * @param string $content XMPExtended block minus the namespace signature
314 * @return Boolean If it succeeded.
316 public function parseExtended( $content ) {
317 // @todo FIXME: This is untested. Hard to find example files
318 // or programs that make such files..
319 $guid = substr( $content, 0, 32 );
320 if ( !isset( $this->results
['xmp-special']['HasExtendedXMP'] )
321 ||
$this->results
['xmp-special']['HasExtendedXMP'] !== $guid ) {
322 wfDebugLog( 'XMP', __METHOD__
. " Ignoring XMPExtended block due to wrong guid (guid= '$guid')" );
325 $len = unpack( 'Nlength/Noffset', substr( $content, 32, 8 ) );
327 if ( !$len ||
$len['length'] < 4 ||
$len['offset'] < 0 ||
$len['offset'] > $len['length'] ) {
328 wfDebugLog( 'XMP', __METHOD__
. 'Error reading extended XMP block, invalid length or offset.' );
332 // we're not very robust here. we should accept it in the wrong order. To quote
334 // "A JPEG writer should write the ExtendedXMP marker segments in order, immediately following the
335 // StandardXMP. However, the JPEG standard does not require preservation of marker segment order. A
336 // robust JPEG reader should tolerate the marker segments in any order."
338 // otoh the probability that an image will have more than 128k of metadata is rather low...
339 // so the probability that it will have > 128k, and be in the wrong order is very low...
341 if ( $len['offset'] !== $this->extendedXMPOffset
) {
342 wfDebugLog( 'XMP', __METHOD__
. 'Ignoring XMPExtended block due to wrong order. (Offset was '
343 . $len['offset'] . ' but expected ' . $this->extendedXMPOffset
. ')' );
347 if ( $len['offset'] === 0 ) {
348 // if we're starting the extended block, we've probably already
349 // done the XMPStandard block, so reset.
350 $this->resetXMLParser();
353 $this->extendedXMPOffset +
= $len['length'];
355 $actualContent = substr( $content, 40 );
357 if ( $this->extendedXMPOffset
=== strlen( $actualContent ) ) {
363 wfDebugLog( 'XMP', __METHOD__
. 'Parsing a XMPExtended block' );
364 return $this->parse( $actualContent, $atEnd );
368 * Character data handler
369 * Called whenever character data is found in the xmp document.
371 * does nothing if we're in MODE_IGNORE or if the data is whitespace
372 * throws an error if we're not in MODE_SIMPLE (as we're not allowed to have character
373 * data in the other modes).
375 * As an example, this happens when we encounter XMP like:
376 * <exif:DigitalZoomRatio>0/10</exif:DigitalZoomRatio>
377 * and are processing the 0/10 bit.
379 * @param $parser XMLParser reference to the xml parser
380 * @param string $data Character data
381 * @throws MWException on invalid data
383 function char( $parser, $data ) {
385 $data = trim( $data );
386 if ( trim( $data ) === "" ) {
390 if ( !isset( $this->mode
[0] ) ) {
391 throw new MWException( 'Unexpected character data before first rdf:Description element' );
394 if ( $this->mode
[0] === self
::MODE_IGNORE
) return;
396 if ( $this->mode
[0] !== self
::MODE_SIMPLE
397 && $this->mode
[0] !== self
::MODE_QDESC
399 throw new MWException( 'character data where not expected. (mode ' . $this->mode
[0] . ')' );
402 // to check, how does this handle w.s.
403 if ( $this->charContent
=== false ) {
404 $this->charContent
= $data;
406 $this->charContent
.= $data;
411 /** When we hit a closing element in MODE_IGNORE
412 * Check to see if this is the element we started to ignore,
413 * in which case we get out of MODE_IGNORE
415 * @param string $elm Namespace of element followed by a space and then tag name of element.
417 private function endElementModeIgnore( $elm ) {
418 if ( $this->curItem
[0] === $elm ) {
419 array_shift( $this->curItem
);
420 array_shift( $this->mode
);
425 * Hit a closing element when in MODE_SIMPLE.
426 * This generally means that we finished processing a
427 * property value, and now have to save the result to the
430 * For example, when processing:
431 * <exif:DigitalZoomRatio>0/10</exif:DigitalZoomRatio>
432 * this deals with when we hit </exif:DigitalZoomRatio>.
434 * Or it could be if we hit the end element of a property
435 * of a compound data structure (like a member of an array).
437 * @param string $elm namespace, space, and tag name.
439 private function endElementModeSimple( $elm ) {
440 if ( $this->charContent
!== false ) {
441 if ( $this->processingArray
) {
442 // if we're processing an array, use the original element
443 // name instead of rdf:li.
444 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
446 list( $ns, $tag ) = explode( ' ', $elm, 2 );
448 $this->saveValue( $ns, $tag, $this->charContent
);
450 $this->charContent
= false; // reset
452 array_shift( $this->curItem
);
453 array_shift( $this->mode
);
458 * Hit a closing element in MODE_STRUCT, MODE_SEQ, MODE_BAG
459 * generally means we've finished processing a nested structure.
460 * resets some internal variables to indicate that.
462 * Note this means we hit the closing element not the "</rdf:Seq>".
464 * @par For example, when processing:
466 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
467 * </rdf:Seq> </exif:ISOSpeedRatings>
470 * This method is called when we hit the "</exif:ISOSpeedRatings>" tag.
472 * @param string $elm namespace . space . tag name.
473 * @throws MWException
475 private function endElementNested( $elm ) {
477 /* cur item must be the same as $elm, unless if in MODE_STRUCT
478 in which case it could also be rdf:Description */
479 if ( $this->curItem
[0] !== $elm
480 && !( $elm === self
::NS_RDF
. ' Description'
481 && $this->mode
[0] === self
::MODE_STRUCT
)
483 throw new MWException( "nesting mismatch. got a </$elm> but expected a </" . $this->curItem
[0] . '>' );
486 // Validate structures.
487 list( $ns, $tag ) = explode( ' ', $elm, 2 );
488 if ( isset( $this->items
[$ns][$tag]['validate'] ) ) {
490 $info =& $this->items
[$ns][$tag];
491 $finalName = isset( $info['map_name'] )
492 ?
$info['map_name'] : $tag;
494 $validate = is_array( $info['validate'] ) ?
$info['validate']
495 : array( 'XMPValidate', $info['validate'] );
497 if ( !isset( $this->results
['xmp-' . $info['map_group']][$finalName] ) ) {
498 // This can happen if all the members of the struct failed validation.
499 wfDebugLog( 'XMP', __METHOD__
. " <$ns:$tag> has no valid members." );
501 } elseif ( is_callable( $validate ) ) {
502 $val =& $this->results
['xmp-' . $info['map_group']][$finalName];
503 call_user_func_array( $validate, array( $info, &$val, false ) );
504 if ( is_null( $val ) ) {
505 // the idea being the validation function will unset the variable if
507 wfDebugLog( 'XMP', __METHOD__
. " <$ns:$tag> failed validation." );
508 unset( $this->results
['xmp-' . $info['map_group']][$finalName] );
511 wfDebugLog( 'XMP', __METHOD__
. " Validation function for $finalName ("
512 . $validate[0] . '::' . $validate[1] . '()) is not callable.' );
516 array_shift( $this->curItem
);
517 array_shift( $this->mode
);
518 $this->ancestorStruct
= false;
519 $this->processingArray
= false;
520 $this->itemLang
= false;
524 * Hit a closing element in MODE_LI (either rdf:Seq, or rdf:Bag )
525 * Add information about what type of element this is.
527 * Note we still have to hit the outer "</property>"
529 * @par For example, when processing:
531 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
532 * </rdf:Seq> </exif:ISOSpeedRatings>
535 * This method is called when we hit the "</rdf:Seq>".
536 * (For comparison, we call endElementModeSimple when we
537 * hit the "</rdf:li>")
539 * @param string $elm namespace . ' ' . element name
540 * @throws MWException
542 private function endElementModeLi( $elm ) {
544 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
545 $info = $this->items
[$ns][$tag];
546 $finalName = isset( $info['map_name'] )
547 ?
$info['map_name'] : $tag;
549 array_shift( $this->mode
);
551 if ( !isset( $this->results
['xmp-' . $info['map_group']][$finalName] ) ) {
552 wfDebugLog( 'XMP', __METHOD__
. " Empty compund element $finalName." );
556 if ( $elm === self
::NS_RDF
. ' Seq' ) {
557 $this->results
['xmp-' . $info['map_group']][$finalName]['_type'] = 'ol';
558 } elseif ( $elm === self
::NS_RDF
. ' Bag' ) {
559 $this->results
['xmp-' . $info['map_group']][$finalName]['_type'] = 'ul';
560 } elseif ( $elm === self
::NS_RDF
. ' Alt' ) {
561 // extra if needed as you could theoretically have a non-language alt.
562 if ( $info['mode'] === self
::MODE_LANG
) {
563 $this->results
['xmp-' . $info['map_group']][$finalName]['_type'] = 'lang';
567 throw new MWException( __METHOD__
. " expected </rdf:seq> or </rdf:bag> but instead got $elm." );
572 * End element while in MODE_QDESC
573 * mostly when ending an element when we have a simple value
574 * that has qualifiers.
576 * Qualifiers aren't all that common, and we don't do anything
579 * @param string $elm namespace and element
581 private function endElementModeQDesc( $elm ) {
583 if ( $elm === self
::NS_RDF
. ' value' ) {
584 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
585 $this->saveValue( $ns, $tag, $this->charContent
);
588 array_shift( $this->mode
);
589 array_shift( $this->curItem
);
594 * Handler for hitting a closing element.
596 * generally just calls a helper function depending on what
599 * Ignores the outer wrapping elements that are optional in
600 * xmp and have no meaning.
602 * @param $parser XMLParser
603 * @param string $elm namespace . ' ' . element name
604 * @throws MWException
606 function endElement( $parser, $elm ) {
607 if ( $elm === ( self
::NS_RDF
. ' RDF' )
608 ||
$elm === 'adobe:ns:meta/ xmpmeta'
609 ||
$elm === 'adobe:ns:meta/ xapmeta' )
615 if ( $elm === self
::NS_RDF
. ' type' ) {
616 // these aren't really supported properly yet.
617 // However, it appears they almost never used.
618 wfDebugLog( 'XMP', __METHOD__
. ' encountered <rdf:type>' );
621 if ( strpos( $elm, ' ' ) === false ) {
622 // This probably shouldn't happen.
623 // However, there is a bug in an adobe product
624 // that forgets the namespace on some things.
625 // (Luckily they are unimportant things).
626 wfDebugLog( 'XMP', __METHOD__
. " Encountered </$elm> which has no namespace. Skipping." );
630 if ( count( $this->mode
[0] ) === 0 ) {
631 // This should never ever happen and means
632 // there is a pretty major bug in this class.
633 throw new MWException( 'Encountered end element with no mode' );
636 if ( count( $this->curItem
) == 0 && $this->mode
[0] !== self
::MODE_INITIAL
) {
637 // just to be paranoid. Should always have a curItem, except for initially
638 // (aka during MODE_INITAL).
639 throw new MWException( "Hit end element </$elm> but no curItem" );
642 switch( $this->mode
[0] ) {
643 case self
::MODE_IGNORE
:
644 $this->endElementModeIgnore( $elm );
646 case self
::MODE_SIMPLE
:
647 $this->endElementModeSimple( $elm );
649 case self
::MODE_STRUCT
:
652 case self
::MODE_LANG
:
653 case self
::MODE_BAGSTRUCT
:
654 $this->endElementNested( $elm );
656 case self
::MODE_INITIAL
:
657 if ( $elm === self
::NS_RDF
. ' Description' ) {
658 array_shift( $this->mode
);
660 throw new MWException( 'Element ended unexpectedly while in MODE_INITIAL' );
664 case self
::MODE_LI_LANG
:
665 $this->endElementModeLi( $elm );
667 case self
::MODE_QDESC
:
668 $this->endElementModeQDesc( $elm );
671 wfDebugLog( 'XMP', __METHOD__
. " no mode (elm = $elm)" );
677 * Hit an opening element while in MODE_IGNORE
679 * XMP is extensible, so ignore any tag we don't understand.
681 * Mostly ignores, unless we encounter the element that we are ignoring.
682 * in which case we add it to the item stack, so we can ignore things
683 * that are nested, correctly.
685 * @param string $elm namespace . ' ' . tag name
687 private function startElementModeIgnore( $elm ) {
688 if ( $elm === $this->curItem
[0] ) {
689 array_unshift( $this->curItem
, $elm );
690 array_unshift( $this->mode
, self
::MODE_IGNORE
);
695 * Start element in MODE_BAG (unordered array)
696 * this should always be <rdf:Bag>
698 * @param string $elm namespace . ' ' . tag
699 * @throws MWException if we have an element that's not <rdf:Bag>
701 private function startElementModeBag( $elm ) {
702 if ( $elm === self
::NS_RDF
. ' Bag' ) {
703 array_unshift( $this->mode
, self
::MODE_LI
);
705 throw new MWException( "Expected <rdf:Bag> but got $elm." );
711 * Start element in MODE_SEQ (ordered array)
712 * this should always be <rdf:Seq>
714 * @param string $elm namespace . ' ' . tag
715 * @throws MWException if we have an element that's not <rdf:Seq>
717 private function startElementModeSeq( $elm ) {
718 if ( $elm === self
::NS_RDF
. ' Seq' ) {
719 array_unshift( $this->mode
, self
::MODE_LI
);
720 } elseif ( $elm === self
::NS_RDF
. ' Bag' ) {
722 wfDebugLog( 'XMP', __METHOD__
. ' Expected an rdf:Seq, but got an rdf:Bag. Pretending'
723 . ' it is a Seq, since some buggy software is known to screw this up.' );
724 array_unshift( $this->mode
, self
::MODE_LI
);
726 throw new MWException( "Expected <rdf:Seq> but got $elm." );
732 * Start element in MODE_LANG (language alternative)
733 * this should always be <rdf:Alt>
735 * This tag tends to be used for metadata like describe this
736 * picture, which can be translated into multiple languages.
738 * XMP supports non-linguistic alternative selections,
739 * which are really only used for thumbnails, which
740 * we don't care about.
742 * @param string $elm namespace . ' ' . tag
743 * @throws MWException if we have an element that's not <rdf:Alt>
745 private function startElementModeLang( $elm ) {
746 if ( $elm === self
::NS_RDF
. ' Alt' ) {
747 array_unshift( $this->mode
, self
::MODE_LI_LANG
);
749 throw new MWException( "Expected <rdf:Seq> but got $elm." );
755 * Handle an opening element when in MODE_SIMPLE
757 * This should not happen often. This is for if a simple element
758 * already opened has a child element. Could happen for a
762 * <exif:DigitalZoomRatio><rdf:Description><rdf:value>0/10</rdf:value>
763 * <foo:someQualifier>Bar</foo:someQualifier> </rdf:Description>
764 * </exif:DigitalZoomRatio>
766 * This method is called when processing the <rdf:Description> element
768 * @param string $elm namespace and tag names separated by space.
769 * @param array $attribs Attributes of the element.
770 * @throws MWException
772 private function startElementModeSimple( $elm, $attribs ) {
773 if ( $elm === self
::NS_RDF
. ' Description' ) {
774 // If this value has qualifiers
775 array_unshift( $this->mode
, self
::MODE_QDESC
);
776 array_unshift( $this->curItem
, $this->curItem
[0] );
778 if ( isset( $attribs[self
::NS_RDF
. ' value'] ) ) {
779 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
780 $this->saveValue( $ns, $tag, $attribs[self
::NS_RDF
. ' value'] );
782 } elseif ( $elm === self
::NS_RDF
. ' value' ) {
783 // This should not be here.
784 throw new MWException( __METHOD__
. ' Encountered <rdf:value> where it was unexpected.' );
787 // something else we don't recognize, like a qualifier maybe.
788 wfDebugLog( 'XMP', __METHOD__
. " Encountered element <$elm> where only expecting character data as value of " . $this->curItem
[0] );
789 array_unshift( $this->mode
, self
::MODE_IGNORE
);
790 array_unshift( $this->curItem
, $elm );
797 * Start an element when in MODE_QDESC.
798 * This generally happens when a simple element has an inner
799 * rdf:Description to hold qualifier elements.
802 * <exif:DigitalZoomRatio><rdf:Description><rdf:value>0/10</rdf:value>
803 * <foo:someQualifier>Bar</foo:someQualifier> </rdf:Description>
804 * </exif:DigitalZoomRatio>
805 * Called when processing the <rdf:value> or <foo:someQualifier>.
807 * @param string $elm namespace and tag name separated by a space.
810 private function startElementModeQDesc( $elm ) {
811 if ( $elm === self
::NS_RDF
. ' value' ) {
812 return; // do nothing
814 // otherwise its a qualifier, which we ignore
815 array_unshift( $this->mode
, self
::MODE_IGNORE
);
816 array_unshift( $this->curItem
, $elm );
821 * Starting an element when in MODE_INITIAL
822 * This usually happens when we hit an element inside
823 * the outer rdf:Description
825 * This is generally where most properties start.
827 * @param string $ns Namespace
828 * @param string $tag tag name (without namespace prefix)
829 * @param array $attribs array of attributes
830 * @throws MWException
832 private function startElementModeInitial( $ns, $tag, $attribs ) {
833 if ( $ns !== self
::NS_RDF
) {
835 if ( isset( $this->items
[$ns][$tag] ) ) {
836 if ( isset( $this->items
[$ns][$tag]['structPart'] ) ) {
837 // If this element is supposed to appear only as
838 // a child of a structure, but appears here (not as
839 // a child of a struct), then something weird is
840 // happening, so ignore this element and its children.
842 wfDebugLog( 'XMP', "Encountered <$ns:$tag> outside"
843 . " of its expected parent. Ignoring." );
845 array_unshift( $this->mode
, self
::MODE_IGNORE
);
846 array_unshift( $this->curItem
, $ns . ' ' . $tag );
849 $mode = $this->items
[$ns][$tag]['mode'];
850 array_unshift( $this->mode
, $mode );
851 array_unshift( $this->curItem
, $ns . ' ' . $tag );
852 if ( $mode === self
::MODE_STRUCT
) {
853 $this->ancestorStruct
= isset( $this->items
[$ns][$tag]['map_name'] )
854 ?
$this->items
[$ns][$tag]['map_name'] : $tag;
856 if ( $this->charContent
!== false ) {
858 // Should not happen in valid XMP.
859 throw new MWException( 'tag nested in non-whitespace characters.' );
862 // This element is not on our list of allowed elements so ignore.
863 wfDebugLog( 'XMP', __METHOD__
. " Ignoring unrecognized element <$ns:$tag>." );
864 array_unshift( $this->mode
, self
::MODE_IGNORE
);
865 array_unshift( $this->curItem
, $ns . ' ' . $tag );
870 // process attributes
871 $this->doAttribs( $attribs );
875 * Hit an opening element when in a Struct (MODE_STRUCT)
876 * This is generally for fields of a compound property.
878 * Example of a struct (abbreviated; flash has more properties):
880 * <exif:Flash> <rdf:Description> <exif:Fired>True</exif:Fired>
881 * <exif:Mode>1</exif:Mode></rdf:Description></exif:Flash>
885 * <exif:Flash rdf:parseType='Resource'> <exif:Fired>True</exif:Fired>
886 * <exif:Mode>1</exif:Mode></exif:Flash>
888 * @param string $ns namespace
889 * @param string $tag tag name (no ns)
890 * @param array $attribs array of attribs w/ values.
891 * @throws MWException
893 private function startElementModeStruct( $ns, $tag, $attribs ) {
894 if ( $ns !== self
::NS_RDF
) {
896 if ( isset( $this->items
[$ns][$tag] ) ) {
897 if ( isset( $this->items
[$ns][$this->ancestorStruct
]['children'] )
898 && !isset( $this->items
[$ns][$this->ancestorStruct
]['children'][$tag] ) )
900 // This assumes that we don't have inter-namespace nesting
901 // which we don't in all the properties we're interested in.
902 throw new MWException( " <$tag> appeared nested in <" . $this->ancestorStruct
903 . "> where it is not allowed." );
905 array_unshift( $this->mode
, $this->items
[$ns][$tag]['mode'] );
906 array_unshift( $this->curItem
, $ns . ' ' . $tag );
907 if ( $this->charContent
!== false ) {
909 // Should not happen in valid XMP.
910 throw new MWException( "tag <$tag> nested in non-whitespace characters (" . $this->charContent
. ")." );
913 array_unshift( $this->mode
, self
::MODE_IGNORE
);
914 array_unshift( $this->curItem
, $elm );
920 if ( $ns === self
::NS_RDF
&& $tag === 'Description' ) {
921 $this->doAttribs( $attribs );
922 array_unshift( $this->mode
, self
::MODE_STRUCT
);
923 array_unshift( $this->curItem
, $this->curItem
[0] );
928 * opening element in MODE_LI
929 * process elements of arrays.
932 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
933 * </rdf:Seq> </exif:ISOSpeedRatings>
934 * This method is called when we hit the <rdf:li> element.
936 * @param string $elm namespace . ' ' . tagname
937 * @param array $attribs Attributes. (needed for BAGSTRUCTS)
938 * @throws MWException if gets a tag other than <rdf:li>
940 private function startElementModeLi( $elm, $attribs ) {
941 if ( ( $elm ) !== self
::NS_RDF
. ' li' ) {
942 throw new MWException( "<rdf:li> expected but got $elm." );
945 if ( !isset( $this->mode
[1] ) ) {
946 // This should never ever ever happen. Checking for it
948 throw new MWException( 'In mode Li, but no 2xPrevious mode!' );
951 if ( $this->mode
[1] === self
::MODE_BAGSTRUCT
) {
952 // This list item contains a compound (STRUCT) value.
953 array_unshift( $this->mode
, self
::MODE_STRUCT
);
954 array_unshift( $this->curItem
, $elm );
955 $this->processingArray
= true;
957 if ( !isset( $this->curItem
[1] ) ) {
959 throw new MWException( 'Can not find parent of BAGSTRUCT.' );
961 list( $curNS, $curTag ) = explode( ' ', $this->curItem
[1] );
962 $this->ancestorStruct
= isset( $this->items
[$curNS][$curTag]['map_name'] )
963 ?
$this->items
[$curNS][$curTag]['map_name'] : $curTag;
965 $this->doAttribs( $attribs );
968 // Normal BAG or SEQ containing simple values.
969 array_unshift( $this->mode
, self
::MODE_SIMPLE
);
970 // need to add curItem[0] on again since one is for the specific item
971 // and one is for the entire group.
972 array_unshift( $this->curItem
, $this->curItem
[0] );
973 $this->processingArray
= true;
979 * Opening element in MODE_LI_LANG.
980 * process elements of language alternatives
983 * <dc:title> <rdf:Alt> <rdf:li xml:lang="x-default">My house
984 * </rdf:li> </rdf:Alt> </dc:title>
986 * This method is called when we hit the <rdf:li> element.
988 * @param string $elm namespace . ' ' . tag
989 * @param array $attribs array of elements (most importantly xml:lang)
990 * @throws MWException if gets a tag other than <rdf:li> or if no xml:lang
992 private function startElementModeLiLang( $elm, $attribs ) {
993 if ( $elm !== self
::NS_RDF
. ' li' ) {
994 throw new MWException( __METHOD__
. " <rdf:li> expected but got $elm." );
996 if ( !isset( $attribs[self
::NS_XML
. ' lang'] )
997 ||
!preg_match( '/^[-A-Za-z0-9]{2,}$/D', $attribs[self
::NS_XML
. ' lang'] ) )
999 throw new MWException( __METHOD__
1000 . " <rdf:li> did not contain, or has invalid xml:lang attribute in lang alternative" );
1003 // Lang is case-insensitive.
1004 $this->itemLang
= strtolower( $attribs[self
::NS_XML
. ' lang'] );
1006 // need to add curItem[0] on again since one is for the specific item
1007 // and one is for the entire group.
1008 array_unshift( $this->curItem
, $this->curItem
[0] );
1009 array_unshift( $this->mode
, self
::MODE_SIMPLE
);
1010 $this->processingArray
= true;
1014 * Hits an opening element.
1015 * Generally just calls a helper based on what MODE we're in.
1016 * Also does some initial set up for the wrapper element
1018 * @param $parser XMLParser
1019 * @param string $elm namespace "<space>" element
1020 * @param array $attribs attribute name => value
1021 * @throws MWException
1023 function startElement( $parser, $elm, $attribs ) {
1025 if ( $elm === self
::NS_RDF
. ' RDF'
1026 ||
$elm === 'adobe:ns:meta/ xmpmeta'
1027 ||
$elm === 'adobe:ns:meta/ xapmeta' )
1031 } elseif ( $elm === self
::NS_RDF
. ' Description' ) {
1032 if ( count( $this->mode
) === 0 ) {
1034 array_unshift( $this->mode
, self
::MODE_INITIAL
);
1036 } elseif ( $elm === self
::NS_RDF
. ' type' ) {
1037 // This doesn't support rdf:type properly.
1038 // In practise I have yet to see a file that
1039 // uses this element, however it is mentioned
1040 // on page 25 of part 1 of the xmp standard.
1042 // also it seems as if exiv2 and exiftool do not support
1043 // this either (That or I misunderstand the standard)
1044 wfDebugLog( 'XMP', __METHOD__
. ' Encountered <rdf:type> which isn\'t currently supported' );
1047 if ( strpos( $elm, ' ' ) === false ) {
1048 // This probably shouldn't happen.
1049 wfDebugLog( 'XMP', __METHOD__
. " Encountered <$elm> which has no namespace. Skipping." );
1053 list( $ns, $tag ) = explode( ' ', $elm, 2 );
1055 if ( count( $this->mode
) === 0 ) {
1056 // This should not happen.
1057 throw new MWException( 'Error extracting XMP, '
1058 . "encountered <$elm> with no mode" );
1061 switch( $this->mode
[0] ) {
1062 case self
::MODE_IGNORE
:
1063 $this->startElementModeIgnore( $elm );
1065 case self
::MODE_SIMPLE
:
1066 $this->startElementModeSimple( $elm, $attribs );
1068 case self
::MODE_INITIAL
:
1069 $this->startElementModeInitial( $ns, $tag, $attribs );
1071 case self
::MODE_STRUCT
:
1072 $this->startElementModeStruct( $ns, $tag, $attribs );
1074 case self
::MODE_BAG
:
1075 case self
::MODE_BAGSTRUCT
:
1076 $this->startElementModeBag( $elm );
1078 case self
::MODE_SEQ
:
1079 $this->startElementModeSeq( $elm );
1081 case self
::MODE_LANG
:
1082 $this->startElementModeLang( $elm );
1084 case self
::MODE_LI_LANG
:
1085 $this->startElementModeLiLang( $elm, $attribs );
1088 $this->startElementModeLi( $elm, $attribs );
1090 case self
::MODE_QDESC
:
1091 $this->startElementModeQDesc( $elm );
1094 throw new MWException( 'StartElement in unknown mode: ' . $this->mode
[0] );
1099 * Process attributes.
1100 * Simple values can be stored as either a tag or attribute
1102 * Often the initial "<rdf:Description>" tag just has all the simple
1103 * properties as attributes.
1107 * <rdf:Description rdf:about="" xmlns:exif="http://ns.adobe.com/exif/1.0/" exif:DigitalZoomRatio="0/10">
1110 * @param array $attribs attribute=>value array.
1111 * @throws MWException
1113 private function doAttribs( $attribs ) {
1115 // first check for rdf:parseType attribute, as that can change
1116 // how the attributes are interperted.
1118 if ( isset( $attribs[self
::NS_RDF
. ' parseType'] )
1119 && $attribs[self
::NS_RDF
. ' parseType'] === 'Resource'
1120 && $this->mode
[0] === self
::MODE_SIMPLE
)
1122 // this is equivalent to having an inner rdf:Description
1123 $this->mode
[0] = self
::MODE_QDESC
;
1125 foreach ( $attribs as $name => $val ) {
1126 if ( strpos( $name, ' ' ) === false ) {
1127 // This shouldn't happen, but so far some old software forgets namespace
1129 wfDebugLog( 'XMP', __METHOD__
. ' Encountered non-namespaced attribute: '
1130 . " $name=\"$val\". Skipping. " );
1133 list( $ns, $tag ) = explode( ' ', $name, 2 );
1134 if ( $ns === self
::NS_RDF
) {
1135 if ( $tag === 'value' ||
$tag === 'resource' ) {
1136 // resource is for url.
1137 // value attribute is a weird way of just putting the contents.
1138 $this->char( $this->xmlParser
, $val );
1140 } elseif ( isset( $this->items
[$ns][$tag] ) ) {
1141 if ( $this->mode
[0] === self
::MODE_SIMPLE
) {
1142 throw new MWException( __METHOD__
1143 . " $ns:$tag found as attribute where not allowed" );
1145 $this->saveValue( $ns, $tag, $val );
1147 wfDebugLog( 'XMP', __METHOD__
. " Ignoring unrecognized element <$ns:$tag>." );
1153 * Given an extracted value, save it to results array
1155 * note also uses $this->ancestorStruct and
1156 * $this->processingArray to determine what name to
1157 * save the value under. (in addition to $tag).
1159 * @param string $ns namespace of tag this is for
1160 * @param string $tag tag name
1161 * @param string $val value to save
1163 private function saveValue( $ns, $tag, $val ) {
1165 $info =& $this->items
[$ns][$tag];
1166 $finalName = isset( $info['map_name'] )
1167 ?
$info['map_name'] : $tag;
1168 if ( isset( $info['validate'] ) ) {
1169 $validate = is_array( $info['validate'] ) ?
$info['validate']
1170 : array( 'XMPValidate', $info['validate'] );
1172 if ( is_callable( $validate ) ) {
1173 call_user_func_array( $validate, array( $info, &$val, true ) );
1174 // the reasoning behind using &$val instead of using the return value
1175 // is to be consistent between here and validating structures.
1176 if ( is_null( $val ) ) {
1177 wfDebugLog( 'XMP', __METHOD__
. " <$ns:$tag> failed validation." );
1181 wfDebugLog( 'XMP', __METHOD__
. " Validation function for $finalName ("
1182 . $validate[0] . '::' . $validate[1] . '()) is not callable.' );
1186 if ( $this->ancestorStruct
&& $this->processingArray
) {
1187 // Aka both an array and a struct. ( self::MODE_BAGSTRUCT )
1188 $this->results
['xmp-' . $info['map_group']][$this->ancestorStruct
][][$finalName] = $val;
1189 } elseif ( $this->ancestorStruct
) {
1190 $this->results
['xmp-' . $info['map_group']][$this->ancestorStruct
][$finalName] = $val;
1191 } elseif ( $this->processingArray
) {
1192 if ( $this->itemLang
=== false ) {
1194 $this->results
['xmp-' . $info['map_group']][$finalName][] = $val;
1197 $this->results
['xmp-' . $info['map_group']][$finalName][$this->itemLang
] = $val;
1200 $this->results
['xmp-' . $info['map_group']][$finalName] = $val;