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");
284 // standard specifically says, if no bom assume utf-8
285 $this->charset
= 'UTF-8';
288 if ( $this->charset
!== 'UTF-8' ) {
289 //don't convert if already utf-8
290 wfSuppressWarnings();
291 $content = iconv( $this->charset
, 'UTF-8//IGNORE', $content );
295 $ok = xml_parse( $this->xmlParser
, $content, $allOfIt );
297 $error = xml_error_string( xml_get_error_code( $this->xmlParser
) );
298 $where = 'line: ' . xml_get_current_line_number( $this->xmlParser
)
299 . ' column: ' . xml_get_current_column_number( $this->xmlParser
)
300 . ' byte offset: ' . xml_get_current_byte_index( $this->xmlParser
);
302 wfDebugLog( 'XMP', "XMPReader::parse : Error reading XMP content: $error ($where)" );
303 $this->results
= array(); // blank if error.
306 } catch ( MWException
$e ) {
307 wfDebugLog( 'XMP', 'XMP parse error: ' . $e );
308 $this->results
= array();
314 /** Entry point for XMPExtended blocks in jpeg files
316 * @todo In serious need of testing
317 * @see http://www.adobe.ge/devnet/xmp/pdfs/XMPSpecificationPart3.pdf XMP spec part 3 page 20
318 * @param String $content XMPExtended block minus the namespace signature
319 * @return Boolean If it succeeded.
321 public function parseExtended( $content ) {
322 // @todo FIXME: This is untested. Hard to find example files
323 // or programs that make such files..
324 $guid = substr( $content, 0, 32 );
325 if ( !isset( $this->results
['xmp-special']['HasExtendedXMP'] )
326 ||
$this->results
['xmp-special']['HasExtendedXMP'] !== $guid ) {
327 wfDebugLog('XMP', __METHOD__
. " Ignoring XMPExtended block due to wrong guid (guid= '$guid' )");
330 $len = unpack( 'Nlength/Noffset', substr( $content, 32, 8 ) );
332 if (!$len ||
$len['length'] < 4 ||
$len['offset'] < 0 ||
$len['offset'] > $len['length'] ) {
333 wfDebugLog('XMP', __METHOD__
. 'Error reading extended XMP block, invalid length or offset.');
338 // we're not very robust here. we should accept it in the wrong order. To quote
340 // "A JPEG writer should write the ExtendedXMP marker segments in order, immediately following the
341 // StandardXMP. However, the JPEG standard does not require preservation of marker segment order. A
342 // robust JPEG reader should tolerate the marker segments in any order."
344 // otoh the probability that an image will have more than 128k of metadata is rather low...
345 // so the probability that it will have > 128k, and be in the wrong order is very low...
347 if ( $len['offset'] !== $this->extendedXMPOffset
) {
348 wfDebugLog('XMP', __METHOD__
. 'Ignoring XMPExtended block due to wrong order. (Offset was '
349 . $len['offset'] . ' but expected ' . $this->extendedXMPOffset
. ')');
353 if ( $len['offset'] === 0 ) {
354 // if we're starting the extended block, we've probably already
355 // done the XMPStandard block, so reset.
356 $this->resetXMLParser();
359 $this->extendedXMPOffset +
= $len['length'];
361 $actualContent = substr( $content, 40 );
363 if ( $this->extendedXMPOffset
=== strlen( $actualContent ) ) {
369 wfDebugLog('XMP', __METHOD__
. 'Parsing a XMPExtended block');
370 return $this->parse( $actualContent, $atEnd );
374 * Character data handler
375 * Called whenever character data is found in the xmp document.
377 * does nothing if we're in MODE_IGNORE or if the data is whitespace
378 * throws an error if we're not in MODE_SIMPLE (as we're not allowed to have character
379 * data in the other modes).
381 * As an example, this happens when we encounter XMP like:
382 * <exif:DigitalZoomRatio>0/10</exif:DigitalZoomRatio>
383 * and are processing the 0/10 bit.
385 * @param $parser XMLParser reference to the xml parser
386 * @param $data String Character data
387 * @throws MWException on invalid data
389 function char( $parser, $data ) {
391 $data = trim( $data );
392 if ( trim( $data ) === "" ) {
396 if ( !isset( $this->mode
[0] ) ) {
397 throw new MWException( 'Unexpected character data before first rdf:Description element' );
400 if ( $this->mode
[0] === self
::MODE_IGNORE
) return;
402 if ( $this->mode
[0] !== self
::MODE_SIMPLE
403 && $this->mode
[0] !== self
::MODE_QDESC
405 throw new MWException( 'character data where not expected. (mode ' . $this->mode
[0] . ')' );
408 // to check, how does this handle w.s.
409 if ( $this->charContent
=== false ) {
410 $this->charContent
= $data;
412 $this->charContent
.= $data;
417 /** When we hit a closing element in MODE_IGNORE
418 * Check to see if this is the element we started to ignore,
419 * in which case we get out of MODE_IGNORE
421 * @param $elm String Namespace of element followed by a space and then tag name of element.
423 private function endElementModeIgnore ( $elm ) {
425 if ( $this->curItem
[0] === $elm ) {
426 array_shift( $this->curItem
);
427 array_shift( $this->mode
);
434 * Hit a closing element when in MODE_SIMPLE.
435 * This generally means that we finished processing a
436 * property value, and now have to save the result to the
439 * For example, when processing:
440 * <exif:DigitalZoomRatio>0/10</exif:DigitalZoomRatio>
441 * this deals with when we hit </exif:DigitalZoomRatio>.
443 * Or it could be if we hit the end element of a property
444 * of a compound data structure (like a member of an array).
446 * @param $elm String namespace, space, and tag name.
448 private function endElementModeSimple ( $elm ) {
449 if ( $this->charContent
!== false ) {
450 if ( $this->processingArray
) {
451 // if we're processing an array, use the original element
452 // name instead of rdf:li.
453 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
455 list( $ns, $tag ) = explode( ' ', $elm, 2 );
457 $this->saveValue( $ns, $tag, $this->charContent
);
459 $this->charContent
= false; // reset
461 array_shift( $this->curItem
);
462 array_shift( $this->mode
);
467 * Hit a closing element in MODE_STRUCT, MODE_SEQ, MODE_BAG
468 * generally means we've finished processing a nested structure.
469 * resets some internal variables to indicate that.
471 * Note this means we hit the closing element not the "</rdf:Seq>".
473 * @par For example, when processing:
475 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
476 * </rdf:Seq> </exif:ISOSpeedRatings>
479 * This method is called when we hit the "</exif:ISOSpeedRatings>" tag.
481 * @param $elm String namespace . space . tag name.
482 * @throws MWException
484 private function endElementNested( $elm ) {
486 /* cur item must be the same as $elm, unless if in MODE_STRUCT
487 in which case it could also be rdf:Description */
488 if ( $this->curItem
[0] !== $elm
489 && !( $elm === self
::NS_RDF
. ' Description'
490 && $this->mode
[0] === self
::MODE_STRUCT
)
492 throw new MWException( "nesting mismatch. got a </$elm> but expected a </" . $this->curItem
[0] . '>' );
495 // Validate structures.
496 list( $ns, $tag ) = explode( ' ', $elm, 2 );
497 if ( isset( $this->items
[$ns][$tag]['validate'] ) ) {
499 $info =& $this->items
[$ns][$tag];
500 $finalName = isset( $info['map_name'] )
501 ?
$info['map_name'] : $tag;
503 $validate = is_array( $info['validate'] ) ?
$info['validate']
504 : array( 'XMPValidate', $info['validate'] );
506 if ( !isset( $this->results
['xmp-' . $info['map_group']][$finalName] ) ) {
507 // This can happen if all the members of the struct failed validation.
508 wfDebugLog( 'XMP', __METHOD__
. " <$ns:$tag> has no valid members." );
510 } elseif ( is_callable( $validate ) ) {
511 $val =& $this->results
['xmp-' . $info['map_group']][$finalName];
512 call_user_func_array( $validate, array( $info, &$val, false ) );
513 if ( is_null( $val ) ) {
514 // the idea being the validation function will unset the variable if
516 wfDebugLog( 'XMP', __METHOD__
. " <$ns:$tag> failed validation." );
517 unset( $this->results
['xmp-' . $info['map_group']][$finalName] );
520 wfDebugLog( 'XMP', __METHOD__
. " Validation function for $finalName ("
521 . $validate[0] . '::' . $validate[1] . '()) is not callable.' );
525 array_shift( $this->curItem
);
526 array_shift( $this->mode
);
527 $this->ancestorStruct
= false;
528 $this->processingArray
= false;
529 $this->itemLang
= false;
533 * Hit a closing element in MODE_LI (either rdf:Seq, or rdf:Bag )
534 * Add information about what type of element this is.
536 * Note we still have to hit the outer "</property>"
538 * @par For example, when processing:
540 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
541 * </rdf:Seq> </exif:ISOSpeedRatings>
544 * This method is called when we hit the "</rdf:Seq>".
545 * (For comparison, we call endElementModeSimple when we
546 * hit the "</rdf:li>")
548 * @param $elm String namespace . ' ' . element name
549 * @throws MWException
551 private function endElementModeLi( $elm ) {
553 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
554 $info = $this->items
[$ns][$tag];
555 $finalName = isset( $info['map_name'] )
556 ?
$info['map_name'] : $tag;
558 array_shift( $this->mode
);
560 if ( !isset( $this->results
['xmp-' . $info['map_group']][$finalName] ) ) {
561 wfDebugLog( 'XMP', __METHOD__
. " Empty compund element $finalName." );
565 if ( $elm === self
::NS_RDF
. ' Seq' ) {
566 $this->results
['xmp-' . $info['map_group']][$finalName]['_type'] = 'ol';
567 } elseif ( $elm === self
::NS_RDF
. ' Bag' ) {
568 $this->results
['xmp-' . $info['map_group']][$finalName]['_type'] = 'ul';
569 } elseif ( $elm === self
::NS_RDF
. ' Alt' ) {
570 // extra if needed as you could theoretically have a non-language alt.
571 if ( $info['mode'] === self
::MODE_LANG
) {
572 $this->results
['xmp-' . $info['map_group']][$finalName]['_type'] = 'lang';
576 throw new MWException( __METHOD__
. " expected </rdf:seq> or </rdf:bag> but instead got $elm." );
581 * End element while in MODE_QDESC
582 * mostly when ending an element when we have a simple value
583 * that has qualifiers.
585 * Qualifiers aren't all that common, and we don't do anything
588 * @param $elm String namespace and element
590 private function endElementModeQDesc( $elm ) {
592 if ( $elm === self
::NS_RDF
. ' value' ) {
593 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
594 $this->saveValue( $ns, $tag, $this->charContent
);
597 array_shift( $this->mode
);
598 array_shift( $this->curItem
);
605 * Handler for hitting a closing element.
607 * generally just calls a helper function depending on what
610 * Ignores the outer wrapping elements that are optional in
611 * xmp and have no meaning.
613 * @param $parser XMLParser
614 * @param $elm String namespace . ' ' . element name
615 * @throws MWException
617 function endElement( $parser, $elm ) {
618 if ( $elm === ( self
::NS_RDF
. ' RDF' )
619 ||
$elm === 'adobe:ns:meta/ xmpmeta'
620 ||
$elm === 'adobe:ns:meta/ xapmeta' )
626 if ( $elm === self
::NS_RDF
. ' type' ) {
627 // these aren't really supported properly yet.
628 // However, it appears they almost never used.
629 wfDebugLog( 'XMP', __METHOD__
. ' encountered <rdf:type>' );
632 if ( strpos( $elm, ' ' ) === false ) {
633 // This probably shouldn't happen.
634 // However, there is a bug in an adobe product
635 // that forgets the namespace on some things.
636 // (Luckily they are unimportant things).
637 wfDebugLog( 'XMP', __METHOD__
. " Encountered </$elm> which has no namespace. Skipping." );
641 if ( count( $this->mode
[0] ) === 0 ) {
642 // This should never ever happen and means
643 // there is a pretty major bug in this class.
644 throw new MWException( 'Encountered end element with no mode' );
647 if ( count( $this->curItem
) == 0 && $this->mode
[0] !== self
::MODE_INITIAL
) {
648 // just to be paranoid. Should always have a curItem, except for initially
649 // (aka during MODE_INITAL).
650 throw new MWException( "Hit end element </$elm> but no curItem" );
653 switch( $this->mode
[0] ) {
654 case self
::MODE_IGNORE
:
655 $this->endElementModeIgnore( $elm );
657 case self
::MODE_SIMPLE
:
658 $this->endElementModeSimple( $elm );
660 case self
::MODE_STRUCT
:
663 case self
::MODE_LANG
:
664 case self
::MODE_BAGSTRUCT
:
665 $this->endElementNested( $elm );
667 case self
::MODE_INITIAL
:
668 if ( $elm === self
::NS_RDF
. ' Description' ) {
669 array_shift( $this->mode
);
671 throw new MWException( 'Element ended unexpectedly while in MODE_INITIAL' );
675 case self
::MODE_LI_LANG
:
676 $this->endElementModeLi( $elm );
678 case self
::MODE_QDESC
:
679 $this->endElementModeQDesc( $elm );
682 wfDebugLog( 'XMP', __METHOD__
. " no mode (elm = $elm)" );
688 * Hit an opening element while in MODE_IGNORE
690 * XMP is extensible, so ignore any tag we don't understand.
692 * Mostly ignores, unless we encounter the element that we are ignoring.
693 * in which case we add it to the item stack, so we can ignore things
694 * that are nested, correctly.
696 * @param $elm String namespace . ' ' . tag name
698 private function startElementModeIgnore( $elm ) {
699 if ( $elm === $this->curItem
[0] ) {
700 array_unshift( $this->curItem
, $elm );
701 array_unshift( $this->mode
, self
::MODE_IGNORE
);
706 * Start element in MODE_BAG (unordered array)
707 * this should always be <rdf:Bag>
709 * @param $elm String namespace . ' ' . tag
710 * @throws MWException if we have an element that's not <rdf:Bag>
712 private function startElementModeBag( $elm ) {
713 if ( $elm === self
::NS_RDF
. ' Bag' ) {
714 array_unshift( $this->mode
, self
::MODE_LI
);
716 throw new MWException( "Expected <rdf:Bag> but got $elm." );
722 * Start element in MODE_SEQ (ordered array)
723 * this should always be <rdf:Seq>
725 * @param $elm String namespace . ' ' . tag
726 * @throws MWException if we have an element that's not <rdf:Seq>
728 private function startElementModeSeq( $elm ) {
729 if ( $elm === self
::NS_RDF
. ' Seq' ) {
730 array_unshift( $this->mode
, self
::MODE_LI
);
731 } elseif ( $elm === self
::NS_RDF
. ' Bag' ) {
733 wfDebugLog( 'XMP', __METHOD__
. ' Expected an rdf:Seq, but got an rdf:Bag. Pretending'
734 . ' it is a Seq, since some buggy software is known to screw this up.' );
735 array_unshift( $this->mode
, self
::MODE_LI
);
737 throw new MWException( "Expected <rdf:Seq> but got $elm." );
743 * Start element in MODE_LANG (language alternative)
744 * this should always be <rdf:Alt>
746 * This tag tends to be used for metadata like describe this
747 * picture, which can be translated into multiple languages.
749 * XMP supports non-linguistic alternative selections,
750 * which are really only used for thumbnails, which
751 * we don't care about.
753 * @param $elm String namespace . ' ' . tag
754 * @throws MWException if we have an element that's not <rdf:Alt>
756 private function startElementModeLang( $elm ) {
757 if ( $elm === self
::NS_RDF
. ' Alt' ) {
758 array_unshift( $this->mode
, self
::MODE_LI_LANG
);
760 throw new MWException( "Expected <rdf:Seq> but got $elm." );
766 * Handle an opening element when in MODE_SIMPLE
768 * This should not happen often. This is for if a simple element
769 * already opened has a child element. Could happen for a
773 * <exif:DigitalZoomRatio><rdf:Description><rdf:value>0/10</rdf:value>
774 * <foo:someQualifier>Bar</foo:someQualifier> </rdf:Description>
775 * </exif:DigitalZoomRatio>
777 * This method is called when processing the <rdf:Description> element
779 * @param $elm String namespace and tag names separated by space.
780 * @param $attribs Array Attributes of the element.
781 * @throws MWException
783 private function startElementModeSimple( $elm, $attribs ) {
784 if ( $elm === self
::NS_RDF
. ' Description' ) {
785 // If this value has qualifiers
786 array_unshift( $this->mode
, self
::MODE_QDESC
);
787 array_unshift( $this->curItem
, $this->curItem
[0] );
789 if ( isset( $attribs[self
::NS_RDF
. ' value'] ) ) {
790 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
791 $this->saveValue( $ns, $tag, $attribs[self
::NS_RDF
. ' value'] );
793 } elseif ( $elm === self
::NS_RDF
. ' value' ) {
794 // This should not be here.
795 throw new MWException( __METHOD__
. ' Encountered <rdf:value> where it was unexpected.' );
798 // something else we don't recognize, like a qualifier maybe.
799 wfDebugLog( 'XMP', __METHOD__
. " Encountered element <$elm> where only expecting character data as value of " . $this->curItem
[0] );
800 array_unshift( $this->mode
, self
::MODE_IGNORE
);
801 array_unshift( $this->curItem
, $elm );
808 * Start an element when in MODE_QDESC.
809 * This generally happens when a simple element has an inner
810 * rdf:Description to hold qualifier elements.
813 * <exif:DigitalZoomRatio><rdf:Description><rdf:value>0/10</rdf:value>
814 * <foo:someQualifier>Bar</foo:someQualifier> </rdf:Description>
815 * </exif:DigitalZoomRatio>
816 * Called when processing the <rdf:value> or <foo:someQualifier>.
818 * @param $elm String namespace and tag name separated by a space.
821 private function startElementModeQDesc( $elm ) {
822 if ( $elm === self
::NS_RDF
. ' value' ) {
823 return; // do nothing
825 // otherwise its a qualifier, which we ignore
826 array_unshift( $this->mode
, self
::MODE_IGNORE
);
827 array_unshift( $this->curItem
, $elm );
832 * Starting an element when in MODE_INITIAL
833 * This usually happens when we hit an element inside
834 * the outer rdf:Description
836 * This is generally where most properties start.
838 * @param $ns String Namespace
839 * @param $tag String tag name (without namespace prefix)
840 * @param $attribs Array array of attributes
841 * @throws MWException
843 private function startElementModeInitial( $ns, $tag, $attribs ) {
844 if ( $ns !== self
::NS_RDF
) {
846 if ( isset( $this->items
[$ns][$tag] ) ) {
847 if ( isset( $this->items
[$ns][$tag]['structPart'] ) ) {
848 // If this element is supposed to appear only as
849 // a child of a structure, but appears here (not as
850 // a child of a struct), then something weird is
851 // happening, so ignore this element and its children.
853 wfDebugLog( 'XMP', "Encountered <$ns:$tag> outside"
854 . " of its expected parent. Ignoring." );
856 array_unshift( $this->mode
, self
::MODE_IGNORE
);
857 array_unshift( $this->curItem
, $ns . ' ' . $tag );
860 $mode = $this->items
[$ns][$tag]['mode'];
861 array_unshift( $this->mode
, $mode );
862 array_unshift( $this->curItem
, $ns . ' ' . $tag );
863 if ( $mode === self
::MODE_STRUCT
) {
864 $this->ancestorStruct
= isset( $this->items
[$ns][$tag]['map_name'] )
865 ?
$this->items
[$ns][$tag]['map_name'] : $tag;
867 if ( $this->charContent
!== false ) {
869 // Should not happen in valid XMP.
870 throw new MWException( 'tag nested in non-whitespace characters.' );
873 // This element is not on our list of allowed elements so ignore.
874 wfDebugLog( 'XMP', __METHOD__
. " Ignoring unrecognized element <$ns:$tag>." );
875 array_unshift( $this->mode
, self
::MODE_IGNORE
);
876 array_unshift( $this->curItem
, $ns . ' ' . $tag );
881 // process attributes
882 $this->doAttribs( $attribs );
886 * Hit an opening element when in a Struct (MODE_STRUCT)
887 * This is generally for fields of a compound property.
889 * Example of a struct (abbreviated; flash has more properties):
891 * <exif:Flash> <rdf:Description> <exif:Fired>True</exif:Fired>
892 * <exif:Mode>1</exif:Mode></rdf:Description></exif:Flash>
896 * <exif:Flash rdf:parseType='Resource'> <exif:Fired>True</exif:Fired>
897 * <exif:Mode>1</exif:Mode></exif:Flash>
899 * @param $ns String namespace
900 * @param $tag String tag name (no ns)
901 * @param $attribs Array array of attribs w/ values.
902 * @throws MWException
904 private function startElementModeStruct( $ns, $tag, $attribs ) {
905 if ( $ns !== self
::NS_RDF
) {
907 if ( isset( $this->items
[$ns][$tag] ) ) {
908 if ( isset( $this->items
[$ns][$this->ancestorStruct
]['children'] )
909 && !isset( $this->items
[$ns][$this->ancestorStruct
]['children'][$tag] ) )
911 // This assumes that we don't have inter-namespace nesting
912 // which we don't in all the properties we're interested in.
913 throw new MWException( " <$tag> appeared nested in <" . $this->ancestorStruct
914 . "> where it is not allowed." );
916 array_unshift( $this->mode
, $this->items
[$ns][$tag]['mode'] );
917 array_unshift( $this->curItem
, $ns . ' ' . $tag );
918 if ( $this->charContent
!== false ) {
920 // Should not happen in valid XMP.
921 throw new MWException( "tag <$tag> nested in non-whitespace characters (" . $this->charContent
. ")." );
924 array_unshift( $this->mode
, self
::MODE_IGNORE
);
925 array_unshift( $this->curItem
, $elm );
931 if ( $ns === self
::NS_RDF
&& $tag === 'Description' ) {
932 $this->doAttribs( $attribs );
933 array_unshift( $this->mode
, self
::MODE_STRUCT
);
934 array_unshift( $this->curItem
, $this->curItem
[0] );
939 * opening element in MODE_LI
940 * process elements of arrays.
943 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
944 * </rdf:Seq> </exif:ISOSpeedRatings>
945 * This method is called when we hit the <rdf:li> element.
947 * @param $elm String: namespace . ' ' . tagname
948 * @param $attribs Array: Attributes. (needed for BAGSTRUCTS)
949 * @throws MWException if gets a tag other than <rdf:li>
951 private function startElementModeLi( $elm, $attribs ) {
952 if ( ( $elm ) !== self
::NS_RDF
. ' li' ) {
953 throw new MWException( "<rdf:li> expected but got $elm." );
956 if ( !isset( $this->mode
[1] ) ) {
957 // This should never ever ever happen. Checking for it
959 throw new MWException( 'In mode Li, but no 2xPrevious mode!' );
962 if ( $this->mode
[1] === self
::MODE_BAGSTRUCT
) {
963 // This list item contains a compound (STRUCT) value.
964 array_unshift( $this->mode
, self
::MODE_STRUCT
);
965 array_unshift( $this->curItem
, $elm );
966 $this->processingArray
= true;
968 if ( !isset( $this->curItem
[1] ) ) {
970 throw new MWException( 'Can not find parent of BAGSTRUCT.' );
972 list( $curNS, $curTag ) = explode( ' ', $this->curItem
[1] );
973 $this->ancestorStruct
= isset( $this->items
[$curNS][$curTag]['map_name'] )
974 ?
$this->items
[$curNS][$curTag]['map_name'] : $curTag;
976 $this->doAttribs( $attribs );
979 // Normal BAG or SEQ containing simple values.
980 array_unshift( $this->mode
, self
::MODE_SIMPLE
);
981 // need to add curItem[0] on again since one is for the specific item
982 // and one is for the entire group.
983 array_unshift( $this->curItem
, $this->curItem
[0] );
984 $this->processingArray
= true;
990 * Opening element in MODE_LI_LANG.
991 * process elements of language alternatives
994 * <dc:title> <rdf:Alt> <rdf:li xml:lang="x-default">My house
995 * </rdf:li> </rdf:Alt> </dc:title>
997 * This method is called when we hit the <rdf:li> element.
999 * @param $elm String namespace . ' ' . tag
1000 * @param $attribs array array of elements (most importantly xml:lang)
1001 * @throws MWException if gets a tag other than <rdf:li> or if no xml:lang
1003 private function startElementModeLiLang( $elm, $attribs ) {
1004 if ( $elm !== self
::NS_RDF
. ' li' ) {
1005 throw new MWException( __METHOD__
. " <rdf:li> expected but got $elm." );
1007 if ( !isset( $attribs[ self
::NS_XML
. ' lang'] )
1008 ||
!preg_match( '/^[-A-Za-z0-9]{2,}$/D', $attribs[ self
::NS_XML
. ' lang' ] ) )
1010 throw new MWException( __METHOD__
1011 . " <rdf:li> did not contain, or has invalid xml:lang attribute in lang alternative" );
1014 // Lang is case-insensitive.
1015 $this->itemLang
= strtolower( $attribs[ self
::NS_XML
. ' lang' ] );
1017 // need to add curItem[0] on again since one is for the specific item
1018 // and one is for the entire group.
1019 array_unshift( $this->curItem
, $this->curItem
[0] );
1020 array_unshift( $this->mode
, self
::MODE_SIMPLE
);
1021 $this->processingArray
= true;
1025 * Hits an opening element.
1026 * Generally just calls a helper based on what MODE we're in.
1027 * Also does some initial set up for the wrapper element
1029 * @param $parser XMLParser
1030 * @param $elm String namespace "<space>" element
1031 * @param $attribs Array attribute name => value
1032 * @throws MWException
1034 function startElement( $parser, $elm, $attribs ) {
1036 if ( $elm === self
::NS_RDF
. ' RDF'
1037 ||
$elm === 'adobe:ns:meta/ xmpmeta'
1038 ||
$elm === 'adobe:ns:meta/ xapmeta')
1042 } elseif ( $elm === self
::NS_RDF
. ' Description' ) {
1043 if ( count( $this->mode
) === 0 ) {
1045 array_unshift( $this->mode
, self
::MODE_INITIAL
);
1047 } elseif ( $elm === self
::NS_RDF
. ' type' ) {
1048 // This doesn't support rdf:type properly.
1049 // In practise I have yet to see a file that
1050 // uses this element, however it is mentioned
1051 // on page 25 of part 1 of the xmp standard.
1053 // also it seems as if exiv2 and exiftool do not support
1054 // this either (That or I misunderstand the standard)
1055 wfDebugLog( 'XMP', __METHOD__
. ' Encountered <rdf:type> which isn\'t currently supported' );
1058 if ( strpos( $elm, ' ' ) === false ) {
1059 // This probably shouldn't happen.
1060 wfDebugLog( 'XMP', __METHOD__
. " Encountered <$elm> which has no namespace. Skipping." );
1064 list( $ns, $tag ) = explode( ' ', $elm, 2 );
1066 if ( count( $this->mode
) === 0 ) {
1067 // This should not happen.
1068 throw new MWException('Error extracting XMP, '
1069 . "encountered <$elm> with no mode" );
1072 switch( $this->mode
[0] ) {
1073 case self
::MODE_IGNORE
:
1074 $this->startElementModeIgnore( $elm );
1076 case self
::MODE_SIMPLE
:
1077 $this->startElementModeSimple( $elm, $attribs );
1079 case self
::MODE_INITIAL
:
1080 $this->startElementModeInitial( $ns, $tag, $attribs );
1082 case self
::MODE_STRUCT
:
1083 $this->startElementModeStruct( $ns, $tag, $attribs );
1085 case self
::MODE_BAG
:
1086 case self
::MODE_BAGSTRUCT
:
1087 $this->startElementModeBag( $elm );
1089 case self
::MODE_SEQ
:
1090 $this->startElementModeSeq( $elm );
1092 case self
::MODE_LANG
:
1093 $this->startElementModeLang( $elm );
1095 case self
::MODE_LI_LANG
:
1096 $this->startElementModeLiLang( $elm, $attribs );
1099 $this->startElementModeLi( $elm, $attribs );
1101 case self
::MODE_QDESC
:
1102 $this->startElementModeQDesc( $elm );
1105 throw new MWException( 'StartElement in unknown mode: ' . $this->mode
[0] );
1111 * Process attributes.
1112 * Simple values can be stored as either a tag or attribute
1114 * Often the initial "<rdf:Description>" tag just has all the simple
1115 * properties as attributes.
1119 * <rdf:Description rdf:about="" xmlns:exif="http://ns.adobe.com/exif/1.0/" exif:DigitalZoomRatio="0/10">
1122 * @param $attribs Array attribute=>value array.
1123 * @throws MWException
1125 private function doAttribs( $attribs ) {
1127 // first check for rdf:parseType attribute, as that can change
1128 // how the attributes are interperted.
1130 if ( isset( $attribs[self
::NS_RDF
. ' parseType'] )
1131 && $attribs[self
::NS_RDF
. ' parseType'] === 'Resource'
1132 && $this->mode
[0] === self
::MODE_SIMPLE
)
1134 // this is equivalent to having an inner rdf:Description
1135 $this->mode
[0] = self
::MODE_QDESC
;
1137 foreach ( $attribs as $name => $val ) {
1140 if ( strpos( $name, ' ' ) === false ) {
1141 // This shouldn't happen, but so far some old software forgets namespace
1143 wfDebugLog( 'XMP', __METHOD__
. ' Encountered non-namespaced attribute: '
1144 . " $name=\"$val\". Skipping. " );
1147 list( $ns, $tag ) = explode( ' ', $name, 2 );
1148 if ( $ns === self
::NS_RDF
) {
1149 if ( $tag === 'value' ||
$tag === 'resource' ) {
1150 // resource is for url.
1151 // value attribute is a weird way of just putting the contents.
1152 $this->char( $this->xmlParser
, $val );
1154 } elseif ( isset( $this->items
[$ns][$tag] ) ) {
1155 if ( $this->mode
[0] === self
::MODE_SIMPLE
) {
1156 throw new MWException( __METHOD__
1157 . " $ns:$tag found as attribute where not allowed" );
1159 $this->saveValue( $ns, $tag, $val );
1161 wfDebugLog( 'XMP', __METHOD__
. " Ignoring unrecognized element <$ns:$tag>." );
1167 * Given an extracted value, save it to results array
1169 * note also uses $this->ancestorStruct and
1170 * $this->processingArray to determine what name to
1171 * save the value under. (in addition to $tag).
1173 * @param $ns String namespace of tag this is for
1174 * @param $tag String tag name
1175 * @param $val String value to save
1177 private function saveValue( $ns, $tag, $val ) {
1179 $info =& $this->items
[$ns][$tag];
1180 $finalName = isset( $info['map_name'] )
1181 ?
$info['map_name'] : $tag;
1182 if ( isset( $info['validate'] ) ) {
1183 $validate = is_array( $info['validate'] ) ?
$info['validate']
1184 : array( 'XMPValidate', $info['validate'] );
1186 if ( is_callable( $validate ) ) {
1187 call_user_func_array( $validate, array( $info, &$val, true ) );
1188 // the reasoning behind using &$val instead of using the return value
1189 // is to be consistent between here and validating structures.
1190 if ( is_null( $val ) ) {
1191 wfDebugLog( 'XMP', __METHOD__
. " <$ns:$tag> failed validation." );
1195 wfDebugLog( 'XMP', __METHOD__
. " Validation function for $finalName ("
1196 . $validate[0] . '::' . $validate[1] . '()) is not callable.' );
1200 if ( $this->ancestorStruct
&& $this->processingArray
) {
1201 // Aka both an array and a struct. ( self::MODE_BAGSTRUCT )
1202 $this->results
['xmp-' . $info['map_group']][$this->ancestorStruct
][][$finalName] = $val;
1203 } elseif ( $this->ancestorStruct
) {
1204 $this->results
['xmp-' . $info['map_group']][$this->ancestorStruct
][$finalName] = $val;
1205 } elseif ( $this->processingArray
) {
1206 if ( $this->itemLang
=== false ) {
1208 $this->results
['xmp-' . $info['map_group']][$finalName][] = $val;
1211 $this->results
['xmp-' . $info['map_group']][$finalName][$this->itemLang
] = $val;
1214 $this->results
['xmp-' . $info['map_group']][$finalName] = $val;