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';
97 * Primary job is to initialize the XMLParser
99 function __construct() {
101 if ( !function_exists( 'xml_parser_create_ns' ) ) {
102 // this should already be checked by this point
103 throw new MWException( 'XMP support requires XML Parser' );
106 $this->items
= XMPInfo
::getItems();
108 $this->resetXMLParser();
112 * Main use is if a single item has multiple xmp documents describing it.
113 * For example in jpeg's with extendedXMP
115 private function resetXMLParser() {
117 if ( $this->xmlParser
) {
119 xml_parser_free( $this->xmlParser
);
122 $this->xmlParser
= xml_parser_create_ns( 'UTF-8', ' ' );
123 xml_parser_set_option( $this->xmlParser
, XML_OPTION_CASE_FOLDING
, 0 );
124 xml_parser_set_option( $this->xmlParser
, XML_OPTION_SKIP_WHITE
, 1 );
126 xml_set_element_handler( $this->xmlParser
,
127 array( $this, 'startElement' ),
128 array( $this, 'endElement' ) );
130 xml_set_character_data_handler( $this->xmlParser
, array( $this, 'char' ) );
133 /** Destroy the xml parser
135 * Not sure if this is actually needed.
137 function __destruct() {
138 // not sure if this is needed.
139 xml_parser_free( $this->xmlParser
);
142 /** Get the result array. Do some post-processing before returning
143 * the array, and transform any metadata that is special-cased.
145 * @return Array array of results as an array of arrays suitable for
146 * FormatMetadata::getFormattedData().
148 public function getResults() {
149 // xmp-special is for metadata that affects how stuff
150 // is extracted. For example xmpNote:HasExtendedXMP.
152 // It is also used to handle photoshop:AuthorsPosition
153 // which is weird and really part of another property,
154 // see 2:85 in IPTC. See also pg 21 of IPTC4XMP standard.
155 // The location fields also use it.
157 $data = $this->results
;
159 wfRunHooks( 'XMPGetResults', Array( &$data ) );
161 if ( isset( $data['xmp-special']['AuthorsPosition'] )
162 && is_string( $data['xmp-special']['AuthorsPosition'] )
163 && isset( $data['xmp-general']['Artist'][0] )
165 // Note, if there is more than one creator,
166 // this only applies to first. This also will
167 // only apply to the dc:Creator prop, not the
170 $data['xmp-general']['Artist'][0] =
171 $data['xmp-special']['AuthorsPosition'] . ', '
172 . $data['xmp-general']['Artist'][0];
175 // Go through the LocationShown and LocationCreated
176 // changing it to the non-hierarchal form used by
177 // the other location fields.
179 if ( isset( $data['xmp-special']['LocationShown'][0] )
180 && is_array( $data['xmp-special']['LocationShown'][0] )
182 // the is_array is just paranoia. It should always
184 foreach( $data['xmp-special']['LocationShown'] as $loc ) {
185 if ( !is_array( $loc ) ) {
186 // To avoid copying over the _type meta-fields.
189 foreach( $loc as $field => $val ) {
190 $data['xmp-general'][$field . 'Dest'][] = $val;
194 if ( isset( $data['xmp-special']['LocationCreated'][0] )
195 && is_array( $data['xmp-special']['LocationCreated'][0] )
197 // the is_array is just paranoia. It should always
199 foreach( $data['xmp-special']['LocationCreated'] as $loc ) {
200 if ( !is_array( $loc ) ) {
201 // To avoid copying over the _type meta-fields.
204 foreach( $loc as $field => $val ) {
205 $data['xmp-general'][$field . 'Created'][] = $val;
211 // We don't want to return the special values, since they're
212 // special and not info to be stored about the file.
213 unset( $data['xmp-special'] );
215 // Convert GPSAltitude to negative if below sea level.
216 if ( isset( $data['xmp-exif']['GPSAltitudeRef'] )
217 && isset( $data['xmp-exif']['GPSAltitude'] )
220 // Must convert to a real before multiplying by -1
221 // XMPValidate guarantees there will always be a '/' in this value.
222 list( $nom, $denom ) = explode( '/', $data['xmp-exif']['GPSAltitude'] );
223 $data['xmp-exif']['GPSAltitude'] = $nom / $denom;
225 if ( $data['xmp-exif']['GPSAltitudeRef'] == '1' ) {
226 $data['xmp-exif']['GPSAltitude'] *= -1;
228 unset( $data['xmp-exif']['GPSAltitudeRef'] );
235 * Main function to call to parse XMP. Use getResults to
238 * Also catches any errors during processing, writes them to
239 * debug log, blanks result array and returns false.
241 * @param $content String: XMP data
242 * @param $allOfIt Boolean: If this is all the data (true) or if its split up (false). Default true
243 * @param $reset Boolean: does xml parser need to be reset. Default false
244 * @throws MWException
245 * @return Boolean success.
247 public function parse( $content, $allOfIt = true, $reset = false ) {
249 $this->resetXMLParser();
253 // detect encoding by looking for BOM which is supposed to be in processing instruction.
254 // see page 12 of http://www.adobe.com/devnet/xmp/pdfs/XMPSpecificationPart3.pdf
255 if ( !$this->charset
) {
257 if ( preg_match( '/\xEF\xBB\xBF|\xFE\xFF|\x00\x00\xFE\xFF|\xFF\xFE\x00\x00|\xFF\xFE/',
262 $this->charset
= 'UTF-16BE';
265 $this->charset
= 'UTF-16LE';
267 case "\x00\x00\xFE\xFF":
268 $this->charset
= 'UTF-32BE';
270 case "\xFF\xFE\x00\x00":
271 $this->charset
= 'UTF-32LE';
274 $this->charset
= 'UTF-8';
277 //this should be impossible to get to
278 throw new MWException( "Invalid BOM" );
281 // standard specifically says, if no bom assume utf-8
282 $this->charset
= 'UTF-8';
285 if ( $this->charset
!== 'UTF-8' ) {
286 //don't convert if already utf-8
287 wfSuppressWarnings();
288 $content = iconv( $this->charset
, 'UTF-8//IGNORE', $content );
292 $ok = xml_parse( $this->xmlParser
, $content, $allOfIt );
294 $error = xml_error_string( xml_get_error_code( $this->xmlParser
) );
295 $where = 'line: ' . xml_get_current_line_number( $this->xmlParser
)
296 . ' column: ' . xml_get_current_column_number( $this->xmlParser
)
297 . ' byte offset: ' . xml_get_current_byte_index( $this->xmlParser
);
299 wfDebugLog( 'XMP', "XMPReader::parse : Error reading XMP content: $error ($where)" );
300 $this->results
= array(); // blank if error.
303 } catch ( MWException
$e ) {
304 wfDebugLog( 'XMP', 'XMP parse error: ' . $e );
305 $this->results
= array();
311 /** Entry point for XMPExtended blocks in jpeg files
313 * @todo In serious need of testing
314 * @see http://www.adobe.ge/devnet/xmp/pdfs/XMPSpecificationPart3.pdf XMP spec part 3 page 20
315 * @param String $content XMPExtended block minus the namespace signature
316 * @return Boolean If it succeeded.
318 public function parseExtended( $content ) {
319 // @todo FIXME: This is untested. Hard to find example files
320 // or programs that make such files..
321 $guid = substr( $content, 0, 32 );
322 if ( !isset( $this->results
['xmp-special']['HasExtendedXMP'] )
323 ||
$this->results
['xmp-special']['HasExtendedXMP'] !== $guid ) {
324 wfDebugLog( 'XMP', __METHOD__
. " Ignoring XMPExtended block due to wrong guid (guid= '$guid')" );
327 $len = unpack( 'Nlength/Noffset', substr( $content, 32, 8 ) );
329 if ( !$len ||
$len['length'] < 4 ||
$len['offset'] < 0 ||
$len['offset'] > $len['length'] ) {
330 wfDebugLog( 'XMP', __METHOD__
. 'Error reading extended XMP block, invalid length or offset.' );
335 // we're not very robust here. we should accept it in the wrong order. To quote
337 // "A JPEG writer should write the ExtendedXMP marker segments in order, immediately following the
338 // StandardXMP. However, the JPEG standard does not require preservation of marker segment order. A
339 // robust JPEG reader should tolerate the marker segments in any order."
341 // otoh the probability that an image will have more than 128k of metadata is rather low...
342 // so the probability that it will have > 128k, and be in the wrong order is very low...
344 if ( $len['offset'] !== $this->extendedXMPOffset
) {
345 wfDebugLog( 'XMP', __METHOD__
. 'Ignoring XMPExtended block due to wrong order. (Offset was '
346 . $len['offset'] . ' but expected ' . $this->extendedXMPOffset
. ')' );
350 if ( $len['offset'] === 0 ) {
351 // if we're starting the extended block, we've probably already
352 // done the XMPStandard block, so reset.
353 $this->resetXMLParser();
356 $this->extendedXMPOffset +
= $len['length'];
358 $actualContent = substr( $content, 40 );
360 if ( $this->extendedXMPOffset
=== strlen( $actualContent ) ) {
366 wfDebugLog( 'XMP', __METHOD__
. 'Parsing a XMPExtended block' );
367 return $this->parse( $actualContent, $atEnd );
371 * Character data handler
372 * Called whenever character data is found in the xmp document.
374 * does nothing if we're in MODE_IGNORE or if the data is whitespace
375 * throws an error if we're not in MODE_SIMPLE (as we're not allowed to have character
376 * data in the other modes).
378 * As an example, this happens when we encounter XMP like:
379 * <exif:DigitalZoomRatio>0/10</exif:DigitalZoomRatio>
380 * and are processing the 0/10 bit.
382 * @param $parser XMLParser reference to the xml parser
383 * @param $data String Character data
384 * @throws MWException on invalid data
386 function char( $parser, $data ) {
388 $data = trim( $data );
389 if ( trim( $data ) === "" ) {
393 if ( !isset( $this->mode
[0] ) ) {
394 throw new MWException( 'Unexpected character data before first rdf:Description element' );
397 if ( $this->mode
[0] === self
::MODE_IGNORE
) return;
399 if ( $this->mode
[0] !== self
::MODE_SIMPLE
400 && $this->mode
[0] !== self
::MODE_QDESC
402 throw new MWException( 'character data where not expected. (mode ' . $this->mode
[0] . ')' );
405 // to check, how does this handle w.s.
406 if ( $this->charContent
=== false ) {
407 $this->charContent
= $data;
409 $this->charContent
.= $data;
414 /** When we hit a closing element in MODE_IGNORE
415 * Check to see if this is the element we started to ignore,
416 * in which case we get out of MODE_IGNORE
418 * @param $elm String Namespace of element followed by a space and then tag name of element.
420 private function endElementModeIgnore ( $elm ) {
421 if ( $this->curItem
[0] === $elm ) {
422 array_shift( $this->curItem
);
423 array_shift( $this->mode
);
428 * Hit a closing element when in MODE_SIMPLE.
429 * This generally means that we finished processing a
430 * property value, and now have to save the result to the
433 * For example, when processing:
434 * <exif:DigitalZoomRatio>0/10</exif:DigitalZoomRatio>
435 * this deals with when we hit </exif:DigitalZoomRatio>.
437 * Or it could be if we hit the end element of a property
438 * of a compound data structure (like a member of an array).
440 * @param $elm String namespace, space, and tag name.
442 private function endElementModeSimple ( $elm ) {
443 if ( $this->charContent
!== false ) {
444 if ( $this->processingArray
) {
445 // if we're processing an array, use the original element
446 // name instead of rdf:li.
447 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
449 list( $ns, $tag ) = explode( ' ', $elm, 2 );
451 $this->saveValue( $ns, $tag, $this->charContent
);
453 $this->charContent
= false; // reset
455 array_shift( $this->curItem
);
456 array_shift( $this->mode
);
461 * Hit a closing element in MODE_STRUCT, MODE_SEQ, MODE_BAG
462 * generally means we've finished processing a nested structure.
463 * resets some internal variables to indicate that.
465 * Note this means we hit the closing element not the "</rdf:Seq>".
467 * @par For example, when processing:
469 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
470 * </rdf:Seq> </exif:ISOSpeedRatings>
473 * This method is called when we hit the "</exif:ISOSpeedRatings>" tag.
475 * @param $elm String namespace . space . tag name.
476 * @throws MWException
478 private function endElementNested( $elm ) {
480 /* cur item must be the same as $elm, unless if in MODE_STRUCT
481 in which case it could also be rdf:Description */
482 if ( $this->curItem
[0] !== $elm
483 && !( $elm === self
::NS_RDF
. ' Description'
484 && $this->mode
[0] === self
::MODE_STRUCT
)
486 throw new MWException( "nesting mismatch. got a </$elm> but expected a </" . $this->curItem
[0] . '>' );
489 // Validate structures.
490 list( $ns, $tag ) = explode( ' ', $elm, 2 );
491 if ( isset( $this->items
[$ns][$tag]['validate'] ) ) {
493 $info =& $this->items
[$ns][$tag];
494 $finalName = isset( $info['map_name'] )
495 ?
$info['map_name'] : $tag;
497 $validate = is_array( $info['validate'] ) ?
$info['validate']
498 : array( 'XMPValidate', $info['validate'] );
500 if ( !isset( $this->results
['xmp-' . $info['map_group']][$finalName] ) ) {
501 // This can happen if all the members of the struct failed validation.
502 wfDebugLog( 'XMP', __METHOD__
. " <$ns:$tag> has no valid members." );
504 } elseif ( is_callable( $validate ) ) {
505 $val =& $this->results
['xmp-' . $info['map_group']][$finalName];
506 call_user_func_array( $validate, array( $info, &$val, false ) );
507 if ( is_null( $val ) ) {
508 // the idea being the validation function will unset the variable if
510 wfDebugLog( 'XMP', __METHOD__
. " <$ns:$tag> failed validation." );
511 unset( $this->results
['xmp-' . $info['map_group']][$finalName] );
514 wfDebugLog( 'XMP', __METHOD__
. " Validation function for $finalName ("
515 . $validate[0] . '::' . $validate[1] . '()) is not callable.' );
519 array_shift( $this->curItem
);
520 array_shift( $this->mode
);
521 $this->ancestorStruct
= false;
522 $this->processingArray
= false;
523 $this->itemLang
= false;
527 * Hit a closing element in MODE_LI (either rdf:Seq, or rdf:Bag )
528 * Add information about what type of element this is.
530 * Note we still have to hit the outer "</property>"
532 * @par For example, when processing:
534 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
535 * </rdf:Seq> </exif:ISOSpeedRatings>
538 * This method is called when we hit the "</rdf:Seq>".
539 * (For comparison, we call endElementModeSimple when we
540 * hit the "</rdf:li>")
542 * @param $elm String namespace . ' ' . element name
543 * @throws MWException
545 private function endElementModeLi( $elm ) {
547 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
548 $info = $this->items
[$ns][$tag];
549 $finalName = isset( $info['map_name'] )
550 ?
$info['map_name'] : $tag;
552 array_shift( $this->mode
);
554 if ( !isset( $this->results
['xmp-' . $info['map_group']][$finalName] ) ) {
555 wfDebugLog( 'XMP', __METHOD__
. " Empty compund element $finalName." );
559 if ( $elm === self
::NS_RDF
. ' Seq' ) {
560 $this->results
['xmp-' . $info['map_group']][$finalName]['_type'] = 'ol';
561 } elseif ( $elm === self
::NS_RDF
. ' Bag' ) {
562 $this->results
['xmp-' . $info['map_group']][$finalName]['_type'] = 'ul';
563 } elseif ( $elm === self
::NS_RDF
. ' Alt' ) {
564 // extra if needed as you could theoretically have a non-language alt.
565 if ( $info['mode'] === self
::MODE_LANG
) {
566 $this->results
['xmp-' . $info['map_group']][$finalName]['_type'] = 'lang';
570 throw new MWException( __METHOD__
. " expected </rdf:seq> or </rdf:bag> but instead got $elm." );
575 * End element while in MODE_QDESC
576 * mostly when ending an element when we have a simple value
577 * that has qualifiers.
579 * Qualifiers aren't all that common, and we don't do anything
582 * @param $elm String namespace and element
584 private function endElementModeQDesc( $elm ) {
586 if ( $elm === self
::NS_RDF
. ' value' ) {
587 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
588 $this->saveValue( $ns, $tag, $this->charContent
);
591 array_shift( $this->mode
);
592 array_shift( $this->curItem
);
599 * Handler for hitting a closing element.
601 * generally just calls a helper function depending on what
604 * Ignores the outer wrapping elements that are optional in
605 * xmp and have no meaning.
607 * @param $parser XMLParser
608 * @param $elm String namespace . ' ' . element name
609 * @throws MWException
611 function endElement( $parser, $elm ) {
612 if ( $elm === ( self
::NS_RDF
. ' RDF' )
613 ||
$elm === 'adobe:ns:meta/ xmpmeta'
614 ||
$elm === 'adobe:ns:meta/ xapmeta' )
620 if ( $elm === self
::NS_RDF
. ' type' ) {
621 // these aren't really supported properly yet.
622 // However, it appears they almost never used.
623 wfDebugLog( 'XMP', __METHOD__
. ' encountered <rdf:type>' );
626 if ( strpos( $elm, ' ' ) === false ) {
627 // This probably shouldn't happen.
628 // However, there is a bug in an adobe product
629 // that forgets the namespace on some things.
630 // (Luckily they are unimportant things).
631 wfDebugLog( 'XMP', __METHOD__
. " Encountered </$elm> which has no namespace. Skipping." );
635 if ( count( $this->mode
[0] ) === 0 ) {
636 // This should never ever happen and means
637 // there is a pretty major bug in this class.
638 throw new MWException( 'Encountered end element with no mode' );
641 if ( count( $this->curItem
) == 0 && $this->mode
[0] !== self
::MODE_INITIAL
) {
642 // just to be paranoid. Should always have a curItem, except for initially
643 // (aka during MODE_INITAL).
644 throw new MWException( "Hit end element </$elm> but no curItem" );
647 switch( $this->mode
[0] ) {
648 case self
::MODE_IGNORE
:
649 $this->endElementModeIgnore( $elm );
651 case self
::MODE_SIMPLE
:
652 $this->endElementModeSimple( $elm );
654 case self
::MODE_STRUCT
:
657 case self
::MODE_LANG
:
658 case self
::MODE_BAGSTRUCT
:
659 $this->endElementNested( $elm );
661 case self
::MODE_INITIAL
:
662 if ( $elm === self
::NS_RDF
. ' Description' ) {
663 array_shift( $this->mode
);
665 throw new MWException( 'Element ended unexpectedly while in MODE_INITIAL' );
669 case self
::MODE_LI_LANG
:
670 $this->endElementModeLi( $elm );
672 case self
::MODE_QDESC
:
673 $this->endElementModeQDesc( $elm );
676 wfDebugLog( 'XMP', __METHOD__
. " no mode (elm = $elm)" );
682 * Hit an opening element while in MODE_IGNORE
684 * XMP is extensible, so ignore any tag we don't understand.
686 * Mostly ignores, unless we encounter the element that we are ignoring.
687 * in which case we add it to the item stack, so we can ignore things
688 * that are nested, correctly.
690 * @param $elm String namespace . ' ' . tag name
692 private function startElementModeIgnore( $elm ) {
693 if ( $elm === $this->curItem
[0] ) {
694 array_unshift( $this->curItem
, $elm );
695 array_unshift( $this->mode
, self
::MODE_IGNORE
);
700 * Start element in MODE_BAG (unordered array)
701 * this should always be <rdf:Bag>
703 * @param $elm String namespace . ' ' . tag
704 * @throws MWException if we have an element that's not <rdf:Bag>
706 private function startElementModeBag( $elm ) {
707 if ( $elm === self
::NS_RDF
. ' Bag' ) {
708 array_unshift( $this->mode
, self
::MODE_LI
);
710 throw new MWException( "Expected <rdf:Bag> but got $elm." );
716 * Start element in MODE_SEQ (ordered array)
717 * this should always be <rdf:Seq>
719 * @param $elm String namespace . ' ' . tag
720 * @throws MWException if we have an element that's not <rdf:Seq>
722 private function startElementModeSeq( $elm ) {
723 if ( $elm === self
::NS_RDF
. ' Seq' ) {
724 array_unshift( $this->mode
, self
::MODE_LI
);
725 } elseif ( $elm === self
::NS_RDF
. ' Bag' ) {
727 wfDebugLog( 'XMP', __METHOD__
. ' Expected an rdf:Seq, but got an rdf:Bag. Pretending'
728 . ' it is a Seq, since some buggy software is known to screw this up.' );
729 array_unshift( $this->mode
, self
::MODE_LI
);
731 throw new MWException( "Expected <rdf:Seq> but got $elm." );
737 * Start element in MODE_LANG (language alternative)
738 * this should always be <rdf:Alt>
740 * This tag tends to be used for metadata like describe this
741 * picture, which can be translated into multiple languages.
743 * XMP supports non-linguistic alternative selections,
744 * which are really only used for thumbnails, which
745 * we don't care about.
747 * @param $elm String namespace . ' ' . tag
748 * @throws MWException if we have an element that's not <rdf:Alt>
750 private function startElementModeLang( $elm ) {
751 if ( $elm === self
::NS_RDF
. ' Alt' ) {
752 array_unshift( $this->mode
, self
::MODE_LI_LANG
);
754 throw new MWException( "Expected <rdf:Seq> but got $elm." );
760 * Handle an opening element when in MODE_SIMPLE
762 * This should not happen often. This is for if a simple element
763 * already opened has a child element. Could happen for a
767 * <exif:DigitalZoomRatio><rdf:Description><rdf:value>0/10</rdf:value>
768 * <foo:someQualifier>Bar</foo:someQualifier> </rdf:Description>
769 * </exif:DigitalZoomRatio>
771 * This method is called when processing the <rdf:Description> element
773 * @param $elm String namespace and tag names separated by space.
774 * @param $attribs Array Attributes of the element.
775 * @throws MWException
777 private function startElementModeSimple( $elm, $attribs ) {
778 if ( $elm === self
::NS_RDF
. ' Description' ) {
779 // If this value has qualifiers
780 array_unshift( $this->mode
, self
::MODE_QDESC
);
781 array_unshift( $this->curItem
, $this->curItem
[0] );
783 if ( isset( $attribs[self
::NS_RDF
. ' value'] ) ) {
784 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
785 $this->saveValue( $ns, $tag, $attribs[self
::NS_RDF
. ' value'] );
787 } elseif ( $elm === self
::NS_RDF
. ' value' ) {
788 // This should not be here.
789 throw new MWException( __METHOD__
. ' Encountered <rdf:value> where it was unexpected.' );
792 // something else we don't recognize, like a qualifier maybe.
793 wfDebugLog( 'XMP', __METHOD__
. " Encountered element <$elm> where only expecting character data as value of " . $this->curItem
[0] );
794 array_unshift( $this->mode
, self
::MODE_IGNORE
);
795 array_unshift( $this->curItem
, $elm );
802 * Start an element when in MODE_QDESC.
803 * This generally happens when a simple element has an inner
804 * rdf:Description to hold qualifier elements.
807 * <exif:DigitalZoomRatio><rdf:Description><rdf:value>0/10</rdf:value>
808 * <foo:someQualifier>Bar</foo:someQualifier> </rdf:Description>
809 * </exif:DigitalZoomRatio>
810 * Called when processing the <rdf:value> or <foo:someQualifier>.
812 * @param $elm String namespace and tag name separated by a space.
815 private function startElementModeQDesc( $elm ) {
816 if ( $elm === self
::NS_RDF
. ' value' ) {
817 return; // do nothing
819 // otherwise its a qualifier, which we ignore
820 array_unshift( $this->mode
, self
::MODE_IGNORE
);
821 array_unshift( $this->curItem
, $elm );
826 * Starting an element when in MODE_INITIAL
827 * This usually happens when we hit an element inside
828 * the outer rdf:Description
830 * This is generally where most properties start.
832 * @param $ns String Namespace
833 * @param $tag String tag name (without namespace prefix)
834 * @param $attribs Array array of attributes
835 * @throws MWException
837 private function startElementModeInitial( $ns, $tag, $attribs ) {
838 if ( $ns !== self
::NS_RDF
) {
840 if ( isset( $this->items
[$ns][$tag] ) ) {
841 if ( isset( $this->items
[$ns][$tag]['structPart'] ) ) {
842 // If this element is supposed to appear only as
843 // a child of a structure, but appears here (not as
844 // a child of a struct), then something weird is
845 // happening, so ignore this element and its children.
847 wfDebugLog( 'XMP', "Encountered <$ns:$tag> outside"
848 . " of its expected parent. Ignoring." );
850 array_unshift( $this->mode
, self
::MODE_IGNORE
);
851 array_unshift( $this->curItem
, $ns . ' ' . $tag );
854 $mode = $this->items
[$ns][$tag]['mode'];
855 array_unshift( $this->mode
, $mode );
856 array_unshift( $this->curItem
, $ns . ' ' . $tag );
857 if ( $mode === self
::MODE_STRUCT
) {
858 $this->ancestorStruct
= isset( $this->items
[$ns][$tag]['map_name'] )
859 ?
$this->items
[$ns][$tag]['map_name'] : $tag;
861 if ( $this->charContent
!== false ) {
863 // Should not happen in valid XMP.
864 throw new MWException( 'tag nested in non-whitespace characters.' );
867 // This element is not on our list of allowed elements so ignore.
868 wfDebugLog( 'XMP', __METHOD__
. " Ignoring unrecognized element <$ns:$tag>." );
869 array_unshift( $this->mode
, self
::MODE_IGNORE
);
870 array_unshift( $this->curItem
, $ns . ' ' . $tag );
875 // process attributes
876 $this->doAttribs( $attribs );
880 * Hit an opening element when in a Struct (MODE_STRUCT)
881 * This is generally for fields of a compound property.
883 * Example of a struct (abbreviated; flash has more properties):
885 * <exif:Flash> <rdf:Description> <exif:Fired>True</exif:Fired>
886 * <exif:Mode>1</exif:Mode></rdf:Description></exif:Flash>
890 * <exif:Flash rdf:parseType='Resource'> <exif:Fired>True</exif:Fired>
891 * <exif:Mode>1</exif:Mode></exif:Flash>
893 * @param $ns String namespace
894 * @param $tag String tag name (no ns)
895 * @param $attribs Array array of attribs w/ values.
896 * @throws MWException
898 private function startElementModeStruct( $ns, $tag, $attribs ) {
899 if ( $ns !== self
::NS_RDF
) {
901 if ( isset( $this->items
[$ns][$tag] ) ) {
902 if ( isset( $this->items
[$ns][$this->ancestorStruct
]['children'] )
903 && !isset( $this->items
[$ns][$this->ancestorStruct
]['children'][$tag] ) )
905 // This assumes that we don't have inter-namespace nesting
906 // which we don't in all the properties we're interested in.
907 throw new MWException( " <$tag> appeared nested in <" . $this->ancestorStruct
908 . "> where it is not allowed." );
910 array_unshift( $this->mode
, $this->items
[$ns][$tag]['mode'] );
911 array_unshift( $this->curItem
, $ns . ' ' . $tag );
912 if ( $this->charContent
!== false ) {
914 // Should not happen in valid XMP.
915 throw new MWException( "tag <$tag> nested in non-whitespace characters (" . $this->charContent
. ")." );
918 array_unshift( $this->mode
, self
::MODE_IGNORE
);
919 array_unshift( $this->curItem
, $elm );
925 if ( $ns === self
::NS_RDF
&& $tag === 'Description' ) {
926 $this->doAttribs( $attribs );
927 array_unshift( $this->mode
, self
::MODE_STRUCT
);
928 array_unshift( $this->curItem
, $this->curItem
[0] );
933 * opening element in MODE_LI
934 * process elements of arrays.
937 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
938 * </rdf:Seq> </exif:ISOSpeedRatings>
939 * This method is called when we hit the <rdf:li> element.
941 * @param $elm String: namespace . ' ' . tagname
942 * @param $attribs Array: Attributes. (needed for BAGSTRUCTS)
943 * @throws MWException if gets a tag other than <rdf:li>
945 private function startElementModeLi( $elm, $attribs ) {
946 if ( ( $elm ) !== self
::NS_RDF
. ' li' ) {
947 throw new MWException( "<rdf:li> expected but got $elm." );
950 if ( !isset( $this->mode
[1] ) ) {
951 // This should never ever ever happen. Checking for it
953 throw new MWException( 'In mode Li, but no 2xPrevious mode!' );
956 if ( $this->mode
[1] === self
::MODE_BAGSTRUCT
) {
957 // This list item contains a compound (STRUCT) value.
958 array_unshift( $this->mode
, self
::MODE_STRUCT
);
959 array_unshift( $this->curItem
, $elm );
960 $this->processingArray
= true;
962 if ( !isset( $this->curItem
[1] ) ) {
964 throw new MWException( 'Can not find parent of BAGSTRUCT.' );
966 list( $curNS, $curTag ) = explode( ' ', $this->curItem
[1] );
967 $this->ancestorStruct
= isset( $this->items
[$curNS][$curTag]['map_name'] )
968 ?
$this->items
[$curNS][$curTag]['map_name'] : $curTag;
970 $this->doAttribs( $attribs );
973 // Normal BAG or SEQ containing simple values.
974 array_unshift( $this->mode
, self
::MODE_SIMPLE
);
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 $this->processingArray
= true;
984 * Opening element in MODE_LI_LANG.
985 * process elements of language alternatives
988 * <dc:title> <rdf:Alt> <rdf:li xml:lang="x-default">My house
989 * </rdf:li> </rdf:Alt> </dc:title>
991 * This method is called when we hit the <rdf:li> element.
993 * @param $elm String namespace . ' ' . tag
994 * @param $attribs array array of elements (most importantly xml:lang)
995 * @throws MWException if gets a tag other than <rdf:li> or if no xml:lang
997 private function startElementModeLiLang( $elm, $attribs ) {
998 if ( $elm !== self
::NS_RDF
. ' li' ) {
999 throw new MWException( __METHOD__
. " <rdf:li> expected but got $elm." );
1001 if ( !isset( $attribs[ self
::NS_XML
. ' lang'] )
1002 ||
!preg_match( '/^[-A-Za-z0-9]{2,}$/D', $attribs[ self
::NS_XML
. ' lang' ] ) )
1004 throw new MWException( __METHOD__
1005 . " <rdf:li> did not contain, or has invalid xml:lang attribute in lang alternative" );
1008 // Lang is case-insensitive.
1009 $this->itemLang
= strtolower( $attribs[ self
::NS_XML
. ' lang' ] );
1011 // need to add curItem[0] on again since one is for the specific item
1012 // and one is for the entire group.
1013 array_unshift( $this->curItem
, $this->curItem
[0] );
1014 array_unshift( $this->mode
, self
::MODE_SIMPLE
);
1015 $this->processingArray
= true;
1019 * Hits an opening element.
1020 * Generally just calls a helper based on what MODE we're in.
1021 * Also does some initial set up for the wrapper element
1023 * @param $parser XMLParser
1024 * @param $elm String namespace "<space>" element
1025 * @param $attribs Array attribute name => value
1026 * @throws MWException
1028 function startElement( $parser, $elm, $attribs ) {
1030 if ( $elm === self
::NS_RDF
. ' RDF'
1031 ||
$elm === 'adobe:ns:meta/ xmpmeta'
1032 ||
$elm === 'adobe:ns:meta/ xapmeta')
1036 } elseif ( $elm === self
::NS_RDF
. ' Description' ) {
1037 if ( count( $this->mode
) === 0 ) {
1039 array_unshift( $this->mode
, self
::MODE_INITIAL
);
1041 } elseif ( $elm === self
::NS_RDF
. ' type' ) {
1042 // This doesn't support rdf:type properly.
1043 // In practise I have yet to see a file that
1044 // uses this element, however it is mentioned
1045 // on page 25 of part 1 of the xmp standard.
1047 // also it seems as if exiv2 and exiftool do not support
1048 // this either (That or I misunderstand the standard)
1049 wfDebugLog( 'XMP', __METHOD__
. ' Encountered <rdf:type> which isn\'t currently supported' );
1052 if ( strpos( $elm, ' ' ) === false ) {
1053 // This probably shouldn't happen.
1054 wfDebugLog( 'XMP', __METHOD__
. " Encountered <$elm> which has no namespace. Skipping." );
1058 list( $ns, $tag ) = explode( ' ', $elm, 2 );
1060 if ( count( $this->mode
) === 0 ) {
1061 // This should not happen.
1062 throw new MWException('Error extracting XMP, '
1063 . "encountered <$elm> with no mode" );
1066 switch( $this->mode
[0] ) {
1067 case self
::MODE_IGNORE
:
1068 $this->startElementModeIgnore( $elm );
1070 case self
::MODE_SIMPLE
:
1071 $this->startElementModeSimple( $elm, $attribs );
1073 case self
::MODE_INITIAL
:
1074 $this->startElementModeInitial( $ns, $tag, $attribs );
1076 case self
::MODE_STRUCT
:
1077 $this->startElementModeStruct( $ns, $tag, $attribs );
1079 case self
::MODE_BAG
:
1080 case self
::MODE_BAGSTRUCT
:
1081 $this->startElementModeBag( $elm );
1083 case self
::MODE_SEQ
:
1084 $this->startElementModeSeq( $elm );
1086 case self
::MODE_LANG
:
1087 $this->startElementModeLang( $elm );
1089 case self
::MODE_LI_LANG
:
1090 $this->startElementModeLiLang( $elm, $attribs );
1093 $this->startElementModeLi( $elm, $attribs );
1095 case self
::MODE_QDESC
:
1096 $this->startElementModeQDesc( $elm );
1099 throw new MWException( 'StartElement in unknown mode: ' . $this->mode
[0] );
1104 * Process attributes.
1105 * Simple values can be stored as either a tag or attribute
1107 * Often the initial "<rdf:Description>" tag just has all the simple
1108 * properties as attributes.
1112 * <rdf:Description rdf:about="" xmlns:exif="http://ns.adobe.com/exif/1.0/" exif:DigitalZoomRatio="0/10">
1115 * @param $attribs Array attribute=>value array.
1116 * @throws MWException
1118 private function doAttribs( $attribs ) {
1120 // first check for rdf:parseType attribute, as that can change
1121 // how the attributes are interperted.
1123 if ( isset( $attribs[self
::NS_RDF
. ' parseType'] )
1124 && $attribs[self
::NS_RDF
. ' parseType'] === 'Resource'
1125 && $this->mode
[0] === self
::MODE_SIMPLE
)
1127 // this is equivalent to having an inner rdf:Description
1128 $this->mode
[0] = self
::MODE_QDESC
;
1130 foreach ( $attribs as $name => $val ) {
1133 if ( strpos( $name, ' ' ) === false ) {
1134 // This shouldn't happen, but so far some old software forgets namespace
1136 wfDebugLog( 'XMP', __METHOD__
. ' Encountered non-namespaced attribute: '
1137 . " $name=\"$val\". Skipping. " );
1140 list( $ns, $tag ) = explode( ' ', $name, 2 );
1141 if ( $ns === self
::NS_RDF
) {
1142 if ( $tag === 'value' ||
$tag === 'resource' ) {
1143 // resource is for url.
1144 // value attribute is a weird way of just putting the contents.
1145 $this->char( $this->xmlParser
, $val );
1147 } elseif ( isset( $this->items
[$ns][$tag] ) ) {
1148 if ( $this->mode
[0] === self
::MODE_SIMPLE
) {
1149 throw new MWException( __METHOD__
1150 . " $ns:$tag found as attribute where not allowed" );
1152 $this->saveValue( $ns, $tag, $val );
1154 wfDebugLog( 'XMP', __METHOD__
. " Ignoring unrecognized element <$ns:$tag>." );
1160 * Given an extracted value, save it to results array
1162 * note also uses $this->ancestorStruct and
1163 * $this->processingArray to determine what name to
1164 * save the value under. (in addition to $tag).
1166 * @param $ns String namespace of tag this is for
1167 * @param $tag String tag name
1168 * @param $val String value to save
1170 private function saveValue( $ns, $tag, $val ) {
1172 $info =& $this->items
[$ns][$tag];
1173 $finalName = isset( $info['map_name'] )
1174 ?
$info['map_name'] : $tag;
1175 if ( isset( $info['validate'] ) ) {
1176 $validate = is_array( $info['validate'] ) ?
$info['validate']
1177 : array( 'XMPValidate', $info['validate'] );
1179 if ( is_callable( $validate ) ) {
1180 call_user_func_array( $validate, array( $info, &$val, true ) );
1181 // the reasoning behind using &$val instead of using the return value
1182 // is to be consistent between here and validating structures.
1183 if ( is_null( $val ) ) {
1184 wfDebugLog( 'XMP', __METHOD__
. " <$ns:$tag> failed validation." );
1188 wfDebugLog( 'XMP', __METHOD__
. " Validation function for $finalName ("
1189 . $validate[0] . '::' . $validate[1] . '()) is not callable.' );
1193 if ( $this->ancestorStruct
&& $this->processingArray
) {
1194 // Aka both an array and a struct. ( self::MODE_BAGSTRUCT )
1195 $this->results
['xmp-' . $info['map_group']][$this->ancestorStruct
][][$finalName] = $val;
1196 } elseif ( $this->ancestorStruct
) {
1197 $this->results
['xmp-' . $info['map_group']][$this->ancestorStruct
][$finalName] = $val;
1198 } elseif ( $this->processingArray
) {
1199 if ( $this->itemLang
=== false ) {
1201 $this->results
['xmp-' . $info['map_group']][$finalName][] = $val;
1204 $this->results
['xmp-' . $info['map_group']][$finalName][$this->itemLang
] = $val;
1207 $this->results
['xmp-' . $info['map_group']][$finalName] = $val;