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 FormatMetadata accepts.
28 * Note, this is not meant to recognize every possible thing you can
29 * encode in XMP. It should recognize all the properties we want.
30 * For example it doesn't have support for structures with multiple
31 * nesting levels, as none of the properties we're supporting use that
32 * feature. If it comes across properties it doesn't recognize, it should
35 * The public methods one would call in this class are
37 * Reads in xmp content.
38 * Can potentially be called multiple times with partial data each time.
39 * - parseExtended( $content )
40 * Reads XMPExtended blocks (jpeg files only).
42 * Outputs a results array.
44 * Note XMP kind of looks like rdf. They are not the same thing - XMP is
45 * encoded as a specific subset of rdf. This class can read XMP. It cannot
50 /** @var array XMP item configuration array */
53 /** @var array Array to hold the current element (and previous element, and so on) */
54 private $curItem = array();
56 /** @var bool|string The structure name when processing nested structures. */
57 private $ancestorStruct = false;
59 /** @var bool|string Temporary holder for character data that appears in xmp doc. */
60 private $charContent = false;
62 /** @var array Stores the state the xmpreader is in (see MODE_FOO constants) */
63 private $mode = array();
65 /** @var array Array to hold results */
66 private $results = array();
68 /** @var bool If we're doing a seq or bag. */
69 private $processingArray = false;
71 /** @var bool|string Used for lang alts only */
72 private $itemLang = false;
74 /** @var resource A resource handle for the XML parser */
77 /** @var bool|string Character set like 'UTF-8' */
78 private $charset = false;
81 private $extendedXMPOffset = 0;
83 /** @var int Flag determining if the XMP is safe to parse **/
84 private $parsable = 0;
86 /** @var string Buffer of XML to parse **/
87 private $xmlParsableBuffer = '';
90 * These are various mode constants.
91 * they are used to figure out what to do
92 * with an element when its encountered.
94 * For example, MODE_IGNORE is used when processing
95 * a property we're not interested in. So if a new
96 * element pops up when we're in that mode, we ignore it.
98 const MODE_INITIAL
= 0;
99 const MODE_IGNORE
= 1;
101 const MODE_LI_LANG
= 3;
102 const MODE_QDESC
= 4;
104 // The following MODE constants are also used in the
105 // $items array to denote what type of property the item is.
106 const MODE_SIMPLE
= 10;
107 const MODE_STRUCT
= 11; // structure (associative array)
108 const MODE_SEQ
= 12; // ordered list
109 const MODE_BAG
= 13; // unordered list
110 const MODE_LANG
= 14;
111 const MODE_ALT
= 15; // non-language alt. Currently not implemented, and not needed atm.
112 const MODE_BAGSTRUCT
= 16; // A BAG of Structs.
114 const NS_RDF
= 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
115 const NS_XML
= 'http://www.w3.org/XML/1998/namespace';
117 // States used while determining if XML is safe to parse
118 const PARSABLE_UNKNOWN
= 0;
119 const PARSABLE_OK
= 1;
120 const PARSABLE_BUFFERING
= 2;
121 const PARSABLE_NO
= 3;
126 * Primary job is to initialize the XMLParser
128 function __construct() {
130 if ( !function_exists( 'xml_parser_create_ns' ) ) {
131 // this should already be checked by this point
132 throw new RuntimeException( 'XMP support requires XML Parser' );
135 $this->items
= XMPInfo
::getItems();
137 $this->resetXMLParser();
141 * Main use is if a single item has multiple xmp documents describing it.
142 * For example in jpeg's with extendedXMP
144 private function resetXMLParser() {
146 if ( $this->xmlParser
) {
148 xml_parser_free( $this->xmlParser
);
151 $this->xmlParser
= xml_parser_create_ns( 'UTF-8', ' ' );
152 xml_parser_set_option( $this->xmlParser
, XML_OPTION_CASE_FOLDING
, 0 );
153 xml_parser_set_option( $this->xmlParser
, XML_OPTION_SKIP_WHITE
, 1 );
155 xml_set_element_handler( $this->xmlParser
,
156 array( $this, 'startElement' ),
157 array( $this, 'endElement' ) );
159 xml_set_character_data_handler( $this->xmlParser
, array( $this, 'char' ) );
161 $this->parsable
= self
::PARSABLE_UNKNOWN
;
162 $this->xmlParsableBuffer
= '';
165 /** Destroy the xml parser
167 * Not sure if this is actually needed.
169 function __destruct() {
170 // not sure if this is needed.
171 xml_parser_free( $this->xmlParser
);
175 * Check if this instance supports using this class
177 public static function isSupported() {
178 return function_exists( 'xml_parser_create_ns' ) && class_exists( 'XMLReader' );
181 /** Get the result array. Do some post-processing before returning
182 * the array, and transform any metadata that is special-cased.
184 * @return array Array of results as an array of arrays suitable for
185 * FormatMetadata::getFormattedData().
187 public function getResults() {
188 // xmp-special is for metadata that affects how stuff
189 // is extracted. For example xmpNote:HasExtendedXMP.
191 // It is also used to handle photoshop:AuthorsPosition
192 // which is weird and really part of another property,
193 // see 2:85 in IPTC. See also pg 21 of IPTC4XMP standard.
194 // The location fields also use it.
196 $data = $this->results
;
198 if ( isset( $data['xmp-special']['AuthorsPosition'] )
199 && is_string( $data['xmp-special']['AuthorsPosition'] )
200 && isset( $data['xmp-general']['Artist'][0] )
202 // Note, if there is more than one creator,
203 // this only applies to first. This also will
204 // only apply to the dc:Creator prop, not the
207 $data['xmp-general']['Artist'][0] =
208 $data['xmp-special']['AuthorsPosition'] . ', '
209 . $data['xmp-general']['Artist'][0];
212 // Go through the LocationShown and LocationCreated
213 // changing it to the non-hierarchal form used by
214 // the other location fields.
216 if ( isset( $data['xmp-special']['LocationShown'][0] )
217 && is_array( $data['xmp-special']['LocationShown'][0] )
219 // the is_array is just paranoia. It should always
221 foreach ( $data['xmp-special']['LocationShown'] as $loc ) {
222 if ( !is_array( $loc ) ) {
223 // To avoid copying over the _type meta-fields.
226 foreach ( $loc as $field => $val ) {
227 $data['xmp-general'][$field . 'Dest'][] = $val;
231 if ( isset( $data['xmp-special']['LocationCreated'][0] )
232 && is_array( $data['xmp-special']['LocationCreated'][0] )
234 // the is_array is just paranoia. It should always
236 foreach ( $data['xmp-special']['LocationCreated'] as $loc ) {
237 if ( !is_array( $loc ) ) {
238 // To avoid copying over the _type meta-fields.
241 foreach ( $loc as $field => $val ) {
242 $data['xmp-general'][$field . 'Created'][] = $val;
247 // We don't want to return the special values, since they're
248 // special and not info to be stored about the file.
249 unset( $data['xmp-special'] );
251 // Convert GPSAltitude to negative if below sea level.
252 if ( isset( $data['xmp-exif']['GPSAltitudeRef'] )
253 && isset( $data['xmp-exif']['GPSAltitude'] )
256 // Must convert to a real before multiplying by -1
257 // XMPValidate guarantees there will always be a '/' in this value.
258 list( $nom, $denom ) = explode( '/', $data['xmp-exif']['GPSAltitude'] );
259 $data['xmp-exif']['GPSAltitude'] = $nom / $denom;
261 if ( $data['xmp-exif']['GPSAltitudeRef'] == '1' ) {
262 $data['xmp-exif']['GPSAltitude'] *= -1;
264 unset( $data['xmp-exif']['GPSAltitudeRef'] );
271 * Main function to call to parse XMP. Use getResults to
274 * Also catches any errors during processing, writes them to
275 * debug log, blanks result array and returns false.
277 * @param string $content XMP data
278 * @param bool $allOfIt If this is all the data (true) or if its split up (false). Default true
279 * @param bool $reset Does xml parser need to be reset. Default false
280 * @throws RuntimeException
281 * @return bool Success.
283 public function parse( $content, $allOfIt = true, $reset = false ) {
285 $this->resetXMLParser();
289 // detect encoding by looking for BOM which is supposed to be in processing instruction.
290 // see page 12 of http://www.adobe.com/devnet/xmp/pdfs/XMPSpecificationPart3.pdf
291 if ( !$this->charset
) {
293 if ( preg_match( '/\xEF\xBB\xBF|\xFE\xFF|\x00\x00\xFE\xFF|\xFF\xFE\x00\x00|\xFF\xFE/',
298 $this->charset
= 'UTF-16BE';
301 $this->charset
= 'UTF-16LE';
303 case "\x00\x00\xFE\xFF":
304 $this->charset
= 'UTF-32BE';
306 case "\xFF\xFE\x00\x00":
307 $this->charset
= 'UTF-32LE';
310 $this->charset
= 'UTF-8';
313 //this should be impossible to get to
314 throw new RuntimeException( "Invalid BOM" );
317 // standard specifically says, if no bom assume utf-8
318 $this->charset
= 'UTF-8';
321 if ( $this->charset
!== 'UTF-8' ) {
322 //don't convert if already utf-8
323 wfSuppressWarnings();
324 $content = iconv( $this->charset
, 'UTF-8//IGNORE', $content );
328 // Ensure the XMP block does not have an xml doctype declaration, which
329 // could declare entities unsafe to parse with xml_parse (T85848/T71210).
330 if ( $this->parsable
!== self
::PARSABLE_OK
) {
331 if ( $this->parsable
=== self
::PARSABLE_NO
) {
332 throw new Exception( 'Unsafe doctype declaration in XML.' );
335 $content = $this->xmlParsableBuffer
. $content;
336 if ( !$this->checkParseSafety( $content ) ) {
337 if ( !$allOfIt && $this->parsable
!== self
::PARSABLE_NO
) {
338 // parse wasn't Unsuccessful yet, so return true
342 $msg = ( $this->parsable
=== self
::PARSABLE_NO
) ?
343 'Unsafe doctype declaration in XML.' :
344 'No root element found in XML.';
345 throw new Exception( $msg );
349 $ok = xml_parse( $this->xmlParser
, $content, $allOfIt );
351 $error = xml_error_string( xml_get_error_code( $this->xmlParser
) );
352 $where = 'line: ' . xml_get_current_line_number( $this->xmlParser
)
353 . ' column: ' . xml_get_current_column_number( $this->xmlParser
)
354 . ' byte offset: ' . xml_get_current_byte_index( $this->xmlParser
);
356 wfDebugLog( 'XMP', "XMPReader::parse : Error reading XMP content: $error ($where)" );
357 $this->results
= array(); // blank if error.
360 } catch ( Exception
$e ) {
361 wfDebugLog( 'XMP', 'XMP parse error: ' . $e );
362 $this->results
= array();
370 /** Entry point for XMPExtended blocks in jpeg files
372 * @todo In serious need of testing
373 * @see http://www.adobe.ge/devnet/xmp/pdfs/XMPSpecificationPart3.pdf XMP spec part 3 page 20
374 * @param string $content XMPExtended block minus the namespace signature
375 * @return bool If it succeeded.
377 public function parseExtended( $content ) {
378 // @todo FIXME: This is untested. Hard to find example files
379 // or programs that make such files..
380 $guid = substr( $content, 0, 32 );
381 if ( !isset( $this->results
['xmp-special']['HasExtendedXMP'] )
382 ||
$this->results
['xmp-special']['HasExtendedXMP'] !== $guid
384 wfDebugLog( 'XMP', __METHOD__
.
385 " Ignoring XMPExtended block due to wrong guid (guid= '$guid')" );
389 $len = unpack( 'Nlength/Noffset', substr( $content, 32, 8 ) );
391 if ( !$len ||
$len['length'] < 4 ||
$len['offset'] < 0 ||
$len['offset'] > $len['length'] ) {
392 wfDebugLog( 'XMP', __METHOD__
. 'Error reading extended XMP block, invalid length or offset.' );
397 // we're not very robust here. we should accept it in the wrong order.
398 // To quote the XMP standard:
399 // "A JPEG writer should write the ExtendedXMP marker segments in order,
400 // immediately following the StandardXMP. However, the JPEG standard
401 // does not require preservation of marker segment order. A robust JPEG
402 // reader should tolerate the marker segments in any order."
404 // otoh the probability that an image will have more than 128k of
405 // metadata is rather low... so the probability that it will have
406 // > 128k, and be in the wrong order is very low...
408 if ( $len['offset'] !== $this->extendedXMPOffset
) {
409 wfDebugLog( 'XMP', __METHOD__
. 'Ignoring XMPExtended block due to wrong order. (Offset was '
410 . $len['offset'] . ' but expected ' . $this->extendedXMPOffset
. ')' );
415 if ( $len['offset'] === 0 ) {
416 // if we're starting the extended block, we've probably already
417 // done the XMPStandard block, so reset.
418 $this->resetXMLParser();
421 $this->extendedXMPOffset +
= $len['length'];
423 $actualContent = substr( $content, 40 );
425 if ( $this->extendedXMPOffset
=== strlen( $actualContent ) ) {
431 wfDebugLog( 'XMP', __METHOD__
. 'Parsing a XMPExtended block' );
433 return $this->parse( $actualContent, $atEnd );
437 * Character data handler
438 * Called whenever character data is found in the xmp document.
440 * does nothing if we're in MODE_IGNORE or if the data is whitespace
441 * throws an error if we're not in MODE_SIMPLE (as we're not allowed to have character
442 * data in the other modes).
444 * As an example, this happens when we encounter XMP like:
445 * <exif:DigitalZoomRatio>0/10</exif:DigitalZoomRatio>
446 * and are processing the 0/10 bit.
448 * @param XMLParser $parser XMLParser reference to the xml parser
449 * @param string $data Character data
450 * @throws RuntimeException On invalid data
452 function char( $parser, $data ) {
454 $data = trim( $data );
455 if ( trim( $data ) === "" ) {
459 if ( !isset( $this->mode
[0] ) ) {
460 throw new RuntimeException( 'Unexpected character data before first rdf:Description element' );
463 if ( $this->mode
[0] === self
::MODE_IGNORE
) {
467 if ( $this->mode
[0] !== self
::MODE_SIMPLE
468 && $this->mode
[0] !== self
::MODE_QDESC
470 throw new RuntimeException( 'character data where not expected. (mode ' . $this->mode
[0] . ')' );
473 // to check, how does this handle w.s.
474 if ( $this->charContent
=== false ) {
475 $this->charContent
= $data;
477 $this->charContent
.= $data;
482 * Check if a block of XML is safe to pass to xml_parse, i.e. doesn't
483 * contain a doctype declaration which could contain a dos attack if we
484 * parse it and expand internal entities (T85848).
486 * @param string $content xml string to check for parse safety
487 * @return bool true if the xml is safe to parse, false otherwise
489 private function checkParseSafety( $content ) {
490 $reader = new XMLReader();
493 // For XMLReader to parse incomplete/invalid XML, it has to be open()'ed
494 // instead of using XML().
496 'data://text/plain,' . urlencode( $content ),
498 LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_NONET
501 $oldDisable = libxml_disable_entity_loader( true );
502 $reset = new ScopedCallback(
503 'libxml_disable_entity_loader',
506 $reader->setParserProperty( XMLReader
::SUBST_ENTITIES
, false );
508 // Even with LIBXML_NOWARNING set, XMLReader::read gives a warning
509 // when parsing truncated XML, which causes unit tests to fail.
510 wfSuppressWarnings();
511 while ( $reader->read() ) {
512 if ( $reader->nodeType
=== XMLReader
::ELEMENT
) {
513 // Reached the first element without hitting a doctype declaration
514 $this->parsable
= self
::PARSABLE_OK
;
518 if ( $reader->nodeType
=== XMLReader
::DOC_TYPE
) {
519 $this->parsable
= self
::PARSABLE_NO
;
526 if ( !is_null( $result ) ) {
530 // Reached the end of the parsable xml without finding an element
531 // or doctype. Buffer and try again.
532 $this->parsable
= self
::PARSABLE_BUFFERING
;
533 $this->xmlParsableBuffer
= $content;
537 /** When we hit a closing element in MODE_IGNORE
538 * Check to see if this is the element we started to ignore,
539 * in which case we get out of MODE_IGNORE
541 * @param string $elm Namespace of element followed by a space and then tag name of element.
543 private function endElementModeIgnore( $elm ) {
544 if ( $this->curItem
[0] === $elm ) {
545 array_shift( $this->curItem
);
546 array_shift( $this->mode
);
551 * Hit a closing element when in MODE_SIMPLE.
552 * This generally means that we finished processing a
553 * property value, and now have to save the result to the
556 * For example, when processing:
557 * <exif:DigitalZoomRatio>0/10</exif:DigitalZoomRatio>
558 * this deals with when we hit </exif:DigitalZoomRatio>.
560 * Or it could be if we hit the end element of a property
561 * of a compound data structure (like a member of an array).
563 * @param string $elm Namespace, space, and tag name.
565 private function endElementModeSimple( $elm ) {
566 if ( $this->charContent
!== false ) {
567 if ( $this->processingArray
) {
568 // if we're processing an array, use the original element
569 // name instead of rdf:li.
570 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
572 list( $ns, $tag ) = explode( ' ', $elm, 2 );
574 $this->saveValue( $ns, $tag, $this->charContent
);
576 $this->charContent
= false; // reset
578 array_shift( $this->curItem
);
579 array_shift( $this->mode
);
583 * Hit a closing element in MODE_STRUCT, MODE_SEQ, MODE_BAG
584 * generally means we've finished processing a nested structure.
585 * resets some internal variables to indicate that.
587 * Note this means we hit the closing element not the "</rdf:Seq>".
589 * @par For example, when processing:
591 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
592 * </rdf:Seq> </exif:ISOSpeedRatings>
595 * This method is called when we hit the "</exif:ISOSpeedRatings>" tag.
597 * @param string $elm Namespace . space . tag name.
598 * @throws RuntimeException
600 private function endElementNested( $elm ) {
602 /* cur item must be the same as $elm, unless if in MODE_STRUCT
603 in which case it could also be rdf:Description */
604 if ( $this->curItem
[0] !== $elm
605 && !( $elm === self
::NS_RDF
. ' Description'
606 && $this->mode
[0] === self
::MODE_STRUCT
)
608 throw new RuntimeException( "nesting mismatch. got a </$elm> but expected a </" .
609 $this->curItem
[0] . '>' );
612 // Validate structures.
613 list( $ns, $tag ) = explode( ' ', $elm, 2 );
614 if ( isset( $this->items
[$ns][$tag]['validate'] ) ) {
616 $info =& $this->items
[$ns][$tag];
617 $finalName = isset( $info['map_name'] )
618 ?
$info['map_name'] : $tag;
620 $validate = is_array( $info['validate'] ) ?
$info['validate']
621 : array( 'XMPValidate', $info['validate'] );
623 if ( !isset( $this->results
['xmp-' . $info['map_group']][$finalName] ) ) {
624 // This can happen if all the members of the struct failed validation.
625 wfDebugLog( 'XMP', __METHOD__
. " <$ns:$tag> has no valid members." );
626 } elseif ( is_callable( $validate ) ) {
627 $val =& $this->results
['xmp-' . $info['map_group']][$finalName];
628 call_user_func_array( $validate, array( $info, &$val, false ) );
629 if ( is_null( $val ) ) {
630 // the idea being the validation function will unset the variable if
632 wfDebugLog( 'XMP', __METHOD__
. " <$ns:$tag> failed validation." );
633 unset( $this->results
['xmp-' . $info['map_group']][$finalName] );
636 wfDebugLog( 'XMP', __METHOD__
. " Validation function for $finalName ("
637 . $validate[0] . '::' . $validate[1] . '()) is not callable.' );
641 array_shift( $this->curItem
);
642 array_shift( $this->mode
);
643 $this->ancestorStruct
= false;
644 $this->processingArray
= false;
645 $this->itemLang
= false;
649 * Hit a closing element in MODE_LI (either rdf:Seq, or rdf:Bag )
650 * Add information about what type of element this is.
652 * Note we still have to hit the outer "</property>"
654 * @par For example, when processing:
656 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
657 * </rdf:Seq> </exif:ISOSpeedRatings>
660 * This method is called when we hit the "</rdf:Seq>".
661 * (For comparison, we call endElementModeSimple when we
662 * hit the "</rdf:li>")
664 * @param string $elm Namespace . ' ' . element name
665 * @throws RuntimeException
667 private function endElementModeLi( $elm ) {
669 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
670 $info = $this->items
[$ns][$tag];
671 $finalName = isset( $info['map_name'] )
672 ?
$info['map_name'] : $tag;
674 array_shift( $this->mode
);
676 if ( !isset( $this->results
['xmp-' . $info['map_group']][$finalName] ) ) {
677 wfDebugLog( 'XMP', __METHOD__
. " Empty compund element $finalName." );
682 if ( $elm === self
::NS_RDF
. ' Seq' ) {
683 $this->results
['xmp-' . $info['map_group']][$finalName]['_type'] = 'ol';
684 } elseif ( $elm === self
::NS_RDF
. ' Bag' ) {
685 $this->results
['xmp-' . $info['map_group']][$finalName]['_type'] = 'ul';
686 } elseif ( $elm === self
::NS_RDF
. ' Alt' ) {
687 // extra if needed as you could theoretically have a non-language alt.
688 if ( $info['mode'] === self
::MODE_LANG
) {
689 $this->results
['xmp-' . $info['map_group']][$finalName]['_type'] = 'lang';
692 throw new RuntimeException( __METHOD__
. " expected </rdf:seq> or </rdf:bag> but instead got $elm." );
697 * End element while in MODE_QDESC
698 * mostly when ending an element when we have a simple value
699 * that has qualifiers.
701 * Qualifiers aren't all that common, and we don't do anything
704 * @param string $elm Namespace and element
706 private function endElementModeQDesc( $elm ) {
708 if ( $elm === self
::NS_RDF
. ' value' ) {
709 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
710 $this->saveValue( $ns, $tag, $this->charContent
);
714 array_shift( $this->mode
);
715 array_shift( $this->curItem
);
720 * Handler for hitting a closing element.
722 * generally just calls a helper function depending on what
725 * Ignores the outer wrapping elements that are optional in
726 * xmp and have no meaning.
728 * @param XMLParser $parser
729 * @param string $elm Namespace . ' ' . element name
730 * @throws RuntimeException
732 function endElement( $parser, $elm ) {
733 if ( $elm === ( self
::NS_RDF
. ' RDF' )
734 ||
$elm === 'adobe:ns:meta/ xmpmeta'
735 ||
$elm === 'adobe:ns:meta/ xapmeta'
741 if ( $elm === self
::NS_RDF
. ' type' ) {
742 // these aren't really supported properly yet.
743 // However, it appears they almost never used.
744 wfDebugLog( 'XMP', __METHOD__
. ' encountered <rdf:type>' );
747 if ( strpos( $elm, ' ' ) === false ) {
748 // This probably shouldn't happen.
749 // However, there is a bug in an adobe product
750 // that forgets the namespace on some things.
751 // (Luckily they are unimportant things).
752 wfDebugLog( 'XMP', __METHOD__
. " Encountered </$elm> which has no namespace. Skipping." );
757 if ( count( $this->mode
[0] ) === 0 ) {
758 // This should never ever happen and means
759 // there is a pretty major bug in this class.
760 throw new RuntimeException( 'Encountered end element with no mode' );
763 if ( count( $this->curItem
) == 0 && $this->mode
[0] !== self
::MODE_INITIAL
) {
764 // just to be paranoid. Should always have a curItem, except for initially
765 // (aka during MODE_INITAL).
766 throw new RuntimeException( "Hit end element </$elm> but no curItem" );
769 switch ( $this->mode
[0] ) {
770 case self
::MODE_IGNORE
:
771 $this->endElementModeIgnore( $elm );
773 case self
::MODE_SIMPLE
:
774 $this->endElementModeSimple( $elm );
776 case self
::MODE_STRUCT
:
779 case self
::MODE_LANG
:
780 case self
::MODE_BAGSTRUCT
:
781 $this->endElementNested( $elm );
783 case self
::MODE_INITIAL
:
784 if ( $elm === self
::NS_RDF
. ' Description' ) {
785 array_shift( $this->mode
);
787 throw new RuntimeException( 'Element ended unexpectedly while in MODE_INITIAL' );
791 case self
::MODE_LI_LANG
:
792 $this->endElementModeLi( $elm );
794 case self
::MODE_QDESC
:
795 $this->endElementModeQDesc( $elm );
798 wfDebugLog( 'XMP', __METHOD__
. " no mode (elm = $elm)" );
804 * Hit an opening element while in MODE_IGNORE
806 * XMP is extensible, so ignore any tag we don't understand.
808 * Mostly ignores, unless we encounter the element that we are ignoring.
809 * in which case we add it to the item stack, so we can ignore things
810 * that are nested, correctly.
812 * @param string $elm Namespace . ' ' . tag name
814 private function startElementModeIgnore( $elm ) {
815 if ( $elm === $this->curItem
[0] ) {
816 array_unshift( $this->curItem
, $elm );
817 array_unshift( $this->mode
, self
::MODE_IGNORE
);
822 * Start element in MODE_BAG (unordered array)
823 * this should always be <rdf:Bag>
825 * @param string $elm Namespace . ' ' . tag
826 * @throws RuntimeException If we have an element that's not <rdf:Bag>
828 private function startElementModeBag( $elm ) {
829 if ( $elm === self
::NS_RDF
. ' Bag' ) {
830 array_unshift( $this->mode
, self
::MODE_LI
);
832 throw new RuntimeException( "Expected <rdf:Bag> but got $elm." );
837 * Start element in MODE_SEQ (ordered array)
838 * this should always be <rdf:Seq>
840 * @param string $elm Namespace . ' ' . tag
841 * @throws RuntimeException If we have an element that's not <rdf:Seq>
843 private function startElementModeSeq( $elm ) {
844 if ( $elm === self
::NS_RDF
. ' Seq' ) {
845 array_unshift( $this->mode
, self
::MODE_LI
);
846 } elseif ( $elm === self
::NS_RDF
. ' Bag' ) {
848 wfDebugLog( 'XMP', __METHOD__
. ' Expected an rdf:Seq, but got an rdf:Bag. Pretending'
849 . ' it is a Seq, since some buggy software is known to screw this up.' );
850 array_unshift( $this->mode
, self
::MODE_LI
);
852 throw new RuntimeException( "Expected <rdf:Seq> but got $elm." );
857 * Start element in MODE_LANG (language alternative)
858 * this should always be <rdf:Alt>
860 * This tag tends to be used for metadata like describe this
861 * picture, which can be translated into multiple languages.
863 * XMP supports non-linguistic alternative selections,
864 * which are really only used for thumbnails, which
865 * we don't care about.
867 * @param string $elm Namespace . ' ' . tag
868 * @throws RuntimeException If we have an element that's not <rdf:Alt>
870 private function startElementModeLang( $elm ) {
871 if ( $elm === self
::NS_RDF
. ' Alt' ) {
872 array_unshift( $this->mode
, self
::MODE_LI_LANG
);
874 throw new RuntimeException( "Expected <rdf:Seq> but got $elm." );
879 * Handle an opening element when in MODE_SIMPLE
881 * This should not happen often. This is for if a simple element
882 * already opened has a child element. Could happen for a
886 * <exif:DigitalZoomRatio><rdf:Description><rdf:value>0/10</rdf:value>
887 * <foo:someQualifier>Bar</foo:someQualifier> </rdf:Description>
888 * </exif:DigitalZoomRatio>
890 * This method is called when processing the <rdf:Description> element
892 * @param string $elm Namespace and tag names separated by space.
893 * @param array $attribs Attributes of the element.
894 * @throws RuntimeException
896 private function startElementModeSimple( $elm, $attribs ) {
897 if ( $elm === self
::NS_RDF
. ' Description' ) {
898 // If this value has qualifiers
899 array_unshift( $this->mode
, self
::MODE_QDESC
);
900 array_unshift( $this->curItem
, $this->curItem
[0] );
902 if ( isset( $attribs[self
::NS_RDF
. ' value'] ) ) {
903 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
904 $this->saveValue( $ns, $tag, $attribs[self
::NS_RDF
. ' value'] );
906 } elseif ( $elm === self
::NS_RDF
. ' value' ) {
907 // This should not be here.
908 throw new RuntimeException( __METHOD__
. ' Encountered <rdf:value> where it was unexpected.' );
910 // something else we don't recognize, like a qualifier maybe.
911 wfDebugLog( 'XMP', __METHOD__
.
912 " Encountered element <$elm> where only expecting character data as value of " .
914 array_unshift( $this->mode
, self
::MODE_IGNORE
);
915 array_unshift( $this->curItem
, $elm );
920 * Start an element when in MODE_QDESC.
921 * This generally happens when a simple element has an inner
922 * rdf:Description to hold qualifier elements.
925 * <exif:DigitalZoomRatio><rdf:Description><rdf:value>0/10</rdf:value>
926 * <foo:someQualifier>Bar</foo:someQualifier> </rdf:Description>
927 * </exif:DigitalZoomRatio>
928 * Called when processing the <rdf:value> or <foo:someQualifier>.
930 * @param string $elm Namespace and tag name separated by a space.
933 private function startElementModeQDesc( $elm ) {
934 if ( $elm === self
::NS_RDF
. ' value' ) {
935 return; // do nothing
937 // otherwise its a qualifier, which we ignore
938 array_unshift( $this->mode
, self
::MODE_IGNORE
);
939 array_unshift( $this->curItem
, $elm );
944 * Starting an element when in MODE_INITIAL
945 * This usually happens when we hit an element inside
946 * the outer rdf:Description
948 * This is generally where most properties start.
950 * @param string $ns Namespace
951 * @param string $tag Tag name (without namespace prefix)
952 * @param array $attribs Array of attributes
953 * @throws RuntimeException
955 private function startElementModeInitial( $ns, $tag, $attribs ) {
956 if ( $ns !== self
::NS_RDF
) {
958 if ( isset( $this->items
[$ns][$tag] ) ) {
959 if ( isset( $this->items
[$ns][$tag]['structPart'] ) ) {
960 // If this element is supposed to appear only as
961 // a child of a structure, but appears here (not as
962 // a child of a struct), then something weird is
963 // happening, so ignore this element and its children.
965 wfDebugLog( 'XMP', "Encountered <$ns:$tag> outside"
966 . " of its expected parent. Ignoring." );
968 array_unshift( $this->mode
, self
::MODE_IGNORE
);
969 array_unshift( $this->curItem
, $ns . ' ' . $tag );
973 $mode = $this->items
[$ns][$tag]['mode'];
974 array_unshift( $this->mode
, $mode );
975 array_unshift( $this->curItem
, $ns . ' ' . $tag );
976 if ( $mode === self
::MODE_STRUCT
) {
977 $this->ancestorStruct
= isset( $this->items
[$ns][$tag]['map_name'] )
978 ?
$this->items
[$ns][$tag]['map_name'] : $tag;
980 if ( $this->charContent
!== false ) {
982 // Should not happen in valid XMP.
983 throw new RuntimeException( 'tag nested in non-whitespace characters.' );
986 // This element is not on our list of allowed elements so ignore.
987 wfDebugLog( 'XMP', __METHOD__
. " Ignoring unrecognized element <$ns:$tag>." );
988 array_unshift( $this->mode
, self
::MODE_IGNORE
);
989 array_unshift( $this->curItem
, $ns . ' ' . $tag );
994 // process attributes
995 $this->doAttribs( $attribs );
999 * Hit an opening element when in a Struct (MODE_STRUCT)
1000 * This is generally for fields of a compound property.
1002 * Example of a struct (abbreviated; flash has more properties):
1004 * <exif:Flash> <rdf:Description> <exif:Fired>True</exif:Fired>
1005 * <exif:Mode>1</exif:Mode></rdf:Description></exif:Flash>
1009 * <exif:Flash rdf:parseType='Resource'> <exif:Fired>True</exif:Fired>
1010 * <exif:Mode>1</exif:Mode></exif:Flash>
1012 * @param string $ns Namespace
1013 * @param string $tag Tag name (no ns)
1014 * @param array $attribs Array of attribs w/ values.
1015 * @throws RuntimeException
1017 private function startElementModeStruct( $ns, $tag, $attribs ) {
1018 if ( $ns !== self
::NS_RDF
) {
1020 if ( isset( $this->items
[$ns][$tag] ) ) {
1021 if ( isset( $this->items
[$ns][$this->ancestorStruct
]['children'] )
1022 && !isset( $this->items
[$ns][$this->ancestorStruct
]['children'][$tag] )
1024 // This assumes that we don't have inter-namespace nesting
1025 // which we don't in all the properties we're interested in.
1026 throw new RuntimeException( " <$tag> appeared nested in <" . $this->ancestorStruct
1027 . "> where it is not allowed." );
1029 array_unshift( $this->mode
, $this->items
[$ns][$tag]['mode'] );
1030 array_unshift( $this->curItem
, $ns . ' ' . $tag );
1031 if ( $this->charContent
!== false ) {
1033 // Should not happen in valid XMP.
1034 throw new RuntimeException( "tag <$tag> nested in non-whitespace characters (" .
1035 $this->charContent
. ")." );
1038 array_unshift( $this->mode
, self
::MODE_IGNORE
);
1039 array_unshift( $this->curItem
, $elm );
1045 if ( $ns === self
::NS_RDF
&& $tag === 'Description' ) {
1046 $this->doAttribs( $attribs );
1047 array_unshift( $this->mode
, self
::MODE_STRUCT
);
1048 array_unshift( $this->curItem
, $this->curItem
[0] );
1053 * opening element in MODE_LI
1054 * process elements of arrays.
1057 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
1058 * </rdf:Seq> </exif:ISOSpeedRatings>
1059 * This method is called when we hit the <rdf:li> element.
1061 * @param string $elm Namespace . ' ' . tagname
1062 * @param array $attribs Attributes. (needed for BAGSTRUCTS)
1063 * @throws RuntimeException If gets a tag other than <rdf:li>
1065 private function startElementModeLi( $elm, $attribs ) {
1066 if ( ( $elm ) !== self
::NS_RDF
. ' li' ) {
1067 throw new RuntimeException( "<rdf:li> expected but got $elm." );
1070 if ( !isset( $this->mode
[1] ) ) {
1071 // This should never ever ever happen. Checking for it
1073 throw new RuntimeException( 'In mode Li, but no 2xPrevious mode!' );
1076 if ( $this->mode
[1] === self
::MODE_BAGSTRUCT
) {
1077 // This list item contains a compound (STRUCT) value.
1078 array_unshift( $this->mode
, self
::MODE_STRUCT
);
1079 array_unshift( $this->curItem
, $elm );
1080 $this->processingArray
= true;
1082 if ( !isset( $this->curItem
[1] ) ) {
1084 throw new RuntimeException( 'Can not find parent of BAGSTRUCT.' );
1086 list( $curNS, $curTag ) = explode( ' ', $this->curItem
[1] );
1087 $this->ancestorStruct
= isset( $this->items
[$curNS][$curTag]['map_name'] )
1088 ?
$this->items
[$curNS][$curTag]['map_name'] : $curTag;
1090 $this->doAttribs( $attribs );
1092 // Normal BAG or SEQ containing simple values.
1093 array_unshift( $this->mode
, self
::MODE_SIMPLE
);
1094 // need to add curItem[0] on again since one is for the specific item
1095 // and one is for the entire group.
1096 array_unshift( $this->curItem
, $this->curItem
[0] );
1097 $this->processingArray
= true;
1102 * Opening element in MODE_LI_LANG.
1103 * process elements of language alternatives
1106 * <dc:title> <rdf:Alt> <rdf:li xml:lang="x-default">My house
1107 * </rdf:li> </rdf:Alt> </dc:title>
1109 * This method is called when we hit the <rdf:li> element.
1111 * @param string $elm Namespace . ' ' . tag
1112 * @param array $attribs Array of elements (most importantly xml:lang)
1113 * @throws RuntimeException If gets a tag other than <rdf:li> or if no xml:lang
1115 private function startElementModeLiLang( $elm, $attribs ) {
1116 if ( $elm !== self
::NS_RDF
. ' li' ) {
1117 throw new RuntimeException( __METHOD__
. " <rdf:li> expected but got $elm." );
1119 if ( !isset( $attribs[self
::NS_XML
. ' lang'] )
1120 ||
!preg_match( '/^[-A-Za-z0-9]{2,}$/D', $attribs[self
::NS_XML
. ' lang'] )
1122 throw new RuntimeException( __METHOD__
1123 . " <rdf:li> did not contain, or has invalid xml:lang attribute in lang alternative" );
1126 // Lang is case-insensitive.
1127 $this->itemLang
= strtolower( $attribs[self
::NS_XML
. ' lang'] );
1129 // need to add curItem[0] on again since one is for the specific item
1130 // and one is for the entire group.
1131 array_unshift( $this->curItem
, $this->curItem
[0] );
1132 array_unshift( $this->mode
, self
::MODE_SIMPLE
);
1133 $this->processingArray
= true;
1137 * Hits an opening element.
1138 * Generally just calls a helper based on what MODE we're in.
1139 * Also does some initial set up for the wrapper element
1141 * @param XMLParser $parser
1142 * @param string $elm Namespace "<space>" element
1143 * @param array $attribs Attribute name => value
1144 * @throws RuntimeException
1146 function startElement( $parser, $elm, $attribs ) {
1148 if ( $elm === self
::NS_RDF
. ' RDF'
1149 ||
$elm === 'adobe:ns:meta/ xmpmeta'
1150 ||
$elm === 'adobe:ns:meta/ xapmeta'
1154 } elseif ( $elm === self
::NS_RDF
. ' Description' ) {
1155 if ( count( $this->mode
) === 0 ) {
1157 array_unshift( $this->mode
, self
::MODE_INITIAL
);
1159 } elseif ( $elm === self
::NS_RDF
. ' type' ) {
1160 // This doesn't support rdf:type properly.
1161 // In practise I have yet to see a file that
1162 // uses this element, however it is mentioned
1163 // on page 25 of part 1 of the xmp standard.
1165 // also it seems as if exiv2 and exiftool do not support
1166 // this either (That or I misunderstand the standard)
1167 wfDebugLog( 'XMP', __METHOD__
. ' Encountered <rdf:type> which isn\'t currently supported' );
1170 if ( strpos( $elm, ' ' ) === false ) {
1171 // This probably shouldn't happen.
1172 wfDebugLog( 'XMP', __METHOD__
. " Encountered <$elm> which has no namespace. Skipping." );
1177 list( $ns, $tag ) = explode( ' ', $elm, 2 );
1179 if ( count( $this->mode
) === 0 ) {
1180 // This should not happen.
1181 throw new RuntimeException( 'Error extracting XMP, '
1182 . "encountered <$elm> with no mode" );
1185 switch ( $this->mode
[0] ) {
1186 case self
::MODE_IGNORE
:
1187 $this->startElementModeIgnore( $elm );
1189 case self
::MODE_SIMPLE
:
1190 $this->startElementModeSimple( $elm, $attribs );
1192 case self
::MODE_INITIAL
:
1193 $this->startElementModeInitial( $ns, $tag, $attribs );
1195 case self
::MODE_STRUCT
:
1196 $this->startElementModeStruct( $ns, $tag, $attribs );
1198 case self
::MODE_BAG
:
1199 case self
::MODE_BAGSTRUCT
:
1200 $this->startElementModeBag( $elm );
1202 case self
::MODE_SEQ
:
1203 $this->startElementModeSeq( $elm );
1205 case self
::MODE_LANG
:
1206 $this->startElementModeLang( $elm );
1208 case self
::MODE_LI_LANG
:
1209 $this->startElementModeLiLang( $elm, $attribs );
1212 $this->startElementModeLi( $elm, $attribs );
1214 case self
::MODE_QDESC
:
1215 $this->startElementModeQDesc( $elm );
1218 throw new RuntimeException( 'StartElement in unknown mode: ' . $this->mode
[0] );
1223 * Process attributes.
1224 * Simple values can be stored as either a tag or attribute
1226 * Often the initial "<rdf:Description>" tag just has all the simple
1227 * properties as attributes.
1229 * @codingStandardsIgnoreStart Long line that cannot be broken
1232 * <rdf:Description rdf:about="" xmlns:exif="http://ns.adobe.com/exif/1.0/" exif:DigitalZoomRatio="0/10">
1234 * @codingStandardsIgnoreEnd
1236 * @param array $attribs Array attribute=>value
1237 * @throws RuntimeException
1239 private function doAttribs( $attribs ) {
1240 // first check for rdf:parseType attribute, as that can change
1241 // how the attributes are interperted.
1243 if ( isset( $attribs[self
::NS_RDF
. ' parseType'] )
1244 && $attribs[self
::NS_RDF
. ' parseType'] === 'Resource'
1245 && $this->mode
[0] === self
::MODE_SIMPLE
1247 // this is equivalent to having an inner rdf:Description
1248 $this->mode
[0] = self
::MODE_QDESC
;
1250 foreach ( $attribs as $name => $val ) {
1251 if ( strpos( $name, ' ' ) === false ) {
1252 // This shouldn't happen, but so far some old software forgets namespace
1254 wfDebugLog( 'XMP', __METHOD__
. ' Encountered non-namespaced attribute: '
1255 . " $name=\"$val\". Skipping. " );
1258 list( $ns, $tag ) = explode( ' ', $name, 2 );
1259 if ( $ns === self
::NS_RDF
) {
1260 if ( $tag === 'value' ||
$tag === 'resource' ) {
1261 // resource is for url.
1262 // value attribute is a weird way of just putting the contents.
1263 $this->char( $this->xmlParser
, $val );
1265 } elseif ( isset( $this->items
[$ns][$tag] ) ) {
1266 if ( $this->mode
[0] === self
::MODE_SIMPLE
) {
1267 throw new RuntimeException( __METHOD__
1268 . " $ns:$tag found as attribute where not allowed" );
1270 $this->saveValue( $ns, $tag, $val );
1272 wfDebugLog( 'XMP', __METHOD__
. " Ignoring unrecognized element <$ns:$tag>." );
1278 * Given an extracted value, save it to results array
1280 * note also uses $this->ancestorStruct and
1281 * $this->processingArray to determine what name to
1282 * save the value under. (in addition to $tag).
1284 * @param string $ns Namespace of tag this is for
1285 * @param string $tag Tag name
1286 * @param string $val Value to save
1288 private function saveValue( $ns, $tag, $val ) {
1290 $info =& $this->items
[$ns][$tag];
1291 $finalName = isset( $info['map_name'] )
1292 ?
$info['map_name'] : $tag;
1293 if ( isset( $info['validate'] ) ) {
1294 $validate = is_array( $info['validate'] ) ?
$info['validate']
1295 : array( 'XMPValidate', $info['validate'] );
1297 if ( is_callable( $validate ) ) {
1298 call_user_func_array( $validate, array( $info, &$val, true ) );
1299 // the reasoning behind using &$val instead of using the return value
1300 // is to be consistent between here and validating structures.
1301 if ( is_null( $val ) ) {
1302 wfDebugLog( 'XMP', __METHOD__
. " <$ns:$tag> failed validation." );
1307 wfDebugLog( 'XMP', __METHOD__
. " Validation function for $finalName ("
1308 . $validate[0] . '::' . $validate[1] . '()) is not callable.' );
1312 if ( $this->ancestorStruct
&& $this->processingArray
) {
1313 // Aka both an array and a struct. ( self::MODE_BAGSTRUCT )
1314 $this->results
['xmp-' . $info['map_group']][$this->ancestorStruct
][][$finalName] = $val;
1315 } elseif ( $this->ancestorStruct
) {
1316 $this->results
['xmp-' . $info['map_group']][$this->ancestorStruct
][$finalName] = $val;
1317 } elseif ( $this->processingArray
) {
1318 if ( $this->itemLang
=== false ) {
1320 $this->results
['xmp-' . $info['map_group']][$finalName][] = $val;
1323 $this->results
['xmp-' . $info['map_group']][$finalName][$this->itemLang
] = $val;
1326 $this->results
['xmp-' . $info['map_group']][$finalName] = $val;