36e967eabc0daf1efd0c84b8f7c369233b3cd428
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__
. " Ignoring XMPExtended block due to wrong guid (guid= '$guid')" );
336 $len = unpack( 'Nlength/Noffset', substr( $content, 32, 8 ) );
338 if ( !$len ||
$len['length'] < 4 ||
$len['offset'] < 0 ||
$len['offset'] > $len['length'] ) {
339 wfDebugLog( 'XMP', __METHOD__
. 'Error reading extended XMP block, invalid length or offset.' );
344 // we're not very robust here. we should accept it in the wrong order. To quote
346 // "A JPEG writer should write the ExtendedXMP marker segments in order, immediately following the
347 // StandardXMP. However, the JPEG standard does not require preservation of marker segment order. A
348 // robust JPEG reader should tolerate the marker segments in any order."
350 // otoh the probability that an image will have more than 128k of metadata is rather low...
351 // so the probability that it will have > 128k, and be in the wrong order is very low...
353 if ( $len['offset'] !== $this->extendedXMPOffset
) {
354 wfDebugLog( 'XMP', __METHOD__
. 'Ignoring XMPExtended block due to wrong order. (Offset was '
355 . $len['offset'] . ' but expected ' . $this->extendedXMPOffset
. ')' );
360 if ( $len['offset'] === 0 ) {
361 // if we're starting the extended block, we've probably already
362 // done the XMPStandard block, so reset.
363 $this->resetXMLParser();
366 $this->extendedXMPOffset +
= $len['length'];
368 $actualContent = substr( $content, 40 );
370 if ( $this->extendedXMPOffset
=== strlen( $actualContent ) ) {
376 wfDebugLog( 'XMP', __METHOD__
. 'Parsing a XMPExtended block' );
378 return $this->parse( $actualContent, $atEnd );
382 * Character data handler
383 * Called whenever character data is found in the xmp document.
385 * does nothing if we're in MODE_IGNORE or if the data is whitespace
386 * throws an error if we're not in MODE_SIMPLE (as we're not allowed to have character
387 * data in the other modes).
389 * As an example, this happens when we encounter XMP like:
390 * <exif:DigitalZoomRatio>0/10</exif:DigitalZoomRatio>
391 * and are processing the 0/10 bit.
393 * @param $parser XMLParser reference to the xml parser
394 * @param string $data Character data
395 * @throws MWException on invalid data
397 function char( $parser, $data ) {
399 $data = trim( $data );
400 if ( trim( $data ) === "" ) {
404 if ( !isset( $this->mode
[0] ) ) {
405 throw new MWException( 'Unexpected character data before first rdf:Description element' );
408 if ( $this->mode
[0] === self
::MODE_IGNORE
) {
412 if ( $this->mode
[0] !== self
::MODE_SIMPLE
413 && $this->mode
[0] !== self
::MODE_QDESC
415 throw new MWException( 'character data where not expected. (mode ' . $this->mode
[0] . ')' );
418 // to check, how does this handle w.s.
419 if ( $this->charContent
=== false ) {
420 $this->charContent
= $data;
422 $this->charContent
.= $data;
426 /** When we hit a closing element in MODE_IGNORE
427 * Check to see if this is the element we started to ignore,
428 * in which case we get out of MODE_IGNORE
430 * @param string $elm Namespace of element followed by a space and then tag name of element.
432 private function endElementModeIgnore( $elm ) {
433 if ( $this->curItem
[0] === $elm ) {
434 array_shift( $this->curItem
);
435 array_shift( $this->mode
);
440 * Hit a closing element when in MODE_SIMPLE.
441 * This generally means that we finished processing a
442 * property value, and now have to save the result to the
445 * For example, when processing:
446 * <exif:DigitalZoomRatio>0/10</exif:DigitalZoomRatio>
447 * this deals with when we hit </exif:DigitalZoomRatio>.
449 * Or it could be if we hit the end element of a property
450 * of a compound data structure (like a member of an array).
452 * @param string $elm namespace, space, and tag name.
454 private function endElementModeSimple( $elm ) {
455 if ( $this->charContent
!== false ) {
456 if ( $this->processingArray
) {
457 // if we're processing an array, use the original element
458 // name instead of rdf:li.
459 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
461 list( $ns, $tag ) = explode( ' ', $elm, 2 );
463 $this->saveValue( $ns, $tag, $this->charContent
);
465 $this->charContent
= false; // reset
467 array_shift( $this->curItem
);
468 array_shift( $this->mode
);
472 * Hit a closing element in MODE_STRUCT, MODE_SEQ, MODE_BAG
473 * generally means we've finished processing a nested structure.
474 * resets some internal variables to indicate that.
476 * Note this means we hit the closing element not the "</rdf:Seq>".
478 * @par For example, when processing:
480 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
481 * </rdf:Seq> </exif:ISOSpeedRatings>
484 * This method is called when we hit the "</exif:ISOSpeedRatings>" tag.
486 * @param string $elm namespace . space . tag name.
487 * @throws MWException
489 private function endElementNested( $elm ) {
491 /* cur item must be the same as $elm, unless if in MODE_STRUCT
492 in which case it could also be rdf:Description */
493 if ( $this->curItem
[0] !== $elm
494 && !( $elm === self
::NS_RDF
. ' Description'
495 && $this->mode
[0] === self
::MODE_STRUCT
)
497 throw new MWException( "nesting mismatch. got a </$elm> but expected a </" . $this->curItem
[0] . '>' );
500 // Validate structures.
501 list( $ns, $tag ) = explode( ' ', $elm, 2 );
502 if ( isset( $this->items
[$ns][$tag]['validate'] ) ) {
504 $info =& $this->items
[$ns][$tag];
505 $finalName = isset( $info['map_name'] )
506 ?
$info['map_name'] : $tag;
508 $validate = is_array( $info['validate'] ) ?
$info['validate']
509 : array( 'XMPValidate', $info['validate'] );
511 if ( !isset( $this->results
['xmp-' . $info['map_group']][$finalName] ) ) {
512 // This can happen if all the members of the struct failed validation.
513 wfDebugLog( 'XMP', __METHOD__
. " <$ns:$tag> has no valid members." );
514 } elseif ( is_callable( $validate ) ) {
515 $val =& $this->results
['xmp-' . $info['map_group']][$finalName];
516 call_user_func_array( $validate, array( $info, &$val, false ) );
517 if ( is_null( $val ) ) {
518 // the idea being the validation function will unset the variable if
520 wfDebugLog( 'XMP', __METHOD__
. " <$ns:$tag> failed validation." );
521 unset( $this->results
['xmp-' . $info['map_group']][$finalName] );
524 wfDebugLog( 'XMP', __METHOD__
. " Validation function for $finalName ("
525 . $validate[0] . '::' . $validate[1] . '()) is not callable.' );
529 array_shift( $this->curItem
);
530 array_shift( $this->mode
);
531 $this->ancestorStruct
= false;
532 $this->processingArray
= false;
533 $this->itemLang
= false;
537 * Hit a closing element in MODE_LI (either rdf:Seq, or rdf:Bag )
538 * Add information about what type of element this is.
540 * Note we still have to hit the outer "</property>"
542 * @par For example, when processing:
544 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
545 * </rdf:Seq> </exif:ISOSpeedRatings>
548 * This method is called when we hit the "</rdf:Seq>".
549 * (For comparison, we call endElementModeSimple when we
550 * hit the "</rdf:li>")
552 * @param string $elm namespace . ' ' . element name
553 * @throws MWException
555 private function endElementModeLi( $elm ) {
557 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
558 $info = $this->items
[$ns][$tag];
559 $finalName = isset( $info['map_name'] )
560 ?
$info['map_name'] : $tag;
562 array_shift( $this->mode
);
564 if ( !isset( $this->results
['xmp-' . $info['map_group']][$finalName] ) ) {
565 wfDebugLog( 'XMP', __METHOD__
. " Empty compund element $finalName." );
570 if ( $elm === self
::NS_RDF
. ' Seq' ) {
571 $this->results
['xmp-' . $info['map_group']][$finalName]['_type'] = 'ol';
572 } elseif ( $elm === self
::NS_RDF
. ' Bag' ) {
573 $this->results
['xmp-' . $info['map_group']][$finalName]['_type'] = 'ul';
574 } elseif ( $elm === self
::NS_RDF
. ' Alt' ) {
575 // extra if needed as you could theoretically have a non-language alt.
576 if ( $info['mode'] === self
::MODE_LANG
) {
577 $this->results
['xmp-' . $info['map_group']][$finalName]['_type'] = 'lang';
580 throw new MWException( __METHOD__
. " expected </rdf:seq> or </rdf:bag> but instead got $elm." );
585 * End element while in MODE_QDESC
586 * mostly when ending an element when we have a simple value
587 * that has qualifiers.
589 * Qualifiers aren't all that common, and we don't do anything
592 * @param string $elm namespace and element
594 private function endElementModeQDesc( $elm ) {
596 if ( $elm === self
::NS_RDF
. ' value' ) {
597 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
598 $this->saveValue( $ns, $tag, $this->charContent
);
602 array_shift( $this->mode
);
603 array_shift( $this->curItem
);
608 * Handler for hitting a closing element.
610 * generally just calls a helper function depending on what
613 * Ignores the outer wrapping elements that are optional in
614 * xmp and have no meaning.
616 * @param $parser XMLParser
617 * @param string $elm namespace . ' ' . element name
618 * @throws MWException
620 function endElement( $parser, $elm ) {
621 if ( $elm === ( self
::NS_RDF
. ' RDF' )
622 ||
$elm === 'adobe:ns:meta/ xmpmeta'
623 ||
$elm === 'adobe:ns:meta/ xapmeta'
629 if ( $elm === self
::NS_RDF
. ' type' ) {
630 // these aren't really supported properly yet.
631 // However, it appears they almost never used.
632 wfDebugLog( 'XMP', __METHOD__
. ' encountered <rdf:type>' );
635 if ( strpos( $elm, ' ' ) === false ) {
636 // This probably shouldn't happen.
637 // However, there is a bug in an adobe product
638 // that forgets the namespace on some things.
639 // (Luckily they are unimportant things).
640 wfDebugLog( 'XMP', __METHOD__
. " Encountered </$elm> which has no namespace. Skipping." );
645 if ( count( $this->mode
[0] ) === 0 ) {
646 // This should never ever happen and means
647 // there is a pretty major bug in this class.
648 throw new MWException( 'Encountered end element with no mode' );
651 if ( count( $this->curItem
) == 0 && $this->mode
[0] !== self
::MODE_INITIAL
) {
652 // just to be paranoid. Should always have a curItem, except for initially
653 // (aka during MODE_INITAL).
654 throw new MWException( "Hit end element </$elm> but no curItem" );
657 switch ( $this->mode
[0] ) {
658 case self
::MODE_IGNORE
:
659 $this->endElementModeIgnore( $elm );
661 case self
::MODE_SIMPLE
:
662 $this->endElementModeSimple( $elm );
664 case self
::MODE_STRUCT
:
667 case self
::MODE_LANG
:
668 case self
::MODE_BAGSTRUCT
:
669 $this->endElementNested( $elm );
671 case self
::MODE_INITIAL
:
672 if ( $elm === self
::NS_RDF
. ' Description' ) {
673 array_shift( $this->mode
);
675 throw new MWException( 'Element ended unexpectedly while in MODE_INITIAL' );
679 case self
::MODE_LI_LANG
:
680 $this->endElementModeLi( $elm );
682 case self
::MODE_QDESC
:
683 $this->endElementModeQDesc( $elm );
686 wfDebugLog( 'XMP', __METHOD__
. " no mode (elm = $elm)" );
692 * Hit an opening element while in MODE_IGNORE
694 * XMP is extensible, so ignore any tag we don't understand.
696 * Mostly ignores, unless we encounter the element that we are ignoring.
697 * in which case we add it to the item stack, so we can ignore things
698 * that are nested, correctly.
700 * @param string $elm namespace . ' ' . tag name
702 private function startElementModeIgnore( $elm ) {
703 if ( $elm === $this->curItem
[0] ) {
704 array_unshift( $this->curItem
, $elm );
705 array_unshift( $this->mode
, self
::MODE_IGNORE
);
710 * Start element in MODE_BAG (unordered array)
711 * this should always be <rdf:Bag>
713 * @param string $elm namespace . ' ' . tag
714 * @throws MWException if we have an element that's not <rdf:Bag>
716 private function startElementModeBag( $elm ) {
717 if ( $elm === self
::NS_RDF
. ' Bag' ) {
718 array_unshift( $this->mode
, self
::MODE_LI
);
720 throw new MWException( "Expected <rdf:Bag> but got $elm." );
725 * Start element in MODE_SEQ (ordered array)
726 * this should always be <rdf:Seq>
728 * @param string $elm namespace . ' ' . tag
729 * @throws MWException if we have an element that's not <rdf:Seq>
731 private function startElementModeSeq( $elm ) {
732 if ( $elm === self
::NS_RDF
. ' Seq' ) {
733 array_unshift( $this->mode
, self
::MODE_LI
);
734 } elseif ( $elm === self
::NS_RDF
. ' Bag' ) {
736 wfDebugLog( 'XMP', __METHOD__
. ' Expected an rdf:Seq, but got an rdf:Bag. Pretending'
737 . ' it is a Seq, since some buggy software is known to screw this up.' );
738 array_unshift( $this->mode
, self
::MODE_LI
);
740 throw new MWException( "Expected <rdf:Seq> but got $elm." );
745 * Start element in MODE_LANG (language alternative)
746 * this should always be <rdf:Alt>
748 * This tag tends to be used for metadata like describe this
749 * picture, which can be translated into multiple languages.
751 * XMP supports non-linguistic alternative selections,
752 * which are really only used for thumbnails, which
753 * we don't care about.
755 * @param string $elm namespace . ' ' . tag
756 * @throws MWException if we have an element that's not <rdf:Alt>
758 private function startElementModeLang( $elm ) {
759 if ( $elm === self
::NS_RDF
. ' Alt' ) {
760 array_unshift( $this->mode
, self
::MODE_LI_LANG
);
762 throw new MWException( "Expected <rdf:Seq> but got $elm." );
767 * Handle an opening element when in MODE_SIMPLE
769 * This should not happen often. This is for if a simple element
770 * already opened has a child element. Could happen for a
774 * <exif:DigitalZoomRatio><rdf:Description><rdf:value>0/10</rdf:value>
775 * <foo:someQualifier>Bar</foo:someQualifier> </rdf:Description>
776 * </exif:DigitalZoomRatio>
778 * This method is called when processing the <rdf:Description> element
780 * @param string $elm namespace and tag names separated by space.
781 * @param array $attribs Attributes of the element.
782 * @throws MWException
784 private function startElementModeSimple( $elm, $attribs ) {
785 if ( $elm === self
::NS_RDF
. ' Description' ) {
786 // If this value has qualifiers
787 array_unshift( $this->mode
, self
::MODE_QDESC
);
788 array_unshift( $this->curItem
, $this->curItem
[0] );
790 if ( isset( $attribs[self
::NS_RDF
. ' value'] ) ) {
791 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
792 $this->saveValue( $ns, $tag, $attribs[self
::NS_RDF
. ' value'] );
794 } elseif ( $elm === self
::NS_RDF
. ' value' ) {
795 // This should not be here.
796 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 );
806 * Start an element when in MODE_QDESC.
807 * This generally happens when a simple element has an inner
808 * rdf:Description to hold qualifier elements.
811 * <exif:DigitalZoomRatio><rdf:Description><rdf:value>0/10</rdf:value>
812 * <foo:someQualifier>Bar</foo:someQualifier> </rdf:Description>
813 * </exif:DigitalZoomRatio>
814 * Called when processing the <rdf:value> or <foo:someQualifier>.
816 * @param string $elm namespace and tag name separated by a space.
819 private function startElementModeQDesc( $elm ) {
820 if ( $elm === self
::NS_RDF
. ' value' ) {
821 return; // do nothing
823 // otherwise its a qualifier, which we ignore
824 array_unshift( $this->mode
, self
::MODE_IGNORE
);
825 array_unshift( $this->curItem
, $elm );
830 * Starting an element when in MODE_INITIAL
831 * This usually happens when we hit an element inside
832 * the outer rdf:Description
834 * This is generally where most properties start.
836 * @param string $ns Namespace
837 * @param string $tag tag name (without namespace prefix)
838 * @param array $attribs array of attributes
839 * @throws MWException
841 private function startElementModeInitial( $ns, $tag, $attribs ) {
842 if ( $ns !== self
::NS_RDF
) {
844 if ( isset( $this->items
[$ns][$tag] ) ) {
845 if ( isset( $this->items
[$ns][$tag]['structPart'] ) ) {
846 // If this element is supposed to appear only as
847 // a child of a structure, but appears here (not as
848 // a child of a struct), then something weird is
849 // happening, so ignore this element and its children.
851 wfDebugLog( 'XMP', "Encountered <$ns:$tag> outside"
852 . " of its expected parent. Ignoring." );
854 array_unshift( $this->mode
, self
::MODE_IGNORE
);
855 array_unshift( $this->curItem
, $ns . ' ' . $tag );
859 $mode = $this->items
[$ns][$tag]['mode'];
860 array_unshift( $this->mode
, $mode );
861 array_unshift( $this->curItem
, $ns . ' ' . $tag );
862 if ( $mode === self
::MODE_STRUCT
) {
863 $this->ancestorStruct
= isset( $this->items
[$ns][$tag]['map_name'] )
864 ?
$this->items
[$ns][$tag]['map_name'] : $tag;
866 if ( $this->charContent
!== false ) {
868 // Should not happen in valid XMP.
869 throw new MWException( 'tag nested in non-whitespace characters.' );
872 // This element is not on our list of allowed elements so ignore.
873 wfDebugLog( 'XMP', __METHOD__
. " Ignoring unrecognized element <$ns:$tag>." );
874 array_unshift( $this->mode
, self
::MODE_IGNORE
);
875 array_unshift( $this->curItem
, $ns . ' ' . $tag );
880 // process attributes
881 $this->doAttribs( $attribs );
885 * Hit an opening element when in a Struct (MODE_STRUCT)
886 * This is generally for fields of a compound property.
888 * Example of a struct (abbreviated; flash has more properties):
890 * <exif:Flash> <rdf:Description> <exif:Fired>True</exif:Fired>
891 * <exif:Mode>1</exif:Mode></rdf:Description></exif:Flash>
895 * <exif:Flash rdf:parseType='Resource'> <exif:Fired>True</exif:Fired>
896 * <exif:Mode>1</exif:Mode></exif:Flash>
898 * @param string $ns namespace
899 * @param string $tag tag name (no ns)
900 * @param array $attribs array of attribs w/ values.
901 * @throws MWException
903 private function startElementModeStruct( $ns, $tag, $attribs ) {
904 if ( $ns !== self
::NS_RDF
) {
906 if ( isset( $this->items
[$ns][$tag] ) ) {
907 if ( isset( $this->items
[$ns][$this->ancestorStruct
]['children'] )
908 && !isset( $this->items
[$ns][$this->ancestorStruct
]['children'][$tag] )
910 // This assumes that we don't have inter-namespace nesting
911 // which we don't in all the properties we're interested in.
912 throw new MWException( " <$tag> appeared nested in <" . $this->ancestorStruct
913 . "> where it is not allowed." );
915 array_unshift( $this->mode
, $this->items
[$ns][$tag]['mode'] );
916 array_unshift( $this->curItem
, $ns . ' ' . $tag );
917 if ( $this->charContent
!== false ) {
919 // Should not happen in valid XMP.
920 throw new MWException( "tag <$tag> nested in non-whitespace characters (" . $this->charContent
. ")." );
923 array_unshift( $this->mode
, self
::MODE_IGNORE
);
924 array_unshift( $this->curItem
, $elm );
930 if ( $ns === self
::NS_RDF
&& $tag === 'Description' ) {
931 $this->doAttribs( $attribs );
932 array_unshift( $this->mode
, self
::MODE_STRUCT
);
933 array_unshift( $this->curItem
, $this->curItem
[0] );
938 * opening element in MODE_LI
939 * process elements of arrays.
942 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
943 * </rdf:Seq> </exif:ISOSpeedRatings>
944 * This method is called when we hit the <rdf:li> element.
946 * @param string $elm namespace . ' ' . tagname
947 * @param array $attribs Attributes. (needed for BAGSTRUCTS)
948 * @throws MWException if gets a tag other than <rdf:li>
950 private function startElementModeLi( $elm, $attribs ) {
951 if ( ( $elm ) !== self
::NS_RDF
. ' li' ) {
952 throw new MWException( "<rdf:li> expected but got $elm." );
955 if ( !isset( $this->mode
[1] ) ) {
956 // This should never ever ever happen. Checking for it
958 throw new MWException( 'In mode Li, but no 2xPrevious mode!' );
961 if ( $this->mode
[1] === self
::MODE_BAGSTRUCT
) {
962 // This list item contains a compound (STRUCT) value.
963 array_unshift( $this->mode
, self
::MODE_STRUCT
);
964 array_unshift( $this->curItem
, $elm );
965 $this->processingArray
= true;
967 if ( !isset( $this->curItem
[1] ) ) {
969 throw new MWException( 'Can not find parent of BAGSTRUCT.' );
971 list( $curNS, $curTag ) = explode( ' ', $this->curItem
[1] );
972 $this->ancestorStruct
= isset( $this->items
[$curNS][$curTag]['map_name'] )
973 ?
$this->items
[$curNS][$curTag]['map_name'] : $curTag;
975 $this->doAttribs( $attribs );
977 // Normal BAG or SEQ containing simple values.
978 array_unshift( $this->mode
, self
::MODE_SIMPLE
);
979 // need to add curItem[0] on again since one is for the specific item
980 // and one is for the entire group.
981 array_unshift( $this->curItem
, $this->curItem
[0] );
982 $this->processingArray
= true;
987 * Opening element in MODE_LI_LANG.
988 * process elements of language alternatives
991 * <dc:title> <rdf:Alt> <rdf:li xml:lang="x-default">My house
992 * </rdf:li> </rdf:Alt> </dc:title>
994 * This method is called when we hit the <rdf:li> element.
996 * @param string $elm namespace . ' ' . tag
997 * @param array $attribs array of elements (most importantly xml:lang)
998 * @throws MWException if gets a tag other than <rdf:li> or if no xml:lang
1000 private function startElementModeLiLang( $elm, $attribs ) {
1001 if ( $elm !== self
::NS_RDF
. ' li' ) {
1002 throw new MWException( __METHOD__
. " <rdf:li> expected but got $elm." );
1004 if ( !isset( $attribs[self
::NS_XML
. ' lang'] )
1005 ||
!preg_match( '/^[-A-Za-z0-9]{2,}$/D', $attribs[self
::NS_XML
. ' lang'] )
1007 throw new MWException( __METHOD__
1008 . " <rdf:li> did not contain, or has invalid xml:lang attribute in lang alternative" );
1011 // Lang is case-insensitive.
1012 $this->itemLang
= strtolower( $attribs[self
::NS_XML
. ' lang'] );
1014 // need to add curItem[0] on again since one is for the specific item
1015 // and one is for the entire group.
1016 array_unshift( $this->curItem
, $this->curItem
[0] );
1017 array_unshift( $this->mode
, self
::MODE_SIMPLE
);
1018 $this->processingArray
= true;
1022 * Hits an opening element.
1023 * Generally just calls a helper based on what MODE we're in.
1024 * Also does some initial set up for the wrapper element
1026 * @param $parser XMLParser
1027 * @param string $elm namespace "<space>" element
1028 * @param array $attribs attribute name => value
1029 * @throws MWException
1031 function startElement( $parser, $elm, $attribs ) {
1033 if ( $elm === self
::NS_RDF
. ' RDF'
1034 ||
$elm === 'adobe:ns:meta/ xmpmeta'
1035 ||
$elm === 'adobe:ns:meta/ xapmeta'
1039 } elseif ( $elm === self
::NS_RDF
. ' Description' ) {
1040 if ( count( $this->mode
) === 0 ) {
1042 array_unshift( $this->mode
, self
::MODE_INITIAL
);
1044 } elseif ( $elm === self
::NS_RDF
. ' type' ) {
1045 // This doesn't support rdf:type properly.
1046 // In practise I have yet to see a file that
1047 // uses this element, however it is mentioned
1048 // on page 25 of part 1 of the xmp standard.
1050 // also it seems as if exiv2 and exiftool do not support
1051 // this either (That or I misunderstand the standard)
1052 wfDebugLog( 'XMP', __METHOD__
. ' Encountered <rdf:type> which isn\'t currently supported' );
1055 if ( strpos( $elm, ' ' ) === false ) {
1056 // This probably shouldn't happen.
1057 wfDebugLog( 'XMP', __METHOD__
. " Encountered <$elm> which has no namespace. Skipping." );
1062 list( $ns, $tag ) = explode( ' ', $elm, 2 );
1064 if ( count( $this->mode
) === 0 ) {
1065 // This should not happen.
1066 throw new MWException( 'Error extracting XMP, '
1067 . "encountered <$elm> with no mode" );
1070 switch ( $this->mode
[0] ) {
1071 case self
::MODE_IGNORE
:
1072 $this->startElementModeIgnore( $elm );
1074 case self
::MODE_SIMPLE
:
1075 $this->startElementModeSimple( $elm, $attribs );
1077 case self
::MODE_INITIAL
:
1078 $this->startElementModeInitial( $ns, $tag, $attribs );
1080 case self
::MODE_STRUCT
:
1081 $this->startElementModeStruct( $ns, $tag, $attribs );
1083 case self
::MODE_BAG
:
1084 case self
::MODE_BAGSTRUCT
:
1085 $this->startElementModeBag( $elm );
1087 case self
::MODE_SEQ
:
1088 $this->startElementModeSeq( $elm );
1090 case self
::MODE_LANG
:
1091 $this->startElementModeLang( $elm );
1093 case self
::MODE_LI_LANG
:
1094 $this->startElementModeLiLang( $elm, $attribs );
1097 $this->startElementModeLi( $elm, $attribs );
1099 case self
::MODE_QDESC
:
1100 $this->startElementModeQDesc( $elm );
1103 throw new MWException( 'StartElement in unknown mode: ' . $this->mode
[0] );
1108 * Process attributes.
1109 * Simple values can be stored as either a tag or attribute
1111 * Often the initial "<rdf:Description>" tag just has all the simple
1112 * properties as attributes.
1116 * <rdf:Description rdf:about="" xmlns:exif="http://ns.adobe.com/exif/1.0/" exif:DigitalZoomRatio="0/10">
1119 * @param array $attribs attribute=>value array.
1120 * @throws MWException
1122 private function doAttribs( $attribs ) {
1124 // first check for rdf:parseType attribute, as that can change
1125 // how the attributes are interperted.
1127 if ( isset( $attribs[self
::NS_RDF
. ' parseType'] )
1128 && $attribs[self
::NS_RDF
. ' parseType'] === 'Resource'
1129 && $this->mode
[0] === self
::MODE_SIMPLE
1131 // this is equivalent to having an inner rdf:Description
1132 $this->mode
[0] = self
::MODE_QDESC
;
1134 foreach ( $attribs as $name => $val ) {
1135 if ( strpos( $name, ' ' ) === false ) {
1136 // This shouldn't happen, but so far some old software forgets namespace
1138 wfDebugLog( 'XMP', __METHOD__
. ' Encountered non-namespaced attribute: '
1139 . " $name=\"$val\". Skipping. " );
1142 list( $ns, $tag ) = explode( ' ', $name, 2 );
1143 if ( $ns === self
::NS_RDF
) {
1144 if ( $tag === 'value' ||
$tag === 'resource' ) {
1145 // resource is for url.
1146 // value attribute is a weird way of just putting the contents.
1147 $this->char( $this->xmlParser
, $val );
1149 } elseif ( isset( $this->items
[$ns][$tag] ) ) {
1150 if ( $this->mode
[0] === self
::MODE_SIMPLE
) {
1151 throw new MWException( __METHOD__
1152 . " $ns:$tag found as attribute where not allowed" );
1154 $this->saveValue( $ns, $tag, $val );
1156 wfDebugLog( 'XMP', __METHOD__
. " Ignoring unrecognized element <$ns:$tag>." );
1162 * Given an extracted value, save it to results array
1164 * note also uses $this->ancestorStruct and
1165 * $this->processingArray to determine what name to
1166 * save the value under. (in addition to $tag).
1168 * @param string $ns namespace of tag this is for
1169 * @param string $tag tag name
1170 * @param string $val value to save
1172 private function saveValue( $ns, $tag, $val ) {
1174 $info =& $this->items
[$ns][$tag];
1175 $finalName = isset( $info['map_name'] )
1176 ?
$info['map_name'] : $tag;
1177 if ( isset( $info['validate'] ) ) {
1178 $validate = is_array( $info['validate'] ) ?
$info['validate']
1179 : array( 'XMPValidate', $info['validate'] );
1181 if ( is_callable( $validate ) ) {
1182 call_user_func_array( $validate, array( $info, &$val, true ) );
1183 // the reasoning behind using &$val instead of using the return value
1184 // is to be consistent between here and validating structures.
1185 if ( is_null( $val ) ) {
1186 wfDebugLog( 'XMP', __METHOD__
. " <$ns:$tag> failed validation." );
1191 wfDebugLog( 'XMP', __METHOD__
. " Validation function for $finalName ("
1192 . $validate[0] . '::' . $validate[1] . '()) is not callable.' );
1196 if ( $this->ancestorStruct
&& $this->processingArray
) {
1197 // Aka both an array and a struct. ( self::MODE_BAGSTRUCT )
1198 $this->results
['xmp-' . $info['map_group']][$this->ancestorStruct
][][$finalName] = $val;
1199 } elseif ( $this->ancestorStruct
) {
1200 $this->results
['xmp-' . $info['map_group']][$this->ancestorStruct
][$finalName] = $val;
1201 } elseif ( $this->processingArray
) {
1202 if ( $this->itemLang
=== false ) {
1204 $this->results
['xmp-' . $info['map_group']][$finalName][] = $val;
1207 $this->results
['xmp-' . $info['map_group']][$finalName][$this->itemLang
] = $val;
1210 $this->results
['xmp-' . $info['map_group']][$finalName] = $val;