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 * @par For example, when processing:
468 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
469 * </rdf:Seq> </exif:ISOSpeedRatings>
472 * This method is called when we hit the "</exif:ISOSpeedRatings>" tag.
474 * @param $elm String namespace . space . tag name.
476 private function endElementNested( $elm ) {
478 /* cur item must be the same as $elm, unless if in MODE_STRUCT
479 in which case it could also be rdf:Description */
480 if ( $this->curItem
[0] !== $elm
481 && !( $elm === self
::NS_RDF
. ' Description'
482 && $this->mode
[0] === self
::MODE_STRUCT
)
484 throw new MWException( "nesting mismatch. got a </$elm> but expected a </" . $this->curItem
[0] . '>' );
487 // Validate structures.
488 list( $ns, $tag ) = explode( ' ', $elm, 2 );
489 if ( isset( $this->items
[$ns][$tag]['validate'] ) ) {
491 $info =& $this->items
[$ns][$tag];
492 $finalName = isset( $info['map_name'] )
493 ?
$info['map_name'] : $tag;
495 $validate = is_array( $info['validate'] ) ?
$info['validate']
496 : array( 'XMPValidate', $info['validate'] );
498 if ( !isset( $this->results
['xmp-' . $info['map_group']][$finalName] ) ) {
499 // This can happen if all the members of the struct failed validation.
500 wfDebugLog( 'XMP', __METHOD__
. " <$ns:$tag> has no valid members." );
502 } elseif ( is_callable( $validate ) ) {
503 $val =& $this->results
['xmp-' . $info['map_group']][$finalName];
504 call_user_func_array( $validate, array( $info, &$val, false ) );
505 if ( is_null( $val ) ) {
506 // the idea being the validation function will unset the variable if
508 wfDebugLog( 'XMP', __METHOD__
. " <$ns:$tag> failed validation." );
509 unset( $this->results
['xmp-' . $info['map_group']][$finalName] );
512 wfDebugLog( 'XMP', __METHOD__
. " Validation function for $finalName ("
513 . $validate[0] . '::' . $validate[1] . '()) is not callable.' );
517 array_shift( $this->curItem
);
518 array_shift( $this->mode
);
519 $this->ancestorStruct
= false;
520 $this->processingArray
= false;
521 $this->itemLang
= false;
525 * Hit a closing element in MODE_LI (either rdf:Seq, or rdf:Bag )
526 * Add information about what type of element this is.
528 * Note we still have to hit the outer "</property>"
530 * @par For example, when processing:
532 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
533 * </rdf:Seq> </exif:ISOSpeedRatings>
536 * This method is called when we hit the "</rdf:Seq>".
537 * (For comparison, we call endElementModeSimple when we
538 * hit the "</rdf:li>")
540 * @param $elm String namespace . ' ' . element name
542 private function endElementModeLi( $elm ) {
544 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
545 $info = $this->items
[$ns][$tag];
546 $finalName = isset( $info['map_name'] )
547 ?
$info['map_name'] : $tag;
549 array_shift( $this->mode
);
551 if ( !isset( $this->results
['xmp-' . $info['map_group']][$finalName] ) ) {
552 wfDebugLog( 'XMP', __METHOD__
. " Empty compund element $finalName." );
556 if ( $elm === self
::NS_RDF
. ' Seq' ) {
557 $this->results
['xmp-' . $info['map_group']][$finalName]['_type'] = 'ol';
558 } elseif ( $elm === self
::NS_RDF
. ' Bag' ) {
559 $this->results
['xmp-' . $info['map_group']][$finalName]['_type'] = 'ul';
560 } elseif ( $elm === self
::NS_RDF
. ' Alt' ) {
561 // extra if needed as you could theoretically have a non-language alt.
562 if ( $info['mode'] === self
::MODE_LANG
) {
563 $this->results
['xmp-' . $info['map_group']][$finalName]['_type'] = 'lang';
567 throw new MWException( __METHOD__
. " expected </rdf:seq> or </rdf:bag> but instead got $elm." );
572 * End element while in MODE_QDESC
573 * mostly when ending an element when we have a simple value
574 * that has qualifiers.
576 * Qualifiers aren't all that common, and we don't do anything
579 * @param $elm String namespace and element
581 private function endElementModeQDesc( $elm ) {
583 if ( $elm === self
::NS_RDF
. ' value' ) {
584 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
585 $this->saveValue( $ns, $tag, $this->charContent
);
588 array_shift( $this->mode
);
589 array_shift( $this->curItem
);
596 * Handler for hitting a closing element.
598 * generally just calls a helper function depending on what
601 * Ignores the outer wrapping elements that are optional in
602 * xmp and have no meaning.
604 * @param $parser XMLParser
605 * @param $elm String namespace . ' ' . element name
607 function endElement( $parser, $elm ) {
608 if ( $elm === ( self
::NS_RDF
. ' RDF' )
609 ||
$elm === 'adobe:ns:meta/ xmpmeta'
610 ||
$elm === 'adobe:ns:meta/ xapmeta' )
616 if ( $elm === self
::NS_RDF
. ' type' ) {
617 // these aren't really supported properly yet.
618 // However, it appears they almost never used.
619 wfDebugLog( 'XMP', __METHOD__
. ' encountered <rdf:type>' );
622 if ( strpos( $elm, ' ' ) === false ) {
623 // This probably shouldn't happen.
624 // However, there is a bug in an adobe product
625 // that forgets the namespace on some things.
626 // (Luckily they are unimportant things).
627 wfDebugLog( 'XMP', __METHOD__
. " Encountered </$elm> which has no namespace. Skipping." );
631 if ( count( $this->mode
[0] ) === 0 ) {
632 // This should never ever happen and means
633 // there is a pretty major bug in this class.
634 throw new MWException( 'Encountered end element with no mode' );
637 if ( count( $this->curItem
) == 0 && $this->mode
[0] !== self
::MODE_INITIAL
) {
638 // just to be paranoid. Should always have a curItem, except for initially
639 // (aka during MODE_INITAL).
640 throw new MWException( "Hit end element </$elm> but no curItem" );
643 switch( $this->mode
[0] ) {
644 case self
::MODE_IGNORE
:
645 $this->endElementModeIgnore( $elm );
647 case self
::MODE_SIMPLE
:
648 $this->endElementModeSimple( $elm );
650 case self
::MODE_STRUCT
:
653 case self
::MODE_LANG
:
654 case self
::MODE_BAGSTRUCT
:
655 $this->endElementNested( $elm );
657 case self
::MODE_INITIAL
:
658 if ( $elm === self
::NS_RDF
. ' Description' ) {
659 array_shift( $this->mode
);
661 throw new MWException( 'Element ended unexpectedly while in MODE_INITIAL' );
665 case self
::MODE_LI_LANG
:
666 $this->endElementModeLi( $elm );
668 case self
::MODE_QDESC
:
669 $this->endElementModeQDesc( $elm );
672 wfDebugLog( 'XMP', __METHOD__
. " no mode (elm = $elm)" );
678 * Hit an opening element while in MODE_IGNORE
680 * XMP is extensible, so ignore any tag we don't understand.
682 * Mostly ignores, unless we encounter the element that we are ignoring.
683 * in which case we add it to the item stack, so we can ignore things
684 * that are nested, correctly.
686 * @param $elm String namespace . ' ' . tag name
688 private function startElementModeIgnore( $elm ) {
689 if ( $elm === $this->curItem
[0] ) {
690 array_unshift( $this->curItem
, $elm );
691 array_unshift( $this->mode
, self
::MODE_IGNORE
);
696 * Start element in MODE_BAG (unordered array)
697 * this should always be <rdf:Bag>
699 * @param $elm String namespace . ' ' . tag
700 * @throws MWException if we have an element that's not <rdf:Bag>
702 private function startElementModeBag( $elm ) {
703 if ( $elm === self
::NS_RDF
. ' Bag' ) {
704 array_unshift( $this->mode
, self
::MODE_LI
);
706 throw new MWException( "Expected <rdf:Bag> but got $elm." );
712 * Start element in MODE_SEQ (ordered array)
713 * this should always be <rdf:Seq>
715 * @param $elm String namespace . ' ' . tag
716 * @throws MWException if we have an element that's not <rdf:Seq>
718 private function startElementModeSeq( $elm ) {
719 if ( $elm === self
::NS_RDF
. ' Seq' ) {
720 array_unshift( $this->mode
, self
::MODE_LI
);
721 } elseif ( $elm === self
::NS_RDF
. ' Bag' ) {
723 wfDebugLog( 'XMP', __METHOD__
. ' Expected an rdf:Seq, but got an rdf:Bag. Pretending'
724 . ' it is a Seq, since some buggy software is known to screw this up.' );
725 array_unshift( $this->mode
, self
::MODE_LI
);
727 throw new MWException( "Expected <rdf:Seq> but got $elm." );
733 * Start element in MODE_LANG (language alternative)
734 * this should always be <rdf:Alt>
736 * This tag tends to be used for metadata like describe this
737 * picture, which can be translated into multiple languages.
739 * XMP supports non-linguistic alternative selections,
740 * which are really only used for thumbnails, which
741 * we don't care about.
743 * @param $elm String namespace . ' ' . tag
744 * @throws MWException if we have an element that's not <rdf:Alt>
746 private function startElementModeLang( $elm ) {
747 if ( $elm === self
::NS_RDF
. ' Alt' ) {
748 array_unshift( $this->mode
, self
::MODE_LI_LANG
);
750 throw new MWException( "Expected <rdf:Seq> but got $elm." );
756 * Handle an opening element when in MODE_SIMPLE
758 * This should not happen often. This is for if a simple element
759 * already opened has a child element. Could happen for a
763 * <exif:DigitalZoomRatio><rdf:Description><rdf:value>0/10</rdf:value>
764 * <foo:someQualifier>Bar</foo:someQualifier> </rdf:Description>
765 * </exif:DigitalZoomRatio>
767 * This method is called when processing the <rdf:Description> element
769 * @param $elm String namespace and tag names separated by space.
770 * @param $attribs Array Attributes of the element.
772 private function startElementModeSimple( $elm, $attribs ) {
773 if ( $elm === self
::NS_RDF
. ' Description' ) {
774 // If this value has qualifiers
775 array_unshift( $this->mode
, self
::MODE_QDESC
);
776 array_unshift( $this->curItem
, $this->curItem
[0] );
778 if ( isset( $attribs[self
::NS_RDF
. ' value'] ) ) {
779 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
780 $this->saveValue( $ns, $tag, $attribs[self
::NS_RDF
. ' value'] );
782 } elseif ( $elm === self
::NS_RDF
. ' value' ) {
783 // This should not be here.
784 throw new MWException( __METHOD__
. ' Encountered <rdf:value> where it was unexpected.' );
787 // something else we don't recognize, like a qualifier maybe.
788 wfDebugLog( 'XMP', __METHOD__
. " Encountered element <$elm> where only expecting character data as value of " . $this->curItem
[0] );
789 array_unshift( $this->mode
, self
::MODE_IGNORE
);
790 array_unshift( $this->curItem
, $elm );
797 * Start an element when in MODE_QDESC.
798 * This generally happens when a simple element has an inner
799 * rdf:Description to hold qualifier elements.
802 * <exif:DigitalZoomRatio><rdf:Description><rdf:value>0/10</rdf:value>
803 * <foo:someQualifier>Bar</foo:someQualifier> </rdf:Description>
804 * </exif:DigitalZoomRatio>
805 * Called when processing the <rdf:value> or <foo:someQualifier>.
807 * @param $elm String namespace and tag name separated by a space.
810 private function startElementModeQDesc( $elm ) {
811 if ( $elm === self
::NS_RDF
. ' value' ) {
812 return; // do nothing
814 // otherwise its a qualifier, which we ignore
815 array_unshift( $this->mode
, self
::MODE_IGNORE
);
816 array_unshift( $this->curItem
, $elm );
821 * Starting an element when in MODE_INITIAL
822 * This usually happens when we hit an element inside
823 * the outer rdf:Description
825 * This is generally where most properties start.
827 * @param $ns String Namespace
828 * @param $tag String tag name (without namespace prefix)
829 * @param $attribs Array array of attributes
831 private function startElementModeInitial( $ns, $tag, $attribs ) {
832 if ( $ns !== self
::NS_RDF
) {
834 if ( isset( $this->items
[$ns][$tag] ) ) {
835 if ( isset( $this->items
[$ns][$tag]['structPart'] ) ) {
836 // If this element is supposed to appear only as
837 // a child of a structure, but appears here (not as
838 // a child of a struct), then something weird is
839 // happening, so ignore this element and its children.
841 wfDebugLog( 'XMP', "Encountered <$ns:$tag> outside"
842 . " of its expected parent. Ignoring." );
844 array_unshift( $this->mode
, self
::MODE_IGNORE
);
845 array_unshift( $this->curItem
, $ns . ' ' . $tag );
848 $mode = $this->items
[$ns][$tag]['mode'];
849 array_unshift( $this->mode
, $mode );
850 array_unshift( $this->curItem
, $ns . ' ' . $tag );
851 if ( $mode === self
::MODE_STRUCT
) {
852 $this->ancestorStruct
= isset( $this->items
[$ns][$tag]['map_name'] )
853 ?
$this->items
[$ns][$tag]['map_name'] : $tag;
855 if ( $this->charContent
!== false ) {
857 // Should not happen in valid XMP.
858 throw new MWException( 'tag nested in non-whitespace characters.' );
861 // This element is not on our list of allowed elements so ignore.
862 wfDebugLog( 'XMP', __METHOD__
. " Ignoring unrecognized element <$ns:$tag>." );
863 array_unshift( $this->mode
, self
::MODE_IGNORE
);
864 array_unshift( $this->curItem
, $ns . ' ' . $tag );
869 // process attributes
870 $this->doAttribs( $attribs );
874 * Hit an opening element when in a Struct (MODE_STRUCT)
875 * This is generally for fields of a compound property.
877 * Example of a struct (abbreviated; flash has more properties):
879 * <exif:Flash> <rdf:Description> <exif:Fired>True</exif:Fired>
880 * <exif:Mode>1</exif:Mode></rdf:Description></exif:Flash>
884 * <exif:Flash rdf:parseType='Resource'> <exif:Fired>True</exif:Fired>
885 * <exif:Mode>1</exif:Mode></exif:Flash>
887 * @param $ns String namespace
888 * @param $tag String tag name (no ns)
889 * @param $attribs Array array of attribs w/ values.
891 private function startElementModeStruct( $ns, $tag, $attribs ) {
892 if ( $ns !== self
::NS_RDF
) {
894 if ( isset( $this->items
[$ns][$tag] ) ) {
895 if ( isset( $this->items
[$ns][$this->ancestorStruct
]['children'] )
896 && !isset( $this->items
[$ns][$this->ancestorStruct
]['children'][$tag] ) )
898 // This assumes that we don't have inter-namespace nesting
899 // which we don't in all the properties we're interested in.
900 throw new MWException( " <$tag> appeared nested in <" . $this->ancestorStruct
901 . "> where it is not allowed." );
903 array_unshift( $this->mode
, $this->items
[$ns][$tag]['mode'] );
904 array_unshift( $this->curItem
, $ns . ' ' . $tag );
905 if ( $this->charContent
!== false ) {
907 // Should not happen in valid XMP.
908 throw new MWException( "tag <$tag> nested in non-whitespace characters (" . $this->charContent
. ")." );
911 array_unshift( $this->mode
, self
::MODE_IGNORE
);
912 array_unshift( $this->curItem
, $elm );
918 if ( $ns === self
::NS_RDF
&& $tag === 'Description' ) {
919 $this->doAttribs( $attribs );
920 array_unshift( $this->mode
, self
::MODE_STRUCT
);
921 array_unshift( $this->curItem
, $this->curItem
[0] );
926 * opening element in MODE_LI
927 * process elements of arrays.
930 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
931 * </rdf:Seq> </exif:ISOSpeedRatings>
932 * This method is called when we hit the <rdf:li> element.
934 * @param $elm String: namespace . ' ' . tagname
935 * @param $attribs Array: Attributes. (needed for BAGSTRUCTS)
936 * @throws MWException if gets a tag other than <rdf:li>
938 private function startElementModeLi( $elm, $attribs ) {
939 if ( ( $elm ) !== self
::NS_RDF
. ' li' ) {
940 throw new MWException( "<rdf:li> expected but got $elm." );
943 if ( !isset( $this->mode
[1] ) ) {
944 // This should never ever ever happen. Checking for it
946 throw new MWException( 'In mode Li, but no 2xPrevious mode!' );
949 if ( $this->mode
[1] === self
::MODE_BAGSTRUCT
) {
950 // This list item contains a compound (STRUCT) value.
951 array_unshift( $this->mode
, self
::MODE_STRUCT
);
952 array_unshift( $this->curItem
, $elm );
953 $this->processingArray
= true;
955 if ( !isset( $this->curItem
[1] ) ) {
957 throw new MWException( 'Can not find parent of BAGSTRUCT.' );
959 list( $curNS, $curTag ) = explode( ' ', $this->curItem
[1] );
960 $this->ancestorStruct
= isset( $this->items
[$curNS][$curTag]['map_name'] )
961 ?
$this->items
[$curNS][$curTag]['map_name'] : $curTag;
963 $this->doAttribs( $attribs );
966 // Normal BAG or SEQ containing simple values.
967 array_unshift( $this->mode
, self
::MODE_SIMPLE
);
968 // need to add curItem[0] on again since one is for the specific item
969 // and one is for the entire group.
970 array_unshift( $this->curItem
, $this->curItem
[0] );
971 $this->processingArray
= true;
977 * Opening element in MODE_LI_LANG.
978 * process elements of language alternatives
981 * <dc:title> <rdf:Alt> <rdf:li xml:lang="x-default">My house
982 * </rdf:li> </rdf:Alt> </dc:title>
984 * This method is called when we hit the <rdf:li> element.
986 * @param $elm String namespace . ' ' . tag
987 * @param $attribs array array of elements (most importantly xml:lang)
988 * @throws MWException if gets a tag other than <rdf:li> or if no xml:lang
990 private function startElementModeLiLang( $elm, $attribs ) {
991 if ( $elm !== self
::NS_RDF
. ' li' ) {
992 throw new MWException( __METHOD__
. " <rdf:li> expected but got $elm." );
994 if ( !isset( $attribs[ self
::NS_XML
. ' lang'] )
995 ||
!preg_match( '/^[-A-Za-z0-9]{2,}$/D', $attribs[ self
::NS_XML
. ' lang' ] ) )
997 throw new MWException( __METHOD__
998 . " <rdf:li> did not contain, or has invalid xml:lang attribute in lang alternative" );
1001 // Lang is case-insensitive.
1002 $this->itemLang
= strtolower( $attribs[ self
::NS_XML
. ' lang' ] );
1004 // need to add curItem[0] on again since one is for the specific item
1005 // and one is for the entire group.
1006 array_unshift( $this->curItem
, $this->curItem
[0] );
1007 array_unshift( $this->mode
, self
::MODE_SIMPLE
);
1008 $this->processingArray
= true;
1012 * Hits an opening element.
1013 * Generally just calls a helper based on what MODE we're in.
1014 * Also does some initial set up for the wrapper element
1016 * @param $parser XMLParser
1017 * @param $elm String namespace "<space>" element
1018 * @param $attribs Array attribute name => value
1020 function startElement( $parser, $elm, $attribs ) {
1022 if ( $elm === self
::NS_RDF
. ' RDF'
1023 ||
$elm === 'adobe:ns:meta/ xmpmeta'
1024 ||
$elm === 'adobe:ns:meta/ xapmeta')
1028 } elseif ( $elm === self
::NS_RDF
. ' Description' ) {
1029 if ( count( $this->mode
) === 0 ) {
1031 array_unshift( $this->mode
, self
::MODE_INITIAL
);
1033 } elseif ( $elm === self
::NS_RDF
. ' type' ) {
1034 // This doesn't support rdf:type properly.
1035 // In practise I have yet to see a file that
1036 // uses this element, however it is mentioned
1037 // on page 25 of part 1 of the xmp standard.
1039 // also it seems as if exiv2 and exiftool do not support
1040 // this either (That or I misunderstand the standard)
1041 wfDebugLog( 'XMP', __METHOD__
. ' Encountered <rdf:type> which isn\'t currently supported' );
1044 if ( strpos( $elm, ' ' ) === false ) {
1045 // This probably shouldn't happen.
1046 wfDebugLog( 'XMP', __METHOD__
. " Encountered <$elm> which has no namespace. Skipping." );
1050 list( $ns, $tag ) = explode( ' ', $elm, 2 );
1052 if ( count( $this->mode
) === 0 ) {
1053 // This should not happen.
1054 throw new MWException('Error extracting XMP, '
1055 . "encountered <$elm> with no mode" );
1058 switch( $this->mode
[0] ) {
1059 case self
::MODE_IGNORE
:
1060 $this->startElementModeIgnore( $elm );
1062 case self
::MODE_SIMPLE
:
1063 $this->startElementModeSimple( $elm, $attribs );
1065 case self
::MODE_INITIAL
:
1066 $this->startElementModeInitial( $ns, $tag, $attribs );
1068 case self
::MODE_STRUCT
:
1069 $this->startElementModeStruct( $ns, $tag, $attribs );
1071 case self
::MODE_BAG
:
1072 case self
::MODE_BAGSTRUCT
:
1073 $this->startElementModeBag( $elm );
1075 case self
::MODE_SEQ
:
1076 $this->startElementModeSeq( $elm );
1078 case self
::MODE_LANG
:
1079 $this->startElementModeLang( $elm );
1081 case self
::MODE_LI_LANG
:
1082 $this->startElementModeLiLang( $elm, $attribs );
1085 $this->startElementModeLi( $elm, $attribs );
1087 case self
::MODE_QDESC
:
1088 $this->startElementModeQDesc( $elm );
1091 throw new MWException( 'StartElement in unknown mode: ' . $this->mode
[0] );
1097 * Process attributes.
1098 * Simple values can be stored as either a tag or attribute
1100 * Often the initial "<rdf:Description>" tag just has all the simple
1101 * properties as attributes.
1105 * <rdf:Description rdf:about="" xmlns:exif="http://ns.adobe.com/exif/1.0/" exif:DigitalZoomRatio="0/10">
1108 * @param $attribs Array attribute=>value array.
1110 private function doAttribs( $attribs ) {
1112 // first check for rdf:parseType attribute, as that can change
1113 // how the attributes are interperted.
1115 if ( isset( $attribs[self
::NS_RDF
. ' parseType'] )
1116 && $attribs[self
::NS_RDF
. ' parseType'] === 'Resource'
1117 && $this->mode
[0] === self
::MODE_SIMPLE
)
1119 // this is equivalent to having an inner rdf:Description
1120 $this->mode
[0] = self
::MODE_QDESC
;
1122 foreach ( $attribs as $name => $val ) {
1125 if ( strpos( $name, ' ' ) === false ) {
1126 // This shouldn't happen, but so far some old software forgets namespace
1128 wfDebugLog( 'XMP', __METHOD__
. ' Encountered non-namespaced attribute: '
1129 . " $name=\"$val\". Skipping. " );
1132 list( $ns, $tag ) = explode( ' ', $name, 2 );
1133 if ( $ns === self
::NS_RDF
) {
1134 if ( $tag === 'value' ||
$tag === 'resource' ) {
1135 // resource is for url.
1136 // value attribute is a weird way of just putting the contents.
1137 $this->char( $this->xmlParser
, $val );
1139 } elseif ( isset( $this->items
[$ns][$tag] ) ) {
1140 if ( $this->mode
[0] === self
::MODE_SIMPLE
) {
1141 throw new MWException( __METHOD__
1142 . " $ns:$tag found as attribute where not allowed" );
1144 $this->saveValue( $ns, $tag, $val );
1146 wfDebugLog( 'XMP', __METHOD__
. " Ignoring unrecognized element <$ns:$tag>." );
1152 * Given an extracted value, save it to results array
1154 * note also uses $this->ancestorStruct and
1155 * $this->processingArray to determine what name to
1156 * save the value under. (in addition to $tag).
1158 * @param $ns String namespace of tag this is for
1159 * @param $tag String tag name
1160 * @param $val String value to save
1162 private function saveValue( $ns, $tag, $val ) {
1164 $info =& $this->items
[$ns][$tag];
1165 $finalName = isset( $info['map_name'] )
1166 ?
$info['map_name'] : $tag;
1167 if ( isset( $info['validate'] ) ) {
1168 $validate = is_array( $info['validate'] ) ?
$info['validate']
1169 : array( 'XMPValidate', $info['validate'] );
1171 if ( is_callable( $validate ) ) {
1172 call_user_func_array( $validate, array( $info, &$val, true ) );
1173 // the reasoning behind using &$val instead of using the return value
1174 // is to be consistent between here and validating structures.
1175 if ( is_null( $val ) ) {
1176 wfDebugLog( 'XMP', __METHOD__
. " <$ns:$tag> failed validation." );
1180 wfDebugLog( 'XMP', __METHOD__
. " Validation function for $finalName ("
1181 . $validate[0] . '::' . $validate[1] . '()) is not callable.' );
1185 if ( $this->ancestorStruct
&& $this->processingArray
) {
1186 // Aka both an array and a struct. ( self::MODE_BAGSTRUCT )
1187 $this->results
['xmp-' . $info['map_group']][$this->ancestorStruct
][][$finalName] = $val;
1188 } elseif ( $this->ancestorStruct
) {
1189 $this->results
['xmp-' . $info['map_group']][$this->ancestorStruct
][$finalName] = $val;
1190 } elseif ( $this->processingArray
) {
1191 if ( $this->itemLang
=== false ) {
1193 $this->results
['xmp-' . $info['map_group']][$finalName][] = $val;
1196 $this->results
['xmp-' . $info['map_group']][$finalName][$this->itemLang
] = $val;
1199 $this->results
['xmp-' . $info['map_group']][$finalName] = $val;