d60b6994d18dd35f82884c522f80b9d71262b518
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
50 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.
54 private $charContent = false; // temporary holder for character data that appears in xmp doc.
56 private $mode = array(); // stores the state the xmpreader is in (see MODE_FOO constants)
58 private $results = array(); // array to hold results
60 private $processingArray = false; // if we're doing a seq or bag.
62 private $itemLang = false; // used for lang alts only
66 private $charset = false;
68 private $extendedXMPOffset = 0;
73 * These are various mode constants.
74 * they are used to figure out what to do
75 * with an element when its encountered.
77 * For example, MODE_IGNORE is used when processing
78 * a property we're not interested in. So if a new
79 * element pops up when we're in that mode, we ignore it.
81 const MODE_INITIAL
= 0;
82 const MODE_IGNORE
= 1;
84 const MODE_LI_LANG
= 3;
87 // The following MODE constants are also used in the
88 // $items array to denote what type of property the item is.
89 const MODE_SIMPLE
= 10;
90 const MODE_STRUCT
= 11; // structure (associative array)
91 const MODE_SEQ
= 12; // ordered list
92 const MODE_BAG
= 13; // unordered list
94 const MODE_ALT
= 15; // non-language alt. Currently not implemented, and not needed atm.
95 const MODE_BAGSTRUCT
= 16; // A BAG of Structs.
97 const NS_RDF
= 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
98 const NS_XML
= 'http://www.w3.org/XML/1998/namespace';
103 * Primary job is to initialize the XMLParser
105 function __construct() {
107 if ( !function_exists( 'xml_parser_create_ns' ) ) {
108 // this should already be checked by this point
109 throw new MWException( 'XMP support requires XML Parser' );
112 $this->items
= XMPInfo
::getItems();
114 $this->resetXMLParser();
118 * Main use is if a single item has multiple xmp documents describing it.
119 * For example in jpeg's with extendedXMP
121 private function resetXMLParser() {
123 if ( $this->xmlParser
) {
125 xml_parser_free( $this->xmlParser
);
128 $this->xmlParser
= xml_parser_create_ns( 'UTF-8', ' ' );
129 xml_parser_set_option( $this->xmlParser
, XML_OPTION_CASE_FOLDING
, 0 );
130 xml_parser_set_option( $this->xmlParser
, XML_OPTION_SKIP_WHITE
, 1 );
132 xml_set_element_handler( $this->xmlParser
,
133 array( $this, 'startElement' ),
134 array( $this, 'endElement' ) );
136 xml_set_character_data_handler( $this->xmlParser
, array( $this, 'char' ) );
139 /** Destroy the xml parser
141 * Not sure if this is actually needed.
143 function __destruct() {
144 // not sure if this is needed.
145 xml_parser_free( $this->xmlParser
);
148 /** Get the result array. Do some post-processing before returning
149 * the array, and transform any metadata that is special-cased.
151 * @return Array array of results as an array of arrays suitable for
152 * FormatMetadata::getFormattedData().
154 public function getResults() {
155 // xmp-special is for metadata that affects how stuff
156 // is extracted. For example xmpNote:HasExtendedXMP.
158 // It is also used to handle photoshop:AuthorsPosition
159 // which is weird and really part of another property,
160 // see 2:85 in IPTC. See also pg 21 of IPTC4XMP standard.
161 // The location fields also use it.
163 $data = $this->results
;
165 wfRunHooks( 'XMPGetResults', array( &$data ) );
167 if ( isset( $data['xmp-special']['AuthorsPosition'] )
168 && is_string( $data['xmp-special']['AuthorsPosition'] )
169 && isset( $data['xmp-general']['Artist'][0] )
171 // Note, if there is more than one creator,
172 // this only applies to first. This also will
173 // only apply to the dc:Creator prop, not the
176 $data['xmp-general']['Artist'][0] =
177 $data['xmp-special']['AuthorsPosition'] . ', '
178 . $data['xmp-general']['Artist'][0];
181 // Go through the LocationShown and LocationCreated
182 // changing it to the non-hierarchal form used by
183 // the other location fields.
185 if ( isset( $data['xmp-special']['LocationShown'][0] )
186 && is_array( $data['xmp-special']['LocationShown'][0] )
188 // the is_array is just paranoia. It should always
190 foreach ( $data['xmp-special']['LocationShown'] as $loc ) {
191 if ( !is_array( $loc ) ) {
192 // To avoid copying over the _type meta-fields.
195 foreach ( $loc as $field => $val ) {
196 $data['xmp-general'][$field . 'Dest'][] = $val;
200 if ( isset( $data['xmp-special']['LocationCreated'][0] )
201 && is_array( $data['xmp-special']['LocationCreated'][0] )
203 // the is_array is just paranoia. It should always
205 foreach ( $data['xmp-special']['LocationCreated'] as $loc ) {
206 if ( !is_array( $loc ) ) {
207 // To avoid copying over the _type meta-fields.
210 foreach ( $loc as $field => $val ) {
211 $data['xmp-general'][$field . 'Created'][] = $val;
216 // We don't want to return the special values, since they're
217 // special and not info to be stored about the file.
218 unset( $data['xmp-special'] );
220 // Convert GPSAltitude to negative if below sea level.
221 if ( isset( $data['xmp-exif']['GPSAltitudeRef'] )
222 && isset( $data['xmp-exif']['GPSAltitude'] )
225 // Must convert to a real before multiplying by -1
226 // XMPValidate guarantees there will always be a '/' in this value.
227 list( $nom, $denom ) = explode( '/', $data['xmp-exif']['GPSAltitude'] );
228 $data['xmp-exif']['GPSAltitude'] = $nom / $denom;
230 if ( $data['xmp-exif']['GPSAltitudeRef'] == '1' ) {
231 $data['xmp-exif']['GPSAltitude'] *= -1;
233 unset( $data['xmp-exif']['GPSAltitudeRef'] );
240 * Main function to call to parse XMP. Use getResults to
243 * Also catches any errors during processing, writes them to
244 * debug log, blanks result array and returns false.
246 * @param string $content XMP data
247 * @param $allOfIt Boolean: If this is all the data (true) or if its split up (false). Default true
248 * @param $reset Boolean: does xml parser need to be reset. Default false
249 * @throws MWException
250 * @return Boolean success.
252 public function parse( $content, $allOfIt = true, $reset = false ) {
254 $this->resetXMLParser();
258 // detect encoding by looking for BOM which is supposed to be in processing instruction.
259 // see page 12 of http://www.adobe.com/devnet/xmp/pdfs/XMPSpecificationPart3.pdf
260 if ( !$this->charset
) {
262 if ( preg_match( '/\xEF\xBB\xBF|\xFE\xFF|\x00\x00\xFE\xFF|\xFF\xFE\x00\x00|\xFF\xFE/',
267 $this->charset
= 'UTF-16BE';
270 $this->charset
= 'UTF-16LE';
272 case "\x00\x00\xFE\xFF":
273 $this->charset
= 'UTF-32BE';
275 case "\xFF\xFE\x00\x00":
276 $this->charset
= 'UTF-32LE';
279 $this->charset
= 'UTF-8';
282 //this should be impossible to get to
283 throw new MWException( "Invalid BOM" );
286 // standard specifically says, if no bom assume utf-8
287 $this->charset
= 'UTF-8';
290 if ( $this->charset
!== 'UTF-8' ) {
291 //don't convert if already utf-8
292 wfSuppressWarnings();
293 $content = iconv( $this->charset
, 'UTF-8//IGNORE', $content );
297 $ok = xml_parse( $this->xmlParser
, $content, $allOfIt );
299 $error = xml_error_string( xml_get_error_code( $this->xmlParser
) );
300 $where = 'line: ' . xml_get_current_line_number( $this->xmlParser
)
301 . ' column: ' . xml_get_current_column_number( $this->xmlParser
)
302 . ' byte offset: ' . xml_get_current_byte_index( $this->xmlParser
);
304 wfDebugLog( 'XMP', "XMPReader::parse : Error reading XMP content: $error ($where)" );
305 $this->results
= array(); // blank if error.
308 } catch ( MWException
$e ) {
309 wfDebugLog( 'XMP', 'XMP parse error: ' . $e );
310 $this->results
= array();
318 /** Entry point for XMPExtended blocks in jpeg files
320 * @todo In serious need of testing
321 * @see http://www.adobe.ge/devnet/xmp/pdfs/XMPSpecificationPart3.pdf XMP spec part 3 page 20
322 * @param string $content XMPExtended block minus the namespace signature
323 * @return Boolean If it succeeded.
325 public function parseExtended( $content ) {
326 // @todo FIXME: This is untested. Hard to find example files
327 // or programs that make such files..
328 $guid = substr( $content, 0, 32 );
329 if ( !isset( $this->results
['xmp-special']['HasExtendedXMP'] )
330 ||
$this->results
['xmp-special']['HasExtendedXMP'] !== $guid
332 wfDebugLog( 'XMP', __METHOD__
.
333 " Ignoring XMPExtended block due to wrong guid (guid= '$guid')" );
337 $len = unpack( 'Nlength/Noffset', substr( $content, 32, 8 ) );
339 if ( !$len ||
$len['length'] < 4 ||
$len['offset'] < 0 ||
$len['offset'] > $len['length'] ) {
340 wfDebugLog( 'XMP', __METHOD__
. 'Error reading extended XMP block, invalid length or offset.' );
345 // we're not very robust here. we should accept it in the wrong order.
346 // To quote the XMP standard:
347 // "A JPEG writer should write the ExtendedXMP marker segments in order,
348 // immediately following the StandardXMP. However, the JPEG standard
349 // does not require preservation of marker segment order. A robust JPEG
350 // reader should tolerate the marker segments in any order."
352 // otoh the probability that an image will have more than 128k of
353 // metadata is rather low... so the probability that it will have
354 // > 128k, and be in the wrong order is very low...
356 if ( $len['offset'] !== $this->extendedXMPOffset
) {
357 wfDebugLog( 'XMP', __METHOD__
. 'Ignoring XMPExtended block due to wrong order. (Offset was '
358 . $len['offset'] . ' but expected ' . $this->extendedXMPOffset
. ')' );
363 if ( $len['offset'] === 0 ) {
364 // if we're starting the extended block, we've probably already
365 // done the XMPStandard block, so reset.
366 $this->resetXMLParser();
369 $this->extendedXMPOffset +
= $len['length'];
371 $actualContent = substr( $content, 40 );
373 if ( $this->extendedXMPOffset
=== strlen( $actualContent ) ) {
379 wfDebugLog( 'XMP', __METHOD__
. 'Parsing a XMPExtended block' );
381 return $this->parse( $actualContent, $atEnd );
385 * Character data handler
386 * Called whenever character data is found in the xmp document.
388 * does nothing if we're in MODE_IGNORE or if the data is whitespace
389 * throws an error if we're not in MODE_SIMPLE (as we're not allowed to have character
390 * data in the other modes).
392 * As an example, this happens when we encounter XMP like:
393 * <exif:DigitalZoomRatio>0/10</exif:DigitalZoomRatio>
394 * and are processing the 0/10 bit.
396 * @param $parser XMLParser reference to the xml parser
397 * @param string $data Character data
398 * @throws MWException on invalid data
400 function char( $parser, $data ) {
402 $data = trim( $data );
403 if ( trim( $data ) === "" ) {
407 if ( !isset( $this->mode
[0] ) ) {
408 throw new MWException( 'Unexpected character data before first rdf:Description element' );
411 if ( $this->mode
[0] === self
::MODE_IGNORE
) {
415 if ( $this->mode
[0] !== self
::MODE_SIMPLE
416 && $this->mode
[0] !== self
::MODE_QDESC
418 throw new MWException( 'character data where not expected. (mode ' . $this->mode
[0] . ')' );
421 // to check, how does this handle w.s.
422 if ( $this->charContent
=== false ) {
423 $this->charContent
= $data;
425 $this->charContent
.= $data;
429 /** When we hit a closing element in MODE_IGNORE
430 * Check to see if this is the element we started to ignore,
431 * in which case we get out of MODE_IGNORE
433 * @param string $elm Namespace of element followed by a space and then tag name of element.
435 private function endElementModeIgnore( $elm ) {
436 if ( $this->curItem
[0] === $elm ) {
437 array_shift( $this->curItem
);
438 array_shift( $this->mode
);
443 * Hit a closing element when in MODE_SIMPLE.
444 * This generally means that we finished processing a
445 * property value, and now have to save the result to the
448 * For example, when processing:
449 * <exif:DigitalZoomRatio>0/10</exif:DigitalZoomRatio>
450 * this deals with when we hit </exif:DigitalZoomRatio>.
452 * Or it could be if we hit the end element of a property
453 * of a compound data structure (like a member of an array).
455 * @param string $elm namespace, space, and tag name.
457 private function endElementModeSimple( $elm ) {
458 if ( $this->charContent
!== false ) {
459 if ( $this->processingArray
) {
460 // if we're processing an array, use the original element
461 // name instead of rdf:li.
462 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
464 list( $ns, $tag ) = explode( ' ', $elm, 2 );
466 $this->saveValue( $ns, $tag, $this->charContent
);
468 $this->charContent
= false; // reset
470 array_shift( $this->curItem
);
471 array_shift( $this->mode
);
475 * Hit a closing element in MODE_STRUCT, MODE_SEQ, MODE_BAG
476 * generally means we've finished processing a nested structure.
477 * resets some internal variables to indicate that.
479 * Note this means we hit the closing element not the "</rdf:Seq>".
481 * @par For example, when processing:
483 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
484 * </rdf:Seq> </exif:ISOSpeedRatings>
487 * This method is called when we hit the "</exif:ISOSpeedRatings>" tag.
489 * @param string $elm namespace . space . tag name.
490 * @throws MWException
492 private function endElementNested( $elm ) {
494 /* cur item must be the same as $elm, unless if in MODE_STRUCT
495 in which case it could also be rdf:Description */
496 if ( $this->curItem
[0] !== $elm
497 && !( $elm === self
::NS_RDF
. ' Description'
498 && $this->mode
[0] === self
::MODE_STRUCT
)
500 throw new MWException( "nesting mismatch. got a </$elm> but expected a </" .
501 $this->curItem
[0] . '>' );
504 // Validate structures.
505 list( $ns, $tag ) = explode( ' ', $elm, 2 );
506 if ( isset( $this->items
[$ns][$tag]['validate'] ) ) {
508 $info =& $this->items
[$ns][$tag];
509 $finalName = isset( $info['map_name'] )
510 ?
$info['map_name'] : $tag;
512 $validate = is_array( $info['validate'] ) ?
$info['validate']
513 : array( 'XMPValidate', $info['validate'] );
515 if ( !isset( $this->results
['xmp-' . $info['map_group']][$finalName] ) ) {
516 // This can happen if all the members of the struct failed validation.
517 wfDebugLog( 'XMP', __METHOD__
. " <$ns:$tag> has no valid members." );
518 } elseif ( is_callable( $validate ) ) {
519 $val =& $this->results
['xmp-' . $info['map_group']][$finalName];
520 call_user_func_array( $validate, array( $info, &$val, false ) );
521 if ( is_null( $val ) ) {
522 // the idea being the validation function will unset the variable if
524 wfDebugLog( 'XMP', __METHOD__
. " <$ns:$tag> failed validation." );
525 unset( $this->results
['xmp-' . $info['map_group']][$finalName] );
528 wfDebugLog( 'XMP', __METHOD__
. " Validation function for $finalName ("
529 . $validate[0] . '::' . $validate[1] . '()) is not callable.' );
533 array_shift( $this->curItem
);
534 array_shift( $this->mode
);
535 $this->ancestorStruct
= false;
536 $this->processingArray
= false;
537 $this->itemLang
= false;
541 * Hit a closing element in MODE_LI (either rdf:Seq, or rdf:Bag )
542 * Add information about what type of element this is.
544 * Note we still have to hit the outer "</property>"
546 * @par For example, when processing:
548 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
549 * </rdf:Seq> </exif:ISOSpeedRatings>
552 * This method is called when we hit the "</rdf:Seq>".
553 * (For comparison, we call endElementModeSimple when we
554 * hit the "</rdf:li>")
556 * @param string $elm namespace . ' ' . element name
557 * @throws MWException
559 private function endElementModeLi( $elm ) {
561 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
562 $info = $this->items
[$ns][$tag];
563 $finalName = isset( $info['map_name'] )
564 ?
$info['map_name'] : $tag;
566 array_shift( $this->mode
);
568 if ( !isset( $this->results
['xmp-' . $info['map_group']][$finalName] ) ) {
569 wfDebugLog( 'XMP', __METHOD__
. " Empty compund element $finalName." );
574 if ( $elm === self
::NS_RDF
. ' Seq' ) {
575 $this->results
['xmp-' . $info['map_group']][$finalName]['_type'] = 'ol';
576 } elseif ( $elm === self
::NS_RDF
. ' Bag' ) {
577 $this->results
['xmp-' . $info['map_group']][$finalName]['_type'] = 'ul';
578 } elseif ( $elm === self
::NS_RDF
. ' Alt' ) {
579 // extra if needed as you could theoretically have a non-language alt.
580 if ( $info['mode'] === self
::MODE_LANG
) {
581 $this->results
['xmp-' . $info['map_group']][$finalName]['_type'] = 'lang';
584 throw new MWException( __METHOD__
. " expected </rdf:seq> or </rdf:bag> but instead got $elm." );
589 * End element while in MODE_QDESC
590 * mostly when ending an element when we have a simple value
591 * that has qualifiers.
593 * Qualifiers aren't all that common, and we don't do anything
596 * @param string $elm namespace and element
598 private function endElementModeQDesc( $elm ) {
600 if ( $elm === self
::NS_RDF
. ' value' ) {
601 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
602 $this->saveValue( $ns, $tag, $this->charContent
);
606 array_shift( $this->mode
);
607 array_shift( $this->curItem
);
612 * Handler for hitting a closing element.
614 * generally just calls a helper function depending on what
617 * Ignores the outer wrapping elements that are optional in
618 * xmp and have no meaning.
620 * @param $parser XMLParser
621 * @param string $elm namespace . ' ' . element name
622 * @throws MWException
624 function endElement( $parser, $elm ) {
625 if ( $elm === ( self
::NS_RDF
. ' RDF' )
626 ||
$elm === 'adobe:ns:meta/ xmpmeta'
627 ||
$elm === 'adobe:ns:meta/ xapmeta'
633 if ( $elm === self
::NS_RDF
. ' type' ) {
634 // these aren't really supported properly yet.
635 // However, it appears they almost never used.
636 wfDebugLog( 'XMP', __METHOD__
. ' encountered <rdf:type>' );
639 if ( strpos( $elm, ' ' ) === false ) {
640 // This probably shouldn't happen.
641 // However, there is a bug in an adobe product
642 // that forgets the namespace on some things.
643 // (Luckily they are unimportant things).
644 wfDebugLog( 'XMP', __METHOD__
. " Encountered </$elm> which has no namespace. Skipping." );
649 if ( count( $this->mode
[0] ) === 0 ) {
650 // This should never ever happen and means
651 // there is a pretty major bug in this class.
652 throw new MWException( 'Encountered end element with no mode' );
655 if ( count( $this->curItem
) == 0 && $this->mode
[0] !== self
::MODE_INITIAL
) {
656 // just to be paranoid. Should always have a curItem, except for initially
657 // (aka during MODE_INITAL).
658 throw new MWException( "Hit end element </$elm> but no curItem" );
661 switch ( $this->mode
[0] ) {
662 case self
::MODE_IGNORE
:
663 $this->endElementModeIgnore( $elm );
665 case self
::MODE_SIMPLE
:
666 $this->endElementModeSimple( $elm );
668 case self
::MODE_STRUCT
:
671 case self
::MODE_LANG
:
672 case self
::MODE_BAGSTRUCT
:
673 $this->endElementNested( $elm );
675 case self
::MODE_INITIAL
:
676 if ( $elm === self
::NS_RDF
. ' Description' ) {
677 array_shift( $this->mode
);
679 throw new MWException( 'Element ended unexpectedly while in MODE_INITIAL' );
683 case self
::MODE_LI_LANG
:
684 $this->endElementModeLi( $elm );
686 case self
::MODE_QDESC
:
687 $this->endElementModeQDesc( $elm );
690 wfDebugLog( 'XMP', __METHOD__
. " no mode (elm = $elm)" );
696 * Hit an opening element while in MODE_IGNORE
698 * XMP is extensible, so ignore any tag we don't understand.
700 * Mostly ignores, unless we encounter the element that we are ignoring.
701 * in which case we add it to the item stack, so we can ignore things
702 * that are nested, correctly.
704 * @param string $elm namespace . ' ' . tag name
706 private function startElementModeIgnore( $elm ) {
707 if ( $elm === $this->curItem
[0] ) {
708 array_unshift( $this->curItem
, $elm );
709 array_unshift( $this->mode
, self
::MODE_IGNORE
);
714 * Start element in MODE_BAG (unordered array)
715 * this should always be <rdf:Bag>
717 * @param string $elm namespace . ' ' . tag
718 * @throws MWException if we have an element that's not <rdf:Bag>
720 private function startElementModeBag( $elm ) {
721 if ( $elm === self
::NS_RDF
. ' Bag' ) {
722 array_unshift( $this->mode
, self
::MODE_LI
);
724 throw new MWException( "Expected <rdf:Bag> but got $elm." );
729 * Start element in MODE_SEQ (ordered array)
730 * this should always be <rdf:Seq>
732 * @param string $elm namespace . ' ' . tag
733 * @throws MWException if we have an element that's not <rdf:Seq>
735 private function startElementModeSeq( $elm ) {
736 if ( $elm === self
::NS_RDF
. ' Seq' ) {
737 array_unshift( $this->mode
, self
::MODE_LI
);
738 } elseif ( $elm === self
::NS_RDF
. ' Bag' ) {
740 wfDebugLog( 'XMP', __METHOD__
. ' Expected an rdf:Seq, but got an rdf:Bag. Pretending'
741 . ' it is a Seq, since some buggy software is known to screw this up.' );
742 array_unshift( $this->mode
, self
::MODE_LI
);
744 throw new MWException( "Expected <rdf:Seq> but got $elm." );
749 * Start element in MODE_LANG (language alternative)
750 * this should always be <rdf:Alt>
752 * This tag tends to be used for metadata like describe this
753 * picture, which can be translated into multiple languages.
755 * XMP supports non-linguistic alternative selections,
756 * which are really only used for thumbnails, which
757 * we don't care about.
759 * @param string $elm namespace . ' ' . tag
760 * @throws MWException if we have an element that's not <rdf:Alt>
762 private function startElementModeLang( $elm ) {
763 if ( $elm === self
::NS_RDF
. ' Alt' ) {
764 array_unshift( $this->mode
, self
::MODE_LI_LANG
);
766 throw new MWException( "Expected <rdf:Seq> but got $elm." );
771 * Handle an opening element when in MODE_SIMPLE
773 * This should not happen often. This is for if a simple element
774 * already opened has a child element. Could happen for a
778 * <exif:DigitalZoomRatio><rdf:Description><rdf:value>0/10</rdf:value>
779 * <foo:someQualifier>Bar</foo:someQualifier> </rdf:Description>
780 * </exif:DigitalZoomRatio>
782 * This method is called when processing the <rdf:Description> element
784 * @param string $elm namespace and tag names separated by space.
785 * @param array $attribs Attributes of the element.
786 * @throws MWException
788 private function startElementModeSimple( $elm, $attribs ) {
789 if ( $elm === self
::NS_RDF
. ' Description' ) {
790 // If this value has qualifiers
791 array_unshift( $this->mode
, self
::MODE_QDESC
);
792 array_unshift( $this->curItem
, $this->curItem
[0] );
794 if ( isset( $attribs[self
::NS_RDF
. ' value'] ) ) {
795 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
796 $this->saveValue( $ns, $tag, $attribs[self
::NS_RDF
. ' value'] );
798 } elseif ( $elm === self
::NS_RDF
. ' value' ) {
799 // This should not be here.
800 throw new MWException( __METHOD__
. ' Encountered <rdf:value> where it was unexpected.' );
802 // something else we don't recognize, like a qualifier maybe.
803 wfDebugLog( 'XMP', __METHOD__
.
804 " Encountered element <$elm> where only expecting character data as value of " .
806 array_unshift( $this->mode
, self
::MODE_IGNORE
);
807 array_unshift( $this->curItem
, $elm );
812 * Start an element when in MODE_QDESC.
813 * This generally happens when a simple element has an inner
814 * rdf:Description to hold qualifier elements.
817 * <exif:DigitalZoomRatio><rdf:Description><rdf:value>0/10</rdf:value>
818 * <foo:someQualifier>Bar</foo:someQualifier> </rdf:Description>
819 * </exif:DigitalZoomRatio>
820 * Called when processing the <rdf:value> or <foo:someQualifier>.
822 * @param string $elm namespace and tag name separated by a space.
825 private function startElementModeQDesc( $elm ) {
826 if ( $elm === self
::NS_RDF
. ' value' ) {
827 return; // do nothing
829 // otherwise its a qualifier, which we ignore
830 array_unshift( $this->mode
, self
::MODE_IGNORE
);
831 array_unshift( $this->curItem
, $elm );
836 * Starting an element when in MODE_INITIAL
837 * This usually happens when we hit an element inside
838 * the outer rdf:Description
840 * This is generally where most properties start.
842 * @param string $ns Namespace
843 * @param string $tag tag name (without namespace prefix)
844 * @param array $attribs array of attributes
845 * @throws MWException
847 private function startElementModeInitial( $ns, $tag, $attribs ) {
848 if ( $ns !== self
::NS_RDF
) {
850 if ( isset( $this->items
[$ns][$tag] ) ) {
851 if ( isset( $this->items
[$ns][$tag]['structPart'] ) ) {
852 // If this element is supposed to appear only as
853 // a child of a structure, but appears here (not as
854 // a child of a struct), then something weird is
855 // happening, so ignore this element and its children.
857 wfDebugLog( 'XMP', "Encountered <$ns:$tag> outside"
858 . " of its expected parent. Ignoring." );
860 array_unshift( $this->mode
, self
::MODE_IGNORE
);
861 array_unshift( $this->curItem
, $ns . ' ' . $tag );
865 $mode = $this->items
[$ns][$tag]['mode'];
866 array_unshift( $this->mode
, $mode );
867 array_unshift( $this->curItem
, $ns . ' ' . $tag );
868 if ( $mode === self
::MODE_STRUCT
) {
869 $this->ancestorStruct
= isset( $this->items
[$ns][$tag]['map_name'] )
870 ?
$this->items
[$ns][$tag]['map_name'] : $tag;
872 if ( $this->charContent
!== false ) {
874 // Should not happen in valid XMP.
875 throw new MWException( 'tag nested in non-whitespace characters.' );
878 // This element is not on our list of allowed elements so ignore.
879 wfDebugLog( 'XMP', __METHOD__
. " Ignoring unrecognized element <$ns:$tag>." );
880 array_unshift( $this->mode
, self
::MODE_IGNORE
);
881 array_unshift( $this->curItem
, $ns . ' ' . $tag );
886 // process attributes
887 $this->doAttribs( $attribs );
891 * Hit an opening element when in a Struct (MODE_STRUCT)
892 * This is generally for fields of a compound property.
894 * Example of a struct (abbreviated; flash has more properties):
896 * <exif:Flash> <rdf:Description> <exif:Fired>True</exif:Fired>
897 * <exif:Mode>1</exif:Mode></rdf:Description></exif:Flash>
901 * <exif:Flash rdf:parseType='Resource'> <exif:Fired>True</exif:Fired>
902 * <exif:Mode>1</exif:Mode></exif:Flash>
904 * @param string $ns namespace
905 * @param string $tag tag name (no ns)
906 * @param array $attribs array of attribs w/ values.
907 * @throws MWException
909 private function startElementModeStruct( $ns, $tag, $attribs ) {
910 if ( $ns !== self
::NS_RDF
) {
912 if ( isset( $this->items
[$ns][$tag] ) ) {
913 if ( isset( $this->items
[$ns][$this->ancestorStruct
]['children'] )
914 && !isset( $this->items
[$ns][$this->ancestorStruct
]['children'][$tag] )
916 // This assumes that we don't have inter-namespace nesting
917 // which we don't in all the properties we're interested in.
918 throw new MWException( " <$tag> appeared nested in <" . $this->ancestorStruct
919 . "> where it is not allowed." );
921 array_unshift( $this->mode
, $this->items
[$ns][$tag]['mode'] );
922 array_unshift( $this->curItem
, $ns . ' ' . $tag );
923 if ( $this->charContent
!== false ) {
925 // Should not happen in valid XMP.
926 throw new MWException( "tag <$tag> nested in non-whitespace characters (" .
927 $this->charContent
. ")." );
930 array_unshift( $this->mode
, self
::MODE_IGNORE
);
931 array_unshift( $this->curItem
, $elm );
937 if ( $ns === self
::NS_RDF
&& $tag === 'Description' ) {
938 $this->doAttribs( $attribs );
939 array_unshift( $this->mode
, self
::MODE_STRUCT
);
940 array_unshift( $this->curItem
, $this->curItem
[0] );
945 * opening element in MODE_LI
946 * process elements of arrays.
949 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
950 * </rdf:Seq> </exif:ISOSpeedRatings>
951 * This method is called when we hit the <rdf:li> element.
953 * @param string $elm namespace . ' ' . tagname
954 * @param array $attribs Attributes. (needed for BAGSTRUCTS)
955 * @throws MWException if gets a tag other than <rdf:li>
957 private function startElementModeLi( $elm, $attribs ) {
958 if ( ( $elm ) !== self
::NS_RDF
. ' li' ) {
959 throw new MWException( "<rdf:li> expected but got $elm." );
962 if ( !isset( $this->mode
[1] ) ) {
963 // This should never ever ever happen. Checking for it
965 throw new MWException( 'In mode Li, but no 2xPrevious mode!' );
968 if ( $this->mode
[1] === self
::MODE_BAGSTRUCT
) {
969 // This list item contains a compound (STRUCT) value.
970 array_unshift( $this->mode
, self
::MODE_STRUCT
);
971 array_unshift( $this->curItem
, $elm );
972 $this->processingArray
= true;
974 if ( !isset( $this->curItem
[1] ) ) {
976 throw new MWException( 'Can not find parent of BAGSTRUCT.' );
978 list( $curNS, $curTag ) = explode( ' ', $this->curItem
[1] );
979 $this->ancestorStruct
= isset( $this->items
[$curNS][$curTag]['map_name'] )
980 ?
$this->items
[$curNS][$curTag]['map_name'] : $curTag;
982 $this->doAttribs( $attribs );
984 // Normal BAG or SEQ containing simple values.
985 array_unshift( $this->mode
, self
::MODE_SIMPLE
);
986 // need to add curItem[0] on again since one is for the specific item
987 // and one is for the entire group.
988 array_unshift( $this->curItem
, $this->curItem
[0] );
989 $this->processingArray
= true;
994 * Opening element in MODE_LI_LANG.
995 * process elements of language alternatives
998 * <dc:title> <rdf:Alt> <rdf:li xml:lang="x-default">My house
999 * </rdf:li> </rdf:Alt> </dc:title>
1001 * This method is called when we hit the <rdf:li> element.
1003 * @param string $elm namespace . ' ' . tag
1004 * @param array $attribs array of elements (most importantly xml:lang)
1005 * @throws MWException if gets a tag other than <rdf:li> or if no xml:lang
1007 private function startElementModeLiLang( $elm, $attribs ) {
1008 if ( $elm !== self
::NS_RDF
. ' li' ) {
1009 throw new MWException( __METHOD__
. " <rdf:li> expected but got $elm." );
1011 if ( !isset( $attribs[self
::NS_XML
. ' lang'] )
1012 ||
!preg_match( '/^[-A-Za-z0-9]{2,}$/D', $attribs[self
::NS_XML
. ' lang'] )
1014 throw new MWException( __METHOD__
1015 . " <rdf:li> did not contain, or has invalid xml:lang attribute in lang alternative" );
1018 // Lang is case-insensitive.
1019 $this->itemLang
= strtolower( $attribs[self
::NS_XML
. ' lang'] );
1021 // need to add curItem[0] on again since one is for the specific item
1022 // and one is for the entire group.
1023 array_unshift( $this->curItem
, $this->curItem
[0] );
1024 array_unshift( $this->mode
, self
::MODE_SIMPLE
);
1025 $this->processingArray
= true;
1029 * Hits an opening element.
1030 * Generally just calls a helper based on what MODE we're in.
1031 * Also does some initial set up for the wrapper element
1033 * @param $parser XMLParser
1034 * @param string $elm namespace "<space>" element
1035 * @param array $attribs attribute name => value
1036 * @throws MWException
1038 function startElement( $parser, $elm, $attribs ) {
1040 if ( $elm === self
::NS_RDF
. ' RDF'
1041 ||
$elm === 'adobe:ns:meta/ xmpmeta'
1042 ||
$elm === 'adobe:ns:meta/ xapmeta'
1046 } elseif ( $elm === self
::NS_RDF
. ' Description' ) {
1047 if ( count( $this->mode
) === 0 ) {
1049 array_unshift( $this->mode
, self
::MODE_INITIAL
);
1051 } elseif ( $elm === self
::NS_RDF
. ' type' ) {
1052 // This doesn't support rdf:type properly.
1053 // In practise I have yet to see a file that
1054 // uses this element, however it is mentioned
1055 // on page 25 of part 1 of the xmp standard.
1057 // also it seems as if exiv2 and exiftool do not support
1058 // this either (That or I misunderstand the standard)
1059 wfDebugLog( 'XMP', __METHOD__
. ' Encountered <rdf:type> which isn\'t currently supported' );
1062 if ( strpos( $elm, ' ' ) === false ) {
1063 // This probably shouldn't happen.
1064 wfDebugLog( 'XMP', __METHOD__
. " Encountered <$elm> which has no namespace. Skipping." );
1069 list( $ns, $tag ) = explode( ' ', $elm, 2 );
1071 if ( count( $this->mode
) === 0 ) {
1072 // This should not happen.
1073 throw new MWException( 'Error extracting XMP, '
1074 . "encountered <$elm> with no mode" );
1077 switch ( $this->mode
[0] ) {
1078 case self
::MODE_IGNORE
:
1079 $this->startElementModeIgnore( $elm );
1081 case self
::MODE_SIMPLE
:
1082 $this->startElementModeSimple( $elm, $attribs );
1084 case self
::MODE_INITIAL
:
1085 $this->startElementModeInitial( $ns, $tag, $attribs );
1087 case self
::MODE_STRUCT
:
1088 $this->startElementModeStruct( $ns, $tag, $attribs );
1090 case self
::MODE_BAG
:
1091 case self
::MODE_BAGSTRUCT
:
1092 $this->startElementModeBag( $elm );
1094 case self
::MODE_SEQ
:
1095 $this->startElementModeSeq( $elm );
1097 case self
::MODE_LANG
:
1098 $this->startElementModeLang( $elm );
1100 case self
::MODE_LI_LANG
:
1101 $this->startElementModeLiLang( $elm, $attribs );
1104 $this->startElementModeLi( $elm, $attribs );
1106 case self
::MODE_QDESC
:
1107 $this->startElementModeQDesc( $elm );
1110 throw new MWException( 'StartElement in unknown mode: ' . $this->mode
[0] );
1115 * Process attributes.
1116 * Simple values can be stored as either a tag or attribute
1118 * Often the initial "<rdf:Description>" tag just has all the simple
1119 * properties as attributes.
1123 * <rdf:Description rdf:about="" xmlns:exif="http://ns.adobe.com/exif/1.0/" exif:DigitalZoomRatio="0/10">
1126 * @param array $attribs attribute=>value array.
1127 * @throws MWException
1129 private function doAttribs( $attribs ) {
1130 // first check for rdf:parseType attribute, as that can change
1131 // how the attributes are interperted.
1133 if ( isset( $attribs[self
::NS_RDF
. ' parseType'] )
1134 && $attribs[self
::NS_RDF
. ' parseType'] === 'Resource'
1135 && $this->mode
[0] === self
::MODE_SIMPLE
1137 // this is equivalent to having an inner rdf:Description
1138 $this->mode
[0] = self
::MODE_QDESC
;
1140 foreach ( $attribs as $name => $val ) {
1141 if ( strpos( $name, ' ' ) === false ) {
1142 // This shouldn't happen, but so far some old software forgets namespace
1144 wfDebugLog( 'XMP', __METHOD__
. ' Encountered non-namespaced attribute: '
1145 . " $name=\"$val\". Skipping. " );
1148 list( $ns, $tag ) = explode( ' ', $name, 2 );
1149 if ( $ns === self
::NS_RDF
) {
1150 if ( $tag === 'value' ||
$tag === 'resource' ) {
1151 // resource is for url.
1152 // value attribute is a weird way of just putting the contents.
1153 $this->char( $this->xmlParser
, $val );
1155 } elseif ( isset( $this->items
[$ns][$tag] ) ) {
1156 if ( $this->mode
[0] === self
::MODE_SIMPLE
) {
1157 throw new MWException( __METHOD__
1158 . " $ns:$tag found as attribute where not allowed" );
1160 $this->saveValue( $ns, $tag, $val );
1162 wfDebugLog( 'XMP', __METHOD__
. " Ignoring unrecognized element <$ns:$tag>." );
1168 * Given an extracted value, save it to results array
1170 * note also uses $this->ancestorStruct and
1171 * $this->processingArray to determine what name to
1172 * save the value under. (in addition to $tag).
1174 * @param string $ns namespace of tag this is for
1175 * @param string $tag tag name
1176 * @param string $val value to save
1178 private function saveValue( $ns, $tag, $val ) {
1180 $info =& $this->items
[$ns][$tag];
1181 $finalName = isset( $info['map_name'] )
1182 ?
$info['map_name'] : $tag;
1183 if ( isset( $info['validate'] ) ) {
1184 $validate = is_array( $info['validate'] ) ?
$info['validate']
1185 : array( 'XMPValidate', $info['validate'] );
1187 if ( is_callable( $validate ) ) {
1188 call_user_func_array( $validate, array( $info, &$val, true ) );
1189 // the reasoning behind using &$val instead of using the return value
1190 // is to be consistent between here and validating structures.
1191 if ( is_null( $val ) ) {
1192 wfDebugLog( 'XMP', __METHOD__
. " <$ns:$tag> failed validation." );
1197 wfDebugLog( 'XMP', __METHOD__
. " Validation function for $finalName ("
1198 . $validate[0] . '::' . $validate[1] . '()) is not callable.' );
1202 if ( $this->ancestorStruct
&& $this->processingArray
) {
1203 // Aka both an array and a struct. ( self::MODE_BAGSTRUCT )
1204 $this->results
['xmp-' . $info['map_group']][$this->ancestorStruct
][][$finalName] = $val;
1205 } elseif ( $this->ancestorStruct
) {
1206 $this->results
['xmp-' . $info['map_group']][$this->ancestorStruct
][$finalName] = $val;
1207 } elseif ( $this->processingArray
) {
1208 if ( $this->itemLang
=== false ) {
1210 $this->results
['xmp-' . $info['map_group']][$finalName][] = $val;
1213 $this->results
['xmp-' . $info['map_group']][$finalName][$this->itemLang
] = $val;
1216 $this->results
['xmp-' . $info['map_group']][$finalName] = $val;