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 if ( $data['xmp-exif']['GPSAltitudeRef'] == '1'
218 && isset( $data['xmp-exif']['GPSAltitude'] )
220 $data['xmp-exif']['GPSAltitude'] *= -1;
222 unset( $data['xmp-exif']['GPSAltitudeRef'] );
229 * Main function to call to parse XMP. Use getResults to
232 * Also catches any errors during processing, writes them to
233 * debug log, blanks result array and returns false.
235 * @param $content String: XMP data
236 * @param $allOfIt Boolean: If this is all the data (true) or if its split up (false). Default true
237 * @param $reset Boolean: does xml parser need to be reset. Default false
238 * @return Boolean success.
240 public function parse( $content, $allOfIt = true, $reset = false ) {
242 $this->resetXMLParser();
246 // detect encoding by looking for BOM which is supposed to be in processing instruction.
247 // see page 12 of http://www.adobe.com/devnet/xmp/pdfs/XMPSpecificationPart3.pdf
248 if ( !$this->charset
) {
250 if ( preg_match( '/\xEF\xBB\xBF|\xFE\xFF|\x00\x00\xFE\xFF|\xFF\xFE\x00\x00|\xFF\xFE/',
255 $this->charset
= 'UTF-16BE';
258 $this->charset
= 'UTF-16LE';
260 case "\x00\x00\xFE\xFF":
261 $this->charset
= 'UTF-32BE';
263 case "\xFF\xFE\x00\x00":
264 $this->charset
= 'UTF-32LE';
267 $this->charset
= 'UTF-8';
270 //this should be impossible to get to
271 throw new MWException("Invalid BOM");
277 // standard specifically says, if no bom assume utf-8
278 $this->charset
= 'UTF-8';
281 if ( $this->charset
!== 'UTF-8' ) {
282 //don't convert if already utf-8
283 wfSuppressWarnings();
284 $content = iconv( $this->charset
, 'UTF-8//IGNORE', $content );
288 $ok = xml_parse( $this->xmlParser
, $content, $allOfIt );
290 $error = xml_error_string( xml_get_error_code( $this->xmlParser
) );
291 $where = 'line: ' . xml_get_current_line_number( $this->xmlParser
)
292 . ' column: ' . xml_get_current_column_number( $this->xmlParser
)
293 . ' byte offset: ' . xml_get_current_byte_index( $this->xmlParser
);
295 wfDebugLog( 'XMP', "XMPReader::parse : Error reading XMP content: $error ($where)" );
296 $this->results
= array(); // blank if error.
299 } catch ( MWException
$e ) {
300 wfDebugLog( 'XMP', 'XMP parse error: ' . $e );
301 $this->results
= array();
307 /** Entry point for XMPExtended blocks in jpeg files
309 * @todo In serious need of testing
310 * @see http://www.adobe.ge/devnet/xmp/pdfs/XMPSpecificationPart3.pdf XMP spec part 3 page 20
311 * @param String $content XMPExtended block minus the namespace signature
312 * @return Boolean If it succeeded.
314 public function parseExtended( $content ) {
315 // @todo FIXME: This is untested. Hard to find example files
316 // or programs that make such files..
317 $guid = substr( $content, 0, 32 );
318 if ( !isset( $this->results
['xmp-special']['HasExtendedXMP'] )
319 ||
$this->results
['xmp-special']['HasExtendedXMP'] !== $guid ) {
320 wfDebugLog('XMP', __METHOD__
. " Ignoring XMPExtended block due to wrong guid (guid= '$guid' )");
323 $len = unpack( 'Nlength/Noffset', substr( $content, 32, 8 ) );
325 if (!$len ||
$len['length'] < 4 ||
$len['offset'] < 0 ||
$len['offset'] > $len['length'] ) {
326 wfDebugLog('XMP', __METHOD__
. 'Error reading extended XMP block, invalid length or offset.');
331 // we're not very robust here. we should accept it in the wrong order. To quote
333 // "A JPEG writer should write the ExtendedXMP marker segments in order, immediately following the
334 // StandardXMP. However, the JPEG standard does not require preservation of marker segment order. A
335 // robust JPEG reader should tolerate the marker segments in any order."
337 // otoh the probability that an image will have more than 128k of metadata is rather low...
338 // so the probability that it will have > 128k, and be in the wrong order is very low...
340 if ( $len['offset'] !== $this->extendedXMPOffset
) {
341 wfDebugLog('XMP', __METHOD__
. 'Ignoring XMPExtended block due to wrong order. (Offset was '
342 . $len['offset'] . ' but expected ' . $this->extendedXMPOffset
. ')');
346 if ( $len['offset'] === 0 ) {
347 // if we're starting the extended block, we've probably already
348 // done the XMPStandard block, so reset.
349 $this->resetXMLParser();
352 $this->extendedXMPOffset +
= $len['length'];
354 $actualContent = substr( $content, 40 );
356 if ( $this->extendedXMPOffset
=== strlen( $actualContent ) ) {
362 wfDebugLog('XMP', __METHOD__
. 'Parsing a XMPExtended block');
363 return $this->parse( $actualContent, $atEnd );
367 * Character data handler
368 * Called whenever character data is found in the xmp document.
370 * does nothing if we're in MODE_IGNORE or if the data is whitespace
371 * throws an error if we're not in MODE_SIMPLE (as we're not allowed to have character
372 * data in the other modes).
374 * As an example, this happens when we encounter XMP like:
375 * <exif:DigitalZoomRatio>0/10</exif:DigitalZoomRatio>
376 * and are processing the 0/10 bit.
378 * @param $parser XMLParser reference to the xml parser
379 * @param $data String Character data
380 * @throws MWException on invalid data
382 function char( $parser, $data ) {
384 $data = trim( $data );
385 if ( trim( $data ) === "" ) {
389 if ( !isset( $this->mode
[0] ) ) {
390 throw new MWException( 'Unexpected character data before first rdf:Description element' );
393 if ( $this->mode
[0] === self
::MODE_IGNORE
) return;
395 if ( $this->mode
[0] !== self
::MODE_SIMPLE
396 && $this->mode
[0] !== self
::MODE_QDESC
398 throw new MWException( 'character data where not expected. (mode ' . $this->mode
[0] . ')' );
401 // to check, how does this handle w.s.
402 if ( $this->charContent
=== false ) {
403 $this->charContent
= $data;
405 $this->charContent
.= $data;
410 /** When we hit a closing element in MODE_IGNORE
411 * Check to see if this is the element we started to ignore,
412 * in which case we get out of MODE_IGNORE
414 * @param $elm String Namespace of element followed by a space and then tag name of element.
416 private function endElementModeIgnore ( $elm ) {
418 if ( $this->curItem
[0] === $elm ) {
419 array_shift( $this->curItem
);
420 array_shift( $this->mode
);
427 * Hit a closing element when in MODE_SIMPLE.
428 * This generally means that we finished processing a
429 * property value, and now have to save the result to the
432 * For example, when processing:
433 * <exif:DigitalZoomRatio>0/10</exif:DigitalZoomRatio>
434 * this deals with when we hit </exif:DigitalZoomRatio>.
436 * Or it could be if we hit the end element of a property
437 * of a compound data structure (like a member of an array).
439 * @param $elm String namespace, space, and tag name.
441 private function endElementModeSimple ( $elm ) {
442 if ( $this->charContent
!== false ) {
443 if ( $this->processingArray
) {
444 // if we're processing an array, use the original element
445 // name instead of rdf:li.
446 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
448 list( $ns, $tag ) = explode( ' ', $elm, 2 );
450 $this->saveValue( $ns, $tag, $this->charContent
);
452 $this->charContent
= false; // reset
454 array_shift( $this->curItem
);
455 array_shift( $this->mode
);
460 * Hit a closing element in MODE_STRUCT, MODE_SEQ, MODE_BAG
461 * generally means we've finished processing a nested structure.
462 * resets some internal variables to indicate that.
464 * Note this means we hit the </closing element> not the </rdf:Seq>.
466 * For example, when processing:
467 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
468 * </rdf:Seq> </exif:ISOSpeedRatings>
470 * This method is called when we hit the </exif:ISOSpeedRatings> tag.
472 * @param $elm String namespace . space . tag name.
474 private function endElementNested( $elm ) {
476 /* cur item must be the same as $elm, unless if in MODE_STRUCT
477 in which case it could also be rdf:Description */
478 if ( $this->curItem
[0] !== $elm
479 && !( $elm === self
::NS_RDF
. ' Description'
480 && $this->mode
[0] === self
::MODE_STRUCT
)
482 throw new MWException( "nesting mismatch. got a </$elm> but expected a </" . $this->curItem
[0] . '>' );
485 // Validate structures.
486 list( $ns, $tag ) = explode( ' ', $elm, 2 );
487 if ( isset( $this->items
[$ns][$tag]['validate'] ) ) {
489 $info =& $this->items
[$ns][$tag];
490 $finalName = isset( $info['map_name'] )
491 ?
$info['map_name'] : $tag;
493 $validate = is_array( $info['validate'] ) ?
$info['validate']
494 : array( 'XMPValidate', $info['validate'] );
496 if ( !isset( $this->results
['xmp-' . $info['map_group']][$finalName] ) ) {
497 // This can happen if all the members of the struct failed validation.
498 wfDebugLog( 'XMP', __METHOD__
. " <$ns:$tag> has no valid members." );
500 } elseif ( is_callable( $validate ) ) {
501 $val =& $this->results
['xmp-' . $info['map_group']][$finalName];
502 call_user_func_array( $validate, array( $info, &$val, false ) );
503 if ( is_null( $val ) ) {
504 // the idea being the validation function will unset the variable if
506 wfDebugLog( 'XMP', __METHOD__
. " <$ns:$tag> failed validation." );
507 unset( $this->results
['xmp-' . $info['map_group']][$finalName] );
510 wfDebugLog( 'XMP', __METHOD__
. " Validation function for $finalName ("
511 . $validate[0] . '::' . $validate[1] . '()) is not callable.' );
515 array_shift( $this->curItem
);
516 array_shift( $this->mode
);
517 $this->ancestorStruct
= false;
518 $this->processingArray
= false;
519 $this->itemLang
= false;
523 * Hit a closing element in MODE_LI (either rdf:Seq, or rdf:Bag )
524 * Add information about what type of element this is.
526 * Note we still have to hit the outer </property>
528 * For example, when processing:
529 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
530 * </rdf:Seq> </exif:ISOSpeedRatings>
532 * This method is called when we hit the </rdf:Seq>.
533 * (For comparison, we call endElementModeSimple when we
536 * @param $elm String namespace . ' ' . element name
538 private function endElementModeLi( $elm ) {
540 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
541 $info = $this->items
[$ns][$tag];
542 $finalName = isset( $info['map_name'] )
543 ?
$info['map_name'] : $tag;
545 array_shift( $this->mode
);
547 if ( !isset( $this->results
['xmp-' . $info['map_group']][$finalName] ) ) {
548 wfDebugLog( 'XMP', __METHOD__
. " Empty compund element $finalName." );
552 if ( $elm === self
::NS_RDF
. ' Seq' ) {
553 $this->results
['xmp-' . $info['map_group']][$finalName]['_type'] = 'ol';
554 } elseif ( $elm === self
::NS_RDF
. ' Bag' ) {
555 $this->results
['xmp-' . $info['map_group']][$finalName]['_type'] = 'ul';
556 } elseif ( $elm === self
::NS_RDF
. ' Alt' ) {
557 // extra if needed as you could theoretically have a non-language alt.
558 if ( $info['mode'] === self
::MODE_LANG
) {
559 $this->results
['xmp-' . $info['map_group']][$finalName]['_type'] = 'lang';
563 throw new MWException( __METHOD__
. " expected </rdf:seq> or </rdf:bag> but instead got $elm." );
568 * End element while in MODE_QDESC
569 * mostly when ending an element when we have a simple value
570 * that has qualifiers.
572 * Qualifiers aren't all that common, and we don't do anything
575 * @param $elm String namespace and element
577 private function endElementModeQDesc( $elm ) {
579 if ( $elm === self
::NS_RDF
. ' value' ) {
580 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
581 $this->saveValue( $ns, $tag, $this->charContent
);
584 array_shift( $this->mode
);
585 array_shift( $this->curItem
);
592 * Handler for hitting a closing element.
594 * generally just calls a helper function depending on what
597 * Ignores the outer wrapping elements that are optional in
598 * xmp and have no meaning.
600 * @param $parser XMLParser
601 * @param $elm String namespace . ' ' . element name
603 function endElement( $parser, $elm ) {
604 if ( $elm === ( self
::NS_RDF
. ' RDF' )
605 ||
$elm === 'adobe:ns:meta/ xmpmeta'
606 ||
$elm === 'adobe:ns:meta/ xapmeta' )
612 if ( $elm === self
::NS_RDF
. ' type' ) {
613 // these aren't really supported properly yet.
614 // However, it appears they almost never used.
615 wfDebugLog( 'XMP', __METHOD__
. ' encountered <rdf:type>' );
618 if ( strpos( $elm, ' ' ) === false ) {
619 // This probably shouldn't happen.
620 // However, there is a bug in an adobe product
621 // that forgets the namespace on some things.
622 // (Luckily they are unimportant things).
623 wfDebugLog( 'XMP', __METHOD__
. " Encountered </$elm> which has no namespace. Skipping." );
627 if ( count( $this->mode
[0] ) === 0 ) {
628 // This should never ever happen and means
629 // there is a pretty major bug in this class.
630 throw new MWException( 'Encountered end element with no mode' );
633 if ( count( $this->curItem
) == 0 && $this->mode
[0] !== self
::MODE_INITIAL
) {
634 // just to be paranoid. Should always have a curItem, except for initially
635 // (aka during MODE_INITAL).
636 throw new MWException( "Hit end element </$elm> but no curItem" );
639 switch( $this->mode
[0] ) {
640 case self
::MODE_IGNORE
:
641 $this->endElementModeIgnore( $elm );
643 case self
::MODE_SIMPLE
:
644 $this->endElementModeSimple( $elm );
646 case self
::MODE_STRUCT
:
649 case self
::MODE_LANG
:
650 case self
::MODE_BAGSTRUCT
:
651 $this->endElementNested( $elm );
653 case self
::MODE_INITIAL
:
654 if ( $elm === self
::NS_RDF
. ' Description' ) {
655 array_shift( $this->mode
);
657 throw new MWException( 'Element ended unexpectedly while in MODE_INITIAL' );
661 case self
::MODE_LI_LANG
:
662 $this->endElementModeLi( $elm );
664 case self
::MODE_QDESC
:
665 $this->endElementModeQDesc( $elm );
668 wfDebugLog( 'XMP', __METHOD__
. " no mode (elm = $elm)" );
674 * Hit an opening element while in MODE_IGNORE
676 * XMP is extensible, so ignore any tag we don't understand.
678 * Mostly ignores, unless we encounter the element that we are ignoring.
679 * in which case we add it to the item stack, so we can ignore things
680 * that are nested, correctly.
682 * @param $elm String namespace . ' ' . tag name
684 private function startElementModeIgnore( $elm ) {
685 if ( $elm === $this->curItem
[0] ) {
686 array_unshift( $this->curItem
, $elm );
687 array_unshift( $this->mode
, self
::MODE_IGNORE
);
692 * Start element in MODE_BAG (unordered array)
693 * this should always be <rdf:Bag>
695 * @param $elm String namespace . ' ' . tag
696 * @throws MWException if we have an element that's not <rdf:Bag>
698 private function startElementModeBag( $elm ) {
699 if ( $elm === self
::NS_RDF
. ' Bag' ) {
700 array_unshift( $this->mode
, self
::MODE_LI
);
702 throw new MWException( "Expected <rdf:Bag> but got $elm." );
708 * Start element in MODE_SEQ (ordered array)
709 * this should always be <rdf:Seq>
711 * @param $elm String namespace . ' ' . tag
712 * @throws MWException if we have an element that's not <rdf:Seq>
714 private function startElementModeSeq( $elm ) {
715 if ( $elm === self
::NS_RDF
. ' Seq' ) {
716 array_unshift( $this->mode
, self
::MODE_LI
);
717 } elseif ( $elm === self
::NS_RDF
. ' Bag' ) {
719 wfDebugLog( 'XMP', __METHOD__
. ' Expected an rdf:Seq, but got an rdf:Bag. Pretending'
720 . ' it is a Seq, since some buggy software is known to screw this up.' );
721 array_unshift( $this->mode
, self
::MODE_LI
);
723 throw new MWException( "Expected <rdf:Seq> but got $elm." );
729 * Start element in MODE_LANG (language alternative)
730 * this should always be <rdf:Alt>
732 * This tag tends to be used for metadata like describe this
733 * picture, which can be translated into multiple languages.
735 * XMP supports non-linguistic alternative selections,
736 * which are really only used for thumbnails, which
737 * we don't care about.
739 * @param $elm String namespace . ' ' . tag
740 * @throws MWException if we have an element that's not <rdf:Alt>
742 private function startElementModeLang( $elm ) {
743 if ( $elm === self
::NS_RDF
. ' Alt' ) {
744 array_unshift( $this->mode
, self
::MODE_LI_LANG
);
746 throw new MWException( "Expected <rdf:Seq> but got $elm." );
752 * Handle an opening element when in MODE_SIMPLE
754 * This should not happen often. This is for if a simple element
755 * already opened has a child element. Could happen for a
759 * <exif:DigitalZoomRatio><rdf:Description><rdf:value>0/10</rdf:value>
760 * <foo:someQualifier>Bar</foo:someQualifier> </rdf:Description>
761 * </exif:DigitalZoomRatio>
763 * This method is called when processing the <rdf:Description> element
765 * @param $elm String namespace and tag names separated by space.
766 * @param $attribs Array Attributes of the element.
768 private function startElementModeSimple( $elm, $attribs ) {
769 if ( $elm === self
::NS_RDF
. ' Description' ) {
770 // If this value has qualifiers
771 array_unshift( $this->mode
, self
::MODE_QDESC
);
772 array_unshift( $this->curItem
, $this->curItem
[0] );
774 if ( isset( $attribs[self
::NS_RDF
. ' value'] ) ) {
775 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
776 $this->saveValue( $ns, $tag, $attribs[self
::NS_RDF
. ' value'] );
778 } elseif ( $elm === self
::NS_RDF
. ' value' ) {
779 // This should not be here.
780 throw new MWException( __METHOD__
. ' Encountered <rdf:value> where it was unexpected.' );
783 // something else we don't recognize, like a qualifier maybe.
784 wfDebugLog( 'XMP', __METHOD__
. " Encountered element <$elm> where only expecting character data as value of " . $this->curItem
[0] );
785 array_unshift( $this->mode
, self
::MODE_IGNORE
);
786 array_unshift( $this->curItem
, $elm );
793 * Start an element when in MODE_QDESC.
794 * This generally happens when a simple element has an inner
795 * rdf:Description to hold qualifier elements.
798 * <exif:DigitalZoomRatio><rdf:Description><rdf:value>0/10</rdf:value>
799 * <foo:someQualifier>Bar</foo:someQualifier> </rdf:Description>
800 * </exif:DigitalZoomRatio>
801 * Called when processing the <rdf:value> or <foo:someQualifier>.
803 * @param $elm String namespace and tag name separated by a space.
806 private function startElementModeQDesc( $elm ) {
807 if ( $elm === self
::NS_RDF
. ' value' ) {
808 return; // do nothing
810 // otherwise its a qualifier, which we ignore
811 array_unshift( $this->mode
, self
::MODE_IGNORE
);
812 array_unshift( $this->curItem
, $elm );
817 * Starting an element when in MODE_INITIAL
818 * This usually happens when we hit an element inside
819 * the outer rdf:Description
821 * This is generally where most properties start.
823 * @param $ns String Namespace
824 * @param $tag String tag name (without namespace prefix)
825 * @param $attribs Array array of attributes
827 private function startElementModeInitial( $ns, $tag, $attribs ) {
828 if ( $ns !== self
::NS_RDF
) {
830 if ( isset( $this->items
[$ns][$tag] ) ) {
831 if ( isset( $this->items
[$ns][$tag]['structPart'] ) ) {
832 // If this element is supposed to appear only as
833 // a child of a structure, but appears here (not as
834 // a child of a struct), then something weird is
835 // happening, so ignore this element and its children.
837 wfDebugLog( 'XMP', "Encountered <$ns:$tag> outside"
838 . " of its expected parent. Ignoring." );
840 array_unshift( $this->mode
, self
::MODE_IGNORE
);
841 array_unshift( $this->curItem
, $ns . ' ' . $tag );
844 $mode = $this->items
[$ns][$tag]['mode'];
845 array_unshift( $this->mode
, $mode );
846 array_unshift( $this->curItem
, $ns . ' ' . $tag );
847 if ( $mode === self
::MODE_STRUCT
) {
848 $this->ancestorStruct
= isset( $this->items
[$ns][$tag]['map_name'] )
849 ?
$this->items
[$ns][$tag]['map_name'] : $tag;
851 if ( $this->charContent
!== false ) {
853 // Should not happen in valid XMP.
854 throw new MWException( 'tag nested in non-whitespace characters.' );
857 // This element is not on our list of allowed elements so ignore.
858 wfDebugLog( 'XMP', __METHOD__
. " Ignoring unrecognized element <$ns:$tag>." );
859 array_unshift( $this->mode
, self
::MODE_IGNORE
);
860 array_unshift( $this->curItem
, $ns . ' ' . $tag );
865 // process attributes
866 $this->doAttribs( $attribs );
870 * Hit an opening element when in a Struct (MODE_STRUCT)
871 * This is generally for fields of a compound property.
873 * Example of a struct (abbreviated; flash has more properties):
875 * <exif:Flash> <rdf:Description> <exif:Fired>True</exif:Fired>
876 * <exif:Mode>1</exif:Mode></rdf:Description></exif:Flash>
880 * <exif:Flash rdf:parseType='Resource'> <exif:Fired>True</exif:Fired>
881 * <exif:Mode>1</exif:Mode></exif:Flash>
883 * @param $ns String namespace
884 * @param $tag String tag name (no ns)
885 * @param $attribs Array array of attribs w/ values.
887 private function startElementModeStruct( $ns, $tag, $attribs ) {
888 if ( $ns !== self
::NS_RDF
) {
890 if ( isset( $this->items
[$ns][$tag] ) ) {
891 if ( isset( $this->items
[$ns][$this->ancestorStruct
]['children'] )
892 && !isset( $this->items
[$ns][$this->ancestorStruct
]['children'][$tag] ) )
894 // This assumes that we don't have inter-namespace nesting
895 // which we don't in all the properties we're interested in.
896 throw new MWException( " <$tag> appeared nested in <" . $this->ancestorStruct
897 . "> where it is not allowed." );
899 array_unshift( $this->mode
, $this->items
[$ns][$tag]['mode'] );
900 array_unshift( $this->curItem
, $ns . ' ' . $tag );
901 if ( $this->charContent
!== false ) {
903 // Should not happen in valid XMP.
904 throw new MWException( "tag <$tag> nested in non-whitespace characters (" . $this->charContent
. ")." );
907 array_unshift( $this->mode
, self
::MODE_IGNORE
);
908 array_unshift( $this->curItem
, $elm );
914 if ( $ns === self
::NS_RDF
&& $tag === 'Description' ) {
915 $this->doAttribs( $attribs );
916 array_unshift( $this->mode
, self
::MODE_STRUCT
);
917 array_unshift( $this->curItem
, $this->curItem
[0] );
922 * opening element in MODE_LI
923 * process elements of arrays.
926 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
927 * </rdf:Seq> </exif:ISOSpeedRatings>
928 * This method is called when we hit the <rdf:li> element.
930 * @param $elm String: namespace . ' ' . tagname
931 * @param $attribs Array: Attributes. (needed for BAGSTRUCTS)
932 * @throws MWException if gets a tag other than <rdf:li>
934 private function startElementModeLi( $elm, $attribs ) {
935 if ( ( $elm ) !== self
::NS_RDF
. ' li' ) {
936 throw new MWException( "<rdf:li> expected but got $elm." );
939 if ( !isset( $this->mode
[1] ) ) {
940 // This should never ever ever happen. Checking for it
942 throw new MWException( 'In mode Li, but no 2xPrevious mode!' );
945 if ( $this->mode
[1] === self
::MODE_BAGSTRUCT
) {
946 // This list item contains a compound (STRUCT) value.
947 array_unshift( $this->mode
, self
::MODE_STRUCT
);
948 array_unshift( $this->curItem
, $elm );
949 $this->processingArray
= true;
951 if ( !isset( $this->curItem
[1] ) ) {
953 throw new MWException( 'Can not find parent of BAGSTRUCT.' );
955 list( $curNS, $curTag ) = explode( ' ', $this->curItem
[1] );
956 $this->ancestorStruct
= isset( $this->items
[$curNS][$curTag]['map_name'] )
957 ?
$this->items
[$curNS][$curTag]['map_name'] : $curTag;
959 $this->doAttribs( $attribs );
962 // Normal BAG or SEQ containing simple values.
963 array_unshift( $this->mode
, self
::MODE_SIMPLE
);
964 // need to add curItem[0] on again since one is for the specific item
965 // and one is for the entire group.
966 array_unshift( $this->curItem
, $this->curItem
[0] );
967 $this->processingArray
= true;
973 * Opening element in MODE_LI_LANG.
974 * process elements of language alternatives
977 * <dc:title> <rdf:Alt> <rdf:li xml:lang="x-default">My house
978 * </rdf:li> </rdf:Alt> </dc:title>
980 * This method is called when we hit the <rdf:li> element.
982 * @param $elm String namespace . ' ' . tag
983 * @param $attribs array array of elements (most importantly xml:lang)
984 * @throws MWException if gets a tag other than <rdf:li> or if no xml:lang
986 private function startElementModeLiLang( $elm, $attribs ) {
987 if ( $elm !== self
::NS_RDF
. ' li' ) {
988 throw new MWException( __METHOD__
. " <rdf:li> expected but got $elm." );
990 if ( !isset( $attribs[ self
::NS_XML
. ' lang'] )
991 ||
!preg_match( '/^[-A-Za-z0-9]{2,}$/D', $attribs[ self
::NS_XML
. ' lang' ] ) )
993 throw new MWException( __METHOD__
994 . " <rdf:li> did not contain, or has invalid xml:lang attribute in lang alternative" );
997 // Lang is case-insensitive.
998 $this->itemLang
= strtolower( $attribs[ self
::NS_XML
. ' lang' ] );
1000 // need to add curItem[0] on again since one is for the specific item
1001 // and one is for the entire group.
1002 array_unshift( $this->curItem
, $this->curItem
[0] );
1003 array_unshift( $this->mode
, self
::MODE_SIMPLE
);
1004 $this->processingArray
= true;
1008 * Hits an opening element.
1009 * Generally just calls a helper based on what MODE we're in.
1010 * Also does some initial set up for the wrapper element
1012 * @param $parser XMLParser
1013 * @param $elm String namespace <space> element
1014 * @param $attribs Array attribute name => value
1016 function startElement( $parser, $elm, $attribs ) {
1018 if ( $elm === self
::NS_RDF
. ' RDF'
1019 ||
$elm === 'adobe:ns:meta/ xmpmeta'
1020 ||
$elm === 'adobe:ns:meta/ xapmeta')
1024 } elseif ( $elm === self
::NS_RDF
. ' Description' ) {
1025 if ( count( $this->mode
) === 0 ) {
1027 array_unshift( $this->mode
, self
::MODE_INITIAL
);
1029 } elseif ( $elm === self
::NS_RDF
. ' type' ) {
1030 // This doesn't support rdf:type properly.
1031 // In practise I have yet to see a file that
1032 // uses this element, however it is mentioned
1033 // on page 25 of part 1 of the xmp standard.
1035 // also it seems as if exiv2 and exiftool do not support
1036 // this either (That or I misunderstand the standard)
1037 wfDebugLog( 'XMP', __METHOD__
. ' Encountered <rdf:type> which isn\'t currently supported' );
1040 if ( strpos( $elm, ' ' ) === false ) {
1041 // This probably shouldn't happen.
1042 wfDebugLog( 'XMP', __METHOD__
. " Encountered <$elm> which has no namespace. Skipping." );
1046 list( $ns, $tag ) = explode( ' ', $elm, 2 );
1048 if ( count( $this->mode
) === 0 ) {
1049 // This should not happen.
1050 throw new MWException('Error extracting XMP, '
1051 . "encountered <$elm> with no mode" );
1054 switch( $this->mode
[0] ) {
1055 case self
::MODE_IGNORE
:
1056 $this->startElementModeIgnore( $elm );
1058 case self
::MODE_SIMPLE
:
1059 $this->startElementModeSimple( $elm, $attribs );
1061 case self
::MODE_INITIAL
:
1062 $this->startElementModeInitial( $ns, $tag, $attribs );
1064 case self
::MODE_STRUCT
:
1065 $this->startElementModeStruct( $ns, $tag, $attribs );
1067 case self
::MODE_BAG
:
1068 case self
::MODE_BAGSTRUCT
:
1069 $this->startElementModeBag( $elm );
1071 case self
::MODE_SEQ
:
1072 $this->startElementModeSeq( $elm );
1074 case self
::MODE_LANG
:
1075 $this->startElementModeLang( $elm );
1077 case self
::MODE_LI_LANG
:
1078 $this->startElementModeLiLang( $elm, $attribs );
1081 $this->startElementModeLi( $elm, $attribs );
1083 case self
::MODE_QDESC
:
1084 $this->startElementModeQDesc( $elm );
1087 throw new MWException( 'StartElement in unknown mode: ' . $this->mode
[0] );
1093 * Process attributes.
1094 * Simple values can be stored as either a tag or attribute
1096 * Often the initial <rdf:Description> tag just has all the simple
1097 * properties as attributes.
1100 * <rdf:Description rdf:about="" xmlns:exif="http://ns.adobe.com/exif/1.0/" exif:DigitalZoomRatio="0/10">
1102 * @param $attribs Array attribute=>value array.
1104 private function doAttribs( $attribs ) {
1106 // first check for rdf:parseType attribute, as that can change
1107 // how the attributes are interperted.
1109 if ( isset( $attribs[self
::NS_RDF
. ' parseType'] )
1110 && $attribs[self
::NS_RDF
. ' parseType'] === 'Resource'
1111 && $this->mode
[0] === self
::MODE_SIMPLE
)
1113 // this is equivalent to having an inner rdf:Description
1114 $this->mode
[0] = self
::MODE_QDESC
;
1116 foreach ( $attribs as $name => $val ) {
1119 if ( strpos( $name, ' ' ) === false ) {
1120 // This shouldn't happen, but so far some old software forgets namespace
1122 wfDebugLog( 'XMP', __METHOD__
. ' Encountered non-namespaced attribute: '
1123 . " $name=\"$val\". Skipping. " );
1126 list( $ns, $tag ) = explode( ' ', $name, 2 );
1127 if ( $ns === self
::NS_RDF
) {
1128 if ( $tag === 'value' ||
$tag === 'resource' ) {
1129 // resource is for url.
1130 // value attribute is a weird way of just putting the contents.
1131 $this->char( $this->xmlParser
, $val );
1133 } elseif ( isset( $this->items
[$ns][$tag] ) ) {
1134 if ( $this->mode
[0] === self
::MODE_SIMPLE
) {
1135 throw new MWException( __METHOD__
1136 . " $ns:$tag found as attribute where not allowed" );
1138 $this->saveValue( $ns, $tag, $val );
1140 wfDebugLog( 'XMP', __METHOD__
. " Ignoring unrecognized element <$ns:$tag>." );
1146 * Given an extracted value, save it to results array
1148 * note also uses $this->ancestorStruct and
1149 * $this->processingArray to determine what name to
1150 * save the value under. (in addition to $tag).
1152 * @param $ns String namespace of tag this is for
1153 * @param $tag String tag name
1154 * @param $val String value to save
1156 private function saveValue( $ns, $tag, $val ) {
1158 $info =& $this->items
[$ns][$tag];
1159 $finalName = isset( $info['map_name'] )
1160 ?
$info['map_name'] : $tag;
1161 if ( isset( $info['validate'] ) ) {
1162 $validate = is_array( $info['validate'] ) ?
$info['validate']
1163 : array( 'XMPValidate', $info['validate'] );
1165 if ( is_callable( $validate ) ) {
1166 call_user_func_array( $validate, array( $info, &$val, true ) );
1167 // the reasoning behind using &$val instead of using the return value
1168 // is to be consistent between here and validating structures.
1169 if ( is_null( $val ) ) {
1170 wfDebugLog( 'XMP', __METHOD__
. " <$ns:$tag> failed validation." );
1174 wfDebugLog( 'XMP', __METHOD__
. " Validation function for $finalName ("
1175 . $validate[0] . '::' . $validate[1] . '()) is not callable.' );
1179 if ( $this->ancestorStruct
&& $this->processingArray
) {
1180 // Aka both an array and a struct. ( self::MODE_BAGSTRUCT )
1181 $this->results
['xmp-' . $info['map_group']][$this->ancestorStruct
][][$finalName] = $val;
1182 } elseif ( $this->ancestorStruct
) {
1183 $this->results
['xmp-' . $info['map_group']][$this->ancestorStruct
][$finalName] = $val;
1184 } elseif ( $this->processingArray
) {
1185 if ( $this->itemLang
=== false ) {
1187 $this->results
['xmp-' . $info['map_group']][$finalName][] = $val;
1190 $this->results
['xmp-' . $info['map_group']][$finalName][$this->itemLang
] = $val;
1193 $this->results
['xmp-' . $info['map_group']][$finalName] = $val;