3 * Reader for XMP data containing properties relevant to images.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * Class for reading xmp data containing properties relevant to
26 * images, and spitting out an array that FormatExif accepts.
28 * Note, this is not meant to recognize every possible thing you can
29 * encode in XMP. It should recognize all the properties we want.
30 * For example it doesn't have support for structures with multiple
31 * nesting levels, as none of the properties we're supporting use that
32 * feature. If it comes across properties it doesn't recognize, it should
35 * The public methods one would call in this class are
37 * Reads in xmp content.
38 * Can potentially be called multiple times with partial data each time.
39 * - parseExtended( $content )
40 * Reads XMPExtended blocks (jpeg files only).
42 * Outputs a results array.
44 * Note XMP kind of looks like rdf. They are not the same thing - XMP is
45 * encoded as a specific subset of rdf. This class can read XMP. It cannot
51 private $curItem = array(); // array to hold the current element (and previous element, and so on)
52 private $ancestorStruct = false; // the structure name when processing nested structures.
53 private $charContent = false; // temporary holder for character data that appears in xmp doc.
54 private $mode = array(); // stores the state the xmpreader is in (see MODE_FOO constants)
55 private $results = array(); // array to hold results
56 private $processingArray = false; // if we're doing a seq or bag.
57 private $itemLang = false; // used for lang alts only
60 private $charset = false;
61 private $extendedXMPOffset = 0;
66 * These are various mode constants.
67 * they are used to figure out what to do
68 * with an element when its encountered.
70 * For example, MODE_IGNORE is used when processing
71 * a property we're not interested in. So if a new
72 * element pops up when we're in that mode, we ignore it.
74 const MODE_INITIAL
= 0;
75 const MODE_IGNORE
= 1;
77 const MODE_LI_LANG
= 3;
80 // The following MODE constants are also used in the
81 // $items array to denote what type of property the item is.
82 const MODE_SIMPLE
= 10;
83 const MODE_STRUCT
= 11; // structure (associative array)
84 const MODE_SEQ
= 12; // ordered list
85 const MODE_BAG
= 13; // unordered list
87 const MODE_ALT
= 15; // non-language alt. Currently not implemented, and not needed atm.
88 const MODE_BAGSTRUCT
= 16; // A BAG of Structs.
90 const NS_RDF
= 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
91 const NS_XML
= 'http://www.w3.org/XML/1998/namespace';
97 * Primary job is to initialize the XMLParser
99 function __construct() {
101 if ( !function_exists( 'xml_parser_create_ns' ) ) {
102 // this should already be checked by this point
103 throw new MWException( 'XMP support requires XML Parser' );
106 $this->items
= XMPInfo
::getItems();
108 $this->resetXMLParser();
112 * Main use is if a single item has multiple xmp documents describing it.
113 * For example in jpeg's with extendedXMP
115 private function resetXMLParser() {
117 if ($this->xmlParser
) {
119 xml_parser_free( $this->xmlParser
);
122 $this->xmlParser
= xml_parser_create_ns( 'UTF-8', ' ' );
123 xml_parser_set_option( $this->xmlParser
, XML_OPTION_CASE_FOLDING
, 0 );
124 xml_parser_set_option( $this->xmlParser
, XML_OPTION_SKIP_WHITE
, 1 );
126 xml_set_element_handler( $this->xmlParser
,
127 array( $this, 'startElement' ),
128 array( $this, 'endElement' ) );
130 xml_set_character_data_handler( $this->xmlParser
, array( $this, 'char' ) );
133 /** Destroy the xml parser
135 * Not sure if this is actually needed.
137 function __destruct() {
138 // not sure if this is needed.
139 xml_parser_free( $this->xmlParser
);
142 /** Get the result array. Do some post-processing before returning
143 * the array, and transform any metadata that is special-cased.
145 * @return Array array of results as an array of arrays suitable for
146 * FormatMetadata::getFormattedData().
148 public function getResults() {
149 // xmp-special is for metadata that affects how stuff
150 // is extracted. For example xmpNote:HasExtendedXMP.
152 // It is also used to handle photoshop:AuthorsPosition
153 // which is weird and really part of another property,
154 // see 2:85 in IPTC. See also pg 21 of IPTC4XMP standard.
155 // The location fields also use it.
157 $data = $this->results
;
159 wfRunHooks('XMPGetResults', Array(&$data));
161 if ( isset( $data['xmp-special']['AuthorsPosition'] )
162 && is_string( $data['xmp-special']['AuthorsPosition'] )
163 && isset( $data['xmp-general']['Artist'][0] )
165 // Note, if there is more than one creator,
166 // this only applies to first. This also will
167 // only apply to the dc:Creator prop, not the
170 $data['xmp-general']['Artist'][0] =
171 $data['xmp-special']['AuthorsPosition'] . ', '
172 . $data['xmp-general']['Artist'][0];
175 // Go through the LocationShown and LocationCreated
176 // changing it to the non-hierarchal form used by
177 // the other location fields.
179 if ( isset( $data['xmp-special']['LocationShown'][0] )
180 && is_array( $data['xmp-special']['LocationShown'][0] )
182 // the is_array is just paranoia. It should always
184 foreach( $data['xmp-special']['LocationShown'] as $loc ) {
185 if ( !is_array( $loc ) ) {
186 // To avoid copying over the _type meta-fields.
189 foreach( $loc as $field => $val ) {
190 $data['xmp-general'][$field . 'Dest'][] = $val;
194 if ( isset( $data['xmp-special']['LocationCreated'][0] )
195 && is_array( $data['xmp-special']['LocationCreated'][0] )
197 // the is_array is just paranoia. It should always
199 foreach( $data['xmp-special']['LocationCreated'] as $loc ) {
200 if ( !is_array( $loc ) ) {
201 // To avoid copying over the _type meta-fields.
204 foreach( $loc as $field => $val ) {
205 $data['xmp-general'][$field . 'Created'][] = $val;
211 // We don't want to return the special values, since they're
212 // special and not info to be stored about the file.
213 unset( $data['xmp-special'] );
215 // Convert GPSAltitude to negative if below sea level.
216 if ( isset( $data['xmp-exif']['GPSAltitudeRef'] )
217 && isset( $data['xmp-exif']['GPSAltitude'] )
220 // Must convert to a real before multiplying by -1
221 // XMPValidate guarantees there will always be a '/' in this value.
222 list( $nom, $denom ) = explode( '/', $data['xmp-exif']['GPSAltitude'] );
223 $data['xmp-exif']['GPSAltitude'] = $nom / $denom;
225 if ( $data['xmp-exif']['GPSAltitudeRef'] == '1' ) {
226 $data['xmp-exif']['GPSAltitude'] *= -1;
228 unset( $data['xmp-exif']['GPSAltitudeRef'] );
235 * Main function to call to parse XMP. Use getResults to
238 * Also catches any errors during processing, writes them to
239 * debug log, blanks result array and returns false.
241 * @param $content String: XMP data
242 * @param $allOfIt Boolean: If this is all the data (true) or if its split up (false). Default true
243 * @param $reset Boolean: does xml parser need to be reset. Default false
244 * @return Boolean success.
246 public function parse( $content, $allOfIt = true, $reset = false ) {
248 $this->resetXMLParser();
252 // detect encoding by looking for BOM which is supposed to be in processing instruction.
253 // see page 12 of http://www.adobe.com/devnet/xmp/pdfs/XMPSpecificationPart3.pdf
254 if ( !$this->charset
) {
256 if ( preg_match( '/\xEF\xBB\xBF|\xFE\xFF|\x00\x00\xFE\xFF|\xFF\xFE\x00\x00|\xFF\xFE/',
261 $this->charset
= 'UTF-16BE';
264 $this->charset
= 'UTF-16LE';
266 case "\x00\x00\xFE\xFF":
267 $this->charset
= 'UTF-32BE';
269 case "\xFF\xFE\x00\x00":
270 $this->charset
= 'UTF-32LE';
273 $this->charset
= 'UTF-8';
276 //this should be impossible to get to
277 throw new MWException("Invalid BOM");
283 // standard specifically says, if no bom assume utf-8
284 $this->charset
= 'UTF-8';
287 if ( $this->charset
!== 'UTF-8' ) {
288 //don't convert if already utf-8
289 wfSuppressWarnings();
290 $content = iconv( $this->charset
, 'UTF-8//IGNORE', $content );
294 $ok = xml_parse( $this->xmlParser
, $content, $allOfIt );
296 $error = xml_error_string( xml_get_error_code( $this->xmlParser
) );
297 $where = 'line: ' . xml_get_current_line_number( $this->xmlParser
)
298 . ' column: ' . xml_get_current_column_number( $this->xmlParser
)
299 . ' byte offset: ' . xml_get_current_byte_index( $this->xmlParser
);
301 wfDebugLog( 'XMP', "XMPReader::parse : Error reading XMP content: $error ($where)" );
302 $this->results
= array(); // blank if error.
305 } catch ( MWException
$e ) {
306 wfDebugLog( 'XMP', 'XMP parse error: ' . $e );
307 $this->results
= array();
313 /** Entry point for XMPExtended blocks in jpeg files
315 * @todo In serious need of testing
316 * @see http://www.adobe.ge/devnet/xmp/pdfs/XMPSpecificationPart3.pdf XMP spec part 3 page 20
317 * @param String $content XMPExtended block minus the namespace signature
318 * @return Boolean If it succeeded.
320 public function parseExtended( $content ) {
321 // @todo FIXME: This is untested. Hard to find example files
322 // or programs that make such files..
323 $guid = substr( $content, 0, 32 );
324 if ( !isset( $this->results
['xmp-special']['HasExtendedXMP'] )
325 ||
$this->results
['xmp-special']['HasExtendedXMP'] !== $guid ) {
326 wfDebugLog('XMP', __METHOD__
. " Ignoring XMPExtended block due to wrong guid (guid= '$guid' )");
329 $len = unpack( 'Nlength/Noffset', substr( $content, 32, 8 ) );
331 if (!$len ||
$len['length'] < 4 ||
$len['offset'] < 0 ||
$len['offset'] > $len['length'] ) {
332 wfDebugLog('XMP', __METHOD__
. 'Error reading extended XMP block, invalid length or offset.');
337 // we're not very robust here. we should accept it in the wrong order. To quote
339 // "A JPEG writer should write the ExtendedXMP marker segments in order, immediately following the
340 // StandardXMP. However, the JPEG standard does not require preservation of marker segment order. A
341 // robust JPEG reader should tolerate the marker segments in any order."
343 // otoh the probability that an image will have more than 128k of metadata is rather low...
344 // so the probability that it will have > 128k, and be in the wrong order is very low...
346 if ( $len['offset'] !== $this->extendedXMPOffset
) {
347 wfDebugLog('XMP', __METHOD__
. 'Ignoring XMPExtended block due to wrong order. (Offset was '
348 . $len['offset'] . ' but expected ' . $this->extendedXMPOffset
. ')');
352 if ( $len['offset'] === 0 ) {
353 // if we're starting the extended block, we've probably already
354 // done the XMPStandard block, so reset.
355 $this->resetXMLParser();
358 $this->extendedXMPOffset +
= $len['length'];
360 $actualContent = substr( $content, 40 );
362 if ( $this->extendedXMPOffset
=== strlen( $actualContent ) ) {
368 wfDebugLog('XMP', __METHOD__
. 'Parsing a XMPExtended block');
369 return $this->parse( $actualContent, $atEnd );
373 * Character data handler
374 * Called whenever character data is found in the xmp document.
376 * does nothing if we're in MODE_IGNORE or if the data is whitespace
377 * throws an error if we're not in MODE_SIMPLE (as we're not allowed to have character
378 * data in the other modes).
380 * As an example, this happens when we encounter XMP like:
381 * <exif:DigitalZoomRatio>0/10</exif:DigitalZoomRatio>
382 * and are processing the 0/10 bit.
384 * @param $parser XMLParser reference to the xml parser
385 * @param $data String Character data
386 * @throws MWException on invalid data
388 function char( $parser, $data ) {
390 $data = trim( $data );
391 if ( trim( $data ) === "" ) {
395 if ( !isset( $this->mode
[0] ) ) {
396 throw new MWException( 'Unexpected character data before first rdf:Description element' );
399 if ( $this->mode
[0] === self
::MODE_IGNORE
) return;
401 if ( $this->mode
[0] !== self
::MODE_SIMPLE
402 && $this->mode
[0] !== self
::MODE_QDESC
404 throw new MWException( 'character data where not expected. (mode ' . $this->mode
[0] . ')' );
407 // to check, how does this handle w.s.
408 if ( $this->charContent
=== false ) {
409 $this->charContent
= $data;
411 $this->charContent
.= $data;
416 /** When we hit a closing element in MODE_IGNORE
417 * Check to see if this is the element we started to ignore,
418 * in which case we get out of MODE_IGNORE
420 * @param $elm String Namespace of element followed by a space and then tag name of element.
422 private function endElementModeIgnore ( $elm ) {
424 if ( $this->curItem
[0] === $elm ) {
425 array_shift( $this->curItem
);
426 array_shift( $this->mode
);
433 * Hit a closing element when in MODE_SIMPLE.
434 * This generally means that we finished processing a
435 * property value, and now have to save the result to the
438 * For example, when processing:
439 * <exif:DigitalZoomRatio>0/10</exif:DigitalZoomRatio>
440 * this deals with when we hit </exif:DigitalZoomRatio>.
442 * Or it could be if we hit the end element of a property
443 * of a compound data structure (like a member of an array).
445 * @param $elm String namespace, space, and tag name.
447 private function endElementModeSimple ( $elm ) {
448 if ( $this->charContent
!== false ) {
449 if ( $this->processingArray
) {
450 // if we're processing an array, use the original element
451 // name instead of rdf:li.
452 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
454 list( $ns, $tag ) = explode( ' ', $elm, 2 );
456 $this->saveValue( $ns, $tag, $this->charContent
);
458 $this->charContent
= false; // reset
460 array_shift( $this->curItem
);
461 array_shift( $this->mode
);
466 * Hit a closing element in MODE_STRUCT, MODE_SEQ, MODE_BAG
467 * generally means we've finished processing a nested structure.
468 * resets some internal variables to indicate that.
470 * Note this means we hit the closing element not the "</rdf:Seq>".
472 * @par For example, when processing:
474 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
475 * </rdf:Seq> </exif:ISOSpeedRatings>
478 * This method is called when we hit the "</exif:ISOSpeedRatings>" tag.
480 * @param $elm String namespace . space . tag name.
482 private function endElementNested( $elm ) {
484 /* cur item must be the same as $elm, unless if in MODE_STRUCT
485 in which case it could also be rdf:Description */
486 if ( $this->curItem
[0] !== $elm
487 && !( $elm === self
::NS_RDF
. ' Description'
488 && $this->mode
[0] === self
::MODE_STRUCT
)
490 throw new MWException( "nesting mismatch. got a </$elm> but expected a </" . $this->curItem
[0] . '>' );
493 // Validate structures.
494 list( $ns, $tag ) = explode( ' ', $elm, 2 );
495 if ( isset( $this->items
[$ns][$tag]['validate'] ) ) {
497 $info =& $this->items
[$ns][$tag];
498 $finalName = isset( $info['map_name'] )
499 ?
$info['map_name'] : $tag;
501 $validate = is_array( $info['validate'] ) ?
$info['validate']
502 : array( 'XMPValidate', $info['validate'] );
504 if ( !isset( $this->results
['xmp-' . $info['map_group']][$finalName] ) ) {
505 // This can happen if all the members of the struct failed validation.
506 wfDebugLog( 'XMP', __METHOD__
. " <$ns:$tag> has no valid members." );
508 } elseif ( is_callable( $validate ) ) {
509 $val =& $this->results
['xmp-' . $info['map_group']][$finalName];
510 call_user_func_array( $validate, array( $info, &$val, false ) );
511 if ( is_null( $val ) ) {
512 // the idea being the validation function will unset the variable if
514 wfDebugLog( 'XMP', __METHOD__
. " <$ns:$tag> failed validation." );
515 unset( $this->results
['xmp-' . $info['map_group']][$finalName] );
518 wfDebugLog( 'XMP', __METHOD__
. " Validation function for $finalName ("
519 . $validate[0] . '::' . $validate[1] . '()) is not callable.' );
523 array_shift( $this->curItem
);
524 array_shift( $this->mode
);
525 $this->ancestorStruct
= false;
526 $this->processingArray
= false;
527 $this->itemLang
= false;
531 * Hit a closing element in MODE_LI (either rdf:Seq, or rdf:Bag )
532 * Add information about what type of element this is.
534 * Note we still have to hit the outer "</property>"
536 * @par For example, when processing:
538 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
539 * </rdf:Seq> </exif:ISOSpeedRatings>
542 * This method is called when we hit the "</rdf:Seq>".
543 * (For comparison, we call endElementModeSimple when we
544 * hit the "</rdf:li>")
546 * @param $elm String namespace . ' ' . element name
548 private function endElementModeLi( $elm ) {
550 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
551 $info = $this->items
[$ns][$tag];
552 $finalName = isset( $info['map_name'] )
553 ?
$info['map_name'] : $tag;
555 array_shift( $this->mode
);
557 if ( !isset( $this->results
['xmp-' . $info['map_group']][$finalName] ) ) {
558 wfDebugLog( 'XMP', __METHOD__
. " Empty compund element $finalName." );
562 if ( $elm === self
::NS_RDF
. ' Seq' ) {
563 $this->results
['xmp-' . $info['map_group']][$finalName]['_type'] = 'ol';
564 } elseif ( $elm === self
::NS_RDF
. ' Bag' ) {
565 $this->results
['xmp-' . $info['map_group']][$finalName]['_type'] = 'ul';
566 } elseif ( $elm === self
::NS_RDF
. ' Alt' ) {
567 // extra if needed as you could theoretically have a non-language alt.
568 if ( $info['mode'] === self
::MODE_LANG
) {
569 $this->results
['xmp-' . $info['map_group']][$finalName]['_type'] = 'lang';
573 throw new MWException( __METHOD__
. " expected </rdf:seq> or </rdf:bag> but instead got $elm." );
578 * End element while in MODE_QDESC
579 * mostly when ending an element when we have a simple value
580 * that has qualifiers.
582 * Qualifiers aren't all that common, and we don't do anything
585 * @param $elm String namespace and element
587 private function endElementModeQDesc( $elm ) {
589 if ( $elm === self
::NS_RDF
. ' value' ) {
590 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
591 $this->saveValue( $ns, $tag, $this->charContent
);
594 array_shift( $this->mode
);
595 array_shift( $this->curItem
);
602 * Handler for hitting a closing element.
604 * generally just calls a helper function depending on what
607 * Ignores the outer wrapping elements that are optional in
608 * xmp and have no meaning.
610 * @param $parser XMLParser
611 * @param $elm String namespace . ' ' . element name
613 function endElement( $parser, $elm ) {
614 if ( $elm === ( self
::NS_RDF
. ' RDF' )
615 ||
$elm === 'adobe:ns:meta/ xmpmeta'
616 ||
$elm === 'adobe:ns:meta/ xapmeta' )
622 if ( $elm === self
::NS_RDF
. ' type' ) {
623 // these aren't really supported properly yet.
624 // However, it appears they almost never used.
625 wfDebugLog( 'XMP', __METHOD__
. ' encountered <rdf:type>' );
628 if ( strpos( $elm, ' ' ) === false ) {
629 // This probably shouldn't happen.
630 // However, there is a bug in an adobe product
631 // that forgets the namespace on some things.
632 // (Luckily they are unimportant things).
633 wfDebugLog( 'XMP', __METHOD__
. " Encountered </$elm> which has no namespace. Skipping." );
637 if ( count( $this->mode
[0] ) === 0 ) {
638 // This should never ever happen and means
639 // there is a pretty major bug in this class.
640 throw new MWException( 'Encountered end element with no mode' );
643 if ( count( $this->curItem
) == 0 && $this->mode
[0] !== self
::MODE_INITIAL
) {
644 // just to be paranoid. Should always have a curItem, except for initially
645 // (aka during MODE_INITAL).
646 throw new MWException( "Hit end element </$elm> but no curItem" );
649 switch( $this->mode
[0] ) {
650 case self
::MODE_IGNORE
:
651 $this->endElementModeIgnore( $elm );
653 case self
::MODE_SIMPLE
:
654 $this->endElementModeSimple( $elm );
656 case self
::MODE_STRUCT
:
659 case self
::MODE_LANG
:
660 case self
::MODE_BAGSTRUCT
:
661 $this->endElementNested( $elm );
663 case self
::MODE_INITIAL
:
664 if ( $elm === self
::NS_RDF
. ' Description' ) {
665 array_shift( $this->mode
);
667 throw new MWException( 'Element ended unexpectedly while in MODE_INITIAL' );
671 case self
::MODE_LI_LANG
:
672 $this->endElementModeLi( $elm );
674 case self
::MODE_QDESC
:
675 $this->endElementModeQDesc( $elm );
678 wfDebugLog( 'XMP', __METHOD__
. " no mode (elm = $elm)" );
684 * Hit an opening element while in MODE_IGNORE
686 * XMP is extensible, so ignore any tag we don't understand.
688 * Mostly ignores, unless we encounter the element that we are ignoring.
689 * in which case we add it to the item stack, so we can ignore things
690 * that are nested, correctly.
692 * @param $elm String namespace . ' ' . tag name
694 private function startElementModeIgnore( $elm ) {
695 if ( $elm === $this->curItem
[0] ) {
696 array_unshift( $this->curItem
, $elm );
697 array_unshift( $this->mode
, self
::MODE_IGNORE
);
702 * Start element in MODE_BAG (unordered array)
703 * this should always be <rdf:Bag>
705 * @param $elm String namespace . ' ' . tag
706 * @throws MWException if we have an element that's not <rdf:Bag>
708 private function startElementModeBag( $elm ) {
709 if ( $elm === self
::NS_RDF
. ' Bag' ) {
710 array_unshift( $this->mode
, self
::MODE_LI
);
712 throw new MWException( "Expected <rdf:Bag> but got $elm." );
718 * Start element in MODE_SEQ (ordered array)
719 * this should always be <rdf:Seq>
721 * @param $elm String namespace . ' ' . tag
722 * @throws MWException if we have an element that's not <rdf:Seq>
724 private function startElementModeSeq( $elm ) {
725 if ( $elm === self
::NS_RDF
. ' Seq' ) {
726 array_unshift( $this->mode
, self
::MODE_LI
);
727 } elseif ( $elm === self
::NS_RDF
. ' Bag' ) {
729 wfDebugLog( 'XMP', __METHOD__
. ' Expected an rdf:Seq, but got an rdf:Bag. Pretending'
730 . ' it is a Seq, since some buggy software is known to screw this up.' );
731 array_unshift( $this->mode
, self
::MODE_LI
);
733 throw new MWException( "Expected <rdf:Seq> but got $elm." );
739 * Start element in MODE_LANG (language alternative)
740 * this should always be <rdf:Alt>
742 * This tag tends to be used for metadata like describe this
743 * picture, which can be translated into multiple languages.
745 * XMP supports non-linguistic alternative selections,
746 * which are really only used for thumbnails, which
747 * we don't care about.
749 * @param $elm String namespace . ' ' . tag
750 * @throws MWException if we have an element that's not <rdf:Alt>
752 private function startElementModeLang( $elm ) {
753 if ( $elm === self
::NS_RDF
. ' Alt' ) {
754 array_unshift( $this->mode
, self
::MODE_LI_LANG
);
756 throw new MWException( "Expected <rdf:Seq> but got $elm." );
762 * Handle an opening element when in MODE_SIMPLE
764 * This should not happen often. This is for if a simple element
765 * already opened has a child element. Could happen for a
769 * <exif:DigitalZoomRatio><rdf:Description><rdf:value>0/10</rdf:value>
770 * <foo:someQualifier>Bar</foo:someQualifier> </rdf:Description>
771 * </exif:DigitalZoomRatio>
773 * This method is called when processing the <rdf:Description> element
775 * @param $elm String namespace and tag names separated by space.
776 * @param $attribs Array Attributes of the element.
778 private function startElementModeSimple( $elm, $attribs ) {
779 if ( $elm === self
::NS_RDF
. ' Description' ) {
780 // If this value has qualifiers
781 array_unshift( $this->mode
, self
::MODE_QDESC
);
782 array_unshift( $this->curItem
, $this->curItem
[0] );
784 if ( isset( $attribs[self
::NS_RDF
. ' value'] ) ) {
785 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
786 $this->saveValue( $ns, $tag, $attribs[self
::NS_RDF
. ' value'] );
788 } elseif ( $elm === self
::NS_RDF
. ' value' ) {
789 // This should not be here.
790 throw new MWException( __METHOD__
. ' Encountered <rdf:value> where it was unexpected.' );
793 // something else we don't recognize, like a qualifier maybe.
794 wfDebugLog( 'XMP', __METHOD__
. " Encountered element <$elm> where only expecting character data as value of " . $this->curItem
[0] );
795 array_unshift( $this->mode
, self
::MODE_IGNORE
);
796 array_unshift( $this->curItem
, $elm );
803 * Start an element when in MODE_QDESC.
804 * This generally happens when a simple element has an inner
805 * rdf:Description to hold qualifier elements.
808 * <exif:DigitalZoomRatio><rdf:Description><rdf:value>0/10</rdf:value>
809 * <foo:someQualifier>Bar</foo:someQualifier> </rdf:Description>
810 * </exif:DigitalZoomRatio>
811 * Called when processing the <rdf:value> or <foo:someQualifier>.
813 * @param $elm String namespace and tag name separated by a space.
816 private function startElementModeQDesc( $elm ) {
817 if ( $elm === self
::NS_RDF
. ' value' ) {
818 return; // do nothing
820 // otherwise its a qualifier, which we ignore
821 array_unshift( $this->mode
, self
::MODE_IGNORE
);
822 array_unshift( $this->curItem
, $elm );
827 * Starting an element when in MODE_INITIAL
828 * This usually happens when we hit an element inside
829 * the outer rdf:Description
831 * This is generally where most properties start.
833 * @param $ns String Namespace
834 * @param $tag String tag name (without namespace prefix)
835 * @param $attribs Array array of attributes
837 private function startElementModeInitial( $ns, $tag, $attribs ) {
838 if ( $ns !== self
::NS_RDF
) {
840 if ( isset( $this->items
[$ns][$tag] ) ) {
841 if ( isset( $this->items
[$ns][$tag]['structPart'] ) ) {
842 // If this element is supposed to appear only as
843 // a child of a structure, but appears here (not as
844 // a child of a struct), then something weird is
845 // happening, so ignore this element and its children.
847 wfDebugLog( 'XMP', "Encountered <$ns:$tag> outside"
848 . " of its expected parent. Ignoring." );
850 array_unshift( $this->mode
, self
::MODE_IGNORE
);
851 array_unshift( $this->curItem
, $ns . ' ' . $tag );
854 $mode = $this->items
[$ns][$tag]['mode'];
855 array_unshift( $this->mode
, $mode );
856 array_unshift( $this->curItem
, $ns . ' ' . $tag );
857 if ( $mode === self
::MODE_STRUCT
) {
858 $this->ancestorStruct
= isset( $this->items
[$ns][$tag]['map_name'] )
859 ?
$this->items
[$ns][$tag]['map_name'] : $tag;
861 if ( $this->charContent
!== false ) {
863 // Should not happen in valid XMP.
864 throw new MWException( 'tag nested in non-whitespace characters.' );
867 // This element is not on our list of allowed elements so ignore.
868 wfDebugLog( 'XMP', __METHOD__
. " Ignoring unrecognized element <$ns:$tag>." );
869 array_unshift( $this->mode
, self
::MODE_IGNORE
);
870 array_unshift( $this->curItem
, $ns . ' ' . $tag );
875 // process attributes
876 $this->doAttribs( $attribs );
880 * Hit an opening element when in a Struct (MODE_STRUCT)
881 * This is generally for fields of a compound property.
883 * Example of a struct (abbreviated; flash has more properties):
885 * <exif:Flash> <rdf:Description> <exif:Fired>True</exif:Fired>
886 * <exif:Mode>1</exif:Mode></rdf:Description></exif:Flash>
890 * <exif:Flash rdf:parseType='Resource'> <exif:Fired>True</exif:Fired>
891 * <exif:Mode>1</exif:Mode></exif:Flash>
893 * @param $ns String namespace
894 * @param $tag String tag name (no ns)
895 * @param $attribs Array array of attribs w/ values.
897 private function startElementModeStruct( $ns, $tag, $attribs ) {
898 if ( $ns !== self
::NS_RDF
) {
900 if ( isset( $this->items
[$ns][$tag] ) ) {
901 if ( isset( $this->items
[$ns][$this->ancestorStruct
]['children'] )
902 && !isset( $this->items
[$ns][$this->ancestorStruct
]['children'][$tag] ) )
904 // This assumes that we don't have inter-namespace nesting
905 // which we don't in all the properties we're interested in.
906 throw new MWException( " <$tag> appeared nested in <" . $this->ancestorStruct
907 . "> where it is not allowed." );
909 array_unshift( $this->mode
, $this->items
[$ns][$tag]['mode'] );
910 array_unshift( $this->curItem
, $ns . ' ' . $tag );
911 if ( $this->charContent
!== false ) {
913 // Should not happen in valid XMP.
914 throw new MWException( "tag <$tag> nested in non-whitespace characters (" . $this->charContent
. ")." );
917 array_unshift( $this->mode
, self
::MODE_IGNORE
);
918 array_unshift( $this->curItem
, $elm );
924 if ( $ns === self
::NS_RDF
&& $tag === 'Description' ) {
925 $this->doAttribs( $attribs );
926 array_unshift( $this->mode
, self
::MODE_STRUCT
);
927 array_unshift( $this->curItem
, $this->curItem
[0] );
932 * opening element in MODE_LI
933 * process elements of arrays.
936 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
937 * </rdf:Seq> </exif:ISOSpeedRatings>
938 * This method is called when we hit the <rdf:li> element.
940 * @param $elm String: namespace . ' ' . tagname
941 * @param $attribs Array: Attributes. (needed for BAGSTRUCTS)
942 * @throws MWException if gets a tag other than <rdf:li>
944 private function startElementModeLi( $elm, $attribs ) {
945 if ( ( $elm ) !== self
::NS_RDF
. ' li' ) {
946 throw new MWException( "<rdf:li> expected but got $elm." );
949 if ( !isset( $this->mode
[1] ) ) {
950 // This should never ever ever happen. Checking for it
952 throw new MWException( 'In mode Li, but no 2xPrevious mode!' );
955 if ( $this->mode
[1] === self
::MODE_BAGSTRUCT
) {
956 // This list item contains a compound (STRUCT) value.
957 array_unshift( $this->mode
, self
::MODE_STRUCT
);
958 array_unshift( $this->curItem
, $elm );
959 $this->processingArray
= true;
961 if ( !isset( $this->curItem
[1] ) ) {
963 throw new MWException( 'Can not find parent of BAGSTRUCT.' );
965 list( $curNS, $curTag ) = explode( ' ', $this->curItem
[1] );
966 $this->ancestorStruct
= isset( $this->items
[$curNS][$curTag]['map_name'] )
967 ?
$this->items
[$curNS][$curTag]['map_name'] : $curTag;
969 $this->doAttribs( $attribs );
972 // Normal BAG or SEQ containing simple values.
973 array_unshift( $this->mode
, self
::MODE_SIMPLE
);
974 // need to add curItem[0] on again since one is for the specific item
975 // and one is for the entire group.
976 array_unshift( $this->curItem
, $this->curItem
[0] );
977 $this->processingArray
= true;
983 * Opening element in MODE_LI_LANG.
984 * process elements of language alternatives
987 * <dc:title> <rdf:Alt> <rdf:li xml:lang="x-default">My house
988 * </rdf:li> </rdf:Alt> </dc:title>
990 * This method is called when we hit the <rdf:li> element.
992 * @param $elm String namespace . ' ' . tag
993 * @param $attribs array array of elements (most importantly xml:lang)
994 * @throws MWException if gets a tag other than <rdf:li> or if no xml:lang
996 private function startElementModeLiLang( $elm, $attribs ) {
997 if ( $elm !== self
::NS_RDF
. ' li' ) {
998 throw new MWException( __METHOD__
. " <rdf:li> expected but got $elm." );
1000 if ( !isset( $attribs[ self
::NS_XML
. ' lang'] )
1001 ||
!preg_match( '/^[-A-Za-z0-9]{2,}$/D', $attribs[ self
::NS_XML
. ' lang' ] ) )
1003 throw new MWException( __METHOD__
1004 . " <rdf:li> did not contain, or has invalid xml:lang attribute in lang alternative" );
1007 // Lang is case-insensitive.
1008 $this->itemLang
= strtolower( $attribs[ self
::NS_XML
. ' lang' ] );
1010 // need to add curItem[0] on again since one is for the specific item
1011 // and one is for the entire group.
1012 array_unshift( $this->curItem
, $this->curItem
[0] );
1013 array_unshift( $this->mode
, self
::MODE_SIMPLE
);
1014 $this->processingArray
= true;
1018 * Hits an opening element.
1019 * Generally just calls a helper based on what MODE we're in.
1020 * Also does some initial set up for the wrapper element
1022 * @param $parser XMLParser
1023 * @param $elm String namespace "<space>" element
1024 * @param $attribs Array attribute name => value
1026 function startElement( $parser, $elm, $attribs ) {
1028 if ( $elm === self
::NS_RDF
. ' RDF'
1029 ||
$elm === 'adobe:ns:meta/ xmpmeta'
1030 ||
$elm === 'adobe:ns:meta/ xapmeta')
1034 } elseif ( $elm === self
::NS_RDF
. ' Description' ) {
1035 if ( count( $this->mode
) === 0 ) {
1037 array_unshift( $this->mode
, self
::MODE_INITIAL
);
1039 } elseif ( $elm === self
::NS_RDF
. ' type' ) {
1040 // This doesn't support rdf:type properly.
1041 // In practise I have yet to see a file that
1042 // uses this element, however it is mentioned
1043 // on page 25 of part 1 of the xmp standard.
1045 // also it seems as if exiv2 and exiftool do not support
1046 // this either (That or I misunderstand the standard)
1047 wfDebugLog( 'XMP', __METHOD__
. ' Encountered <rdf:type> which isn\'t currently supported' );
1050 if ( strpos( $elm, ' ' ) === false ) {
1051 // This probably shouldn't happen.
1052 wfDebugLog( 'XMP', __METHOD__
. " Encountered <$elm> which has no namespace. Skipping." );
1056 list( $ns, $tag ) = explode( ' ', $elm, 2 );
1058 if ( count( $this->mode
) === 0 ) {
1059 // This should not happen.
1060 throw new MWException('Error extracting XMP, '
1061 . "encountered <$elm> with no mode" );
1064 switch( $this->mode
[0] ) {
1065 case self
::MODE_IGNORE
:
1066 $this->startElementModeIgnore( $elm );
1068 case self
::MODE_SIMPLE
:
1069 $this->startElementModeSimple( $elm, $attribs );
1071 case self
::MODE_INITIAL
:
1072 $this->startElementModeInitial( $ns, $tag, $attribs );
1074 case self
::MODE_STRUCT
:
1075 $this->startElementModeStruct( $ns, $tag, $attribs );
1077 case self
::MODE_BAG
:
1078 case self
::MODE_BAGSTRUCT
:
1079 $this->startElementModeBag( $elm );
1081 case self
::MODE_SEQ
:
1082 $this->startElementModeSeq( $elm );
1084 case self
::MODE_LANG
:
1085 $this->startElementModeLang( $elm );
1087 case self
::MODE_LI_LANG
:
1088 $this->startElementModeLiLang( $elm, $attribs );
1091 $this->startElementModeLi( $elm, $attribs );
1093 case self
::MODE_QDESC
:
1094 $this->startElementModeQDesc( $elm );
1097 throw new MWException( 'StartElement in unknown mode: ' . $this->mode
[0] );
1103 * Process attributes.
1104 * Simple values can be stored as either a tag or attribute
1106 * Often the initial "<rdf:Description>" tag just has all the simple
1107 * properties as attributes.
1111 * <rdf:Description rdf:about="" xmlns:exif="http://ns.adobe.com/exif/1.0/" exif:DigitalZoomRatio="0/10">
1114 * @param $attribs Array attribute=>value array.
1116 private function doAttribs( $attribs ) {
1118 // first check for rdf:parseType attribute, as that can change
1119 // how the attributes are interperted.
1121 if ( isset( $attribs[self
::NS_RDF
. ' parseType'] )
1122 && $attribs[self
::NS_RDF
. ' parseType'] === 'Resource'
1123 && $this->mode
[0] === self
::MODE_SIMPLE
)
1125 // this is equivalent to having an inner rdf:Description
1126 $this->mode
[0] = self
::MODE_QDESC
;
1128 foreach ( $attribs as $name => $val ) {
1131 if ( strpos( $name, ' ' ) === false ) {
1132 // This shouldn't happen, but so far some old software forgets namespace
1134 wfDebugLog( 'XMP', __METHOD__
. ' Encountered non-namespaced attribute: '
1135 . " $name=\"$val\". Skipping. " );
1138 list( $ns, $tag ) = explode( ' ', $name, 2 );
1139 if ( $ns === self
::NS_RDF
) {
1140 if ( $tag === 'value' ||
$tag === 'resource' ) {
1141 // resource is for url.
1142 // value attribute is a weird way of just putting the contents.
1143 $this->char( $this->xmlParser
, $val );
1145 } elseif ( isset( $this->items
[$ns][$tag] ) ) {
1146 if ( $this->mode
[0] === self
::MODE_SIMPLE
) {
1147 throw new MWException( __METHOD__
1148 . " $ns:$tag found as attribute where not allowed" );
1150 $this->saveValue( $ns, $tag, $val );
1152 wfDebugLog( 'XMP', __METHOD__
. " Ignoring unrecognized element <$ns:$tag>." );
1158 * Given an extracted value, save it to results array
1160 * note also uses $this->ancestorStruct and
1161 * $this->processingArray to determine what name to
1162 * save the value under. (in addition to $tag).
1164 * @param $ns String namespace of tag this is for
1165 * @param $tag String tag name
1166 * @param $val String value to save
1168 private function saveValue( $ns, $tag, $val ) {
1170 $info =& $this->items
[$ns][$tag];
1171 $finalName = isset( $info['map_name'] )
1172 ?
$info['map_name'] : $tag;
1173 if ( isset( $info['validate'] ) ) {
1174 $validate = is_array( $info['validate'] ) ?
$info['validate']
1175 : array( 'XMPValidate', $info['validate'] );
1177 if ( is_callable( $validate ) ) {
1178 call_user_func_array( $validate, array( $info, &$val, true ) );
1179 // the reasoning behind using &$val instead of using the return value
1180 // is to be consistent between here and validating structures.
1181 if ( is_null( $val ) ) {
1182 wfDebugLog( 'XMP', __METHOD__
. " <$ns:$tag> failed validation." );
1186 wfDebugLog( 'XMP', __METHOD__
. " Validation function for $finalName ("
1187 . $validate[0] . '::' . $validate[1] . '()) is not callable.' );
1191 if ( $this->ancestorStruct
&& $this->processingArray
) {
1192 // Aka both an array and a struct. ( self::MODE_BAGSTRUCT )
1193 $this->results
['xmp-' . $info['map_group']][$this->ancestorStruct
][][$finalName] = $val;
1194 } elseif ( $this->ancestorStruct
) {
1195 $this->results
['xmp-' . $info['map_group']][$this->ancestorStruct
][$finalName] = $val;
1196 } elseif ( $this->processingArray
) {
1197 if ( $this->itemLang
=== false ) {
1199 $this->results
['xmp-' . $info['map_group']][$finalName][] = $val;
1202 $this->results
['xmp-' . $info['map_group']][$finalName][$this->itemLang
] = $val;
1205 $this->results
['xmp-' . $info['map_group']][$finalName] = $val;