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
24 use Psr\Log\LoggerAwareInterface
;
25 use Psr\Log\LoggerInterface
;
26 use Psr\Log\NullLogger
;
29 * Class for reading xmp data containing properties relevant to
30 * images, and spitting out an array that FormatMetadata accepts.
32 * Note, this is not meant to recognize every possible thing you can
33 * encode in XMP. It should recognize all the properties we want.
34 * For example it doesn't have support for structures with multiple
35 * nesting levels, as none of the properties we're supporting use that
36 * feature. If it comes across properties it doesn't recognize, it should
39 * The public methods one would call in this class are
41 * Reads in xmp content.
42 * Can potentially be called multiple times with partial data each time.
43 * - parseExtended( $content )
44 * Reads XMPExtended blocks (jpeg files only).
46 * Outputs a results array.
48 * Note XMP kind of looks like rdf. They are not the same thing - XMP is
49 * encoded as a specific subset of rdf. This class can read XMP. It cannot
53 class XMPReader
implements LoggerAwareInterface
{
54 /** @var array XMP item configuration array */
57 /** @var array Array to hold the current element (and previous element, and so on) */
58 private $curItem = array();
60 /** @var bool|string The structure name when processing nested structures. */
61 private $ancestorStruct = false;
63 /** @var bool|string Temporary holder for character data that appears in xmp doc. */
64 private $charContent = false;
66 /** @var array Stores the state the xmpreader is in (see MODE_FOO constants) */
67 private $mode = array();
69 /** @var array Array to hold results */
70 private $results = array();
72 /** @var bool If we're doing a seq or bag. */
73 private $processingArray = false;
75 /** @var bool|string Used for lang alts only */
76 private $itemLang = false;
78 /** @var resource A resource handle for the XML parser */
81 /** @var bool|string Character set like 'UTF-8' */
82 private $charset = false;
85 private $extendedXMPOffset = 0;
87 /** @var int Flag determining if the XMP is safe to parse **/
88 private $parsable = 0;
90 /** @var string Buffer of XML to parse **/
91 private $xmlParsableBuffer = '';
94 * These are various mode constants.
95 * they are used to figure out what to do
96 * with an element when its encountered.
98 * For example, MODE_IGNORE is used when processing
99 * a property we're not interested in. So if a new
100 * element pops up when we're in that mode, we ignore it.
102 const MODE_INITIAL
= 0;
103 const MODE_IGNORE
= 1;
105 const MODE_LI_LANG
= 3;
106 const MODE_QDESC
= 4;
108 // The following MODE constants are also used in the
109 // $items array to denote what type of property the item is.
110 const MODE_SIMPLE
= 10;
111 const MODE_STRUCT
= 11; // structure (associative array)
112 const MODE_SEQ
= 12; // ordered list
113 const MODE_BAG
= 13; // unordered list
114 const MODE_LANG
= 14;
115 const MODE_ALT
= 15; // non-language alt. Currently not implemented, and not needed atm.
116 const MODE_BAGSTRUCT
= 16; // A BAG of Structs.
118 const NS_RDF
= 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
119 const NS_XML
= 'http://www.w3.org/XML/1998/namespace';
121 // States used while determining if XML is safe to parse
122 const PARSABLE_UNKNOWN
= 0;
123 const PARSABLE_OK
= 1;
124 const PARSABLE_BUFFERING
= 2;
125 const PARSABLE_NO
= 3;
128 * @var LoggerInterface
135 * Primary job is to initialize the XMLParser
137 function __construct( LoggerInterface
$logger = null ) {
139 if ( !function_exists( 'xml_parser_create_ns' ) ) {
140 // this should already be checked by this point
141 throw new RuntimeException( 'XMP support requires XML Parser' );
144 $this->setLogger( $logger );
146 $this->setLogger( new NullLogger() );
149 $this->items
= XMPInfo
::getItems();
151 $this->resetXMLParser();
154 public function setLogger( LoggerInterface
$logger ) {
155 $this->logger
= $logger;
159 * Main use is if a single item has multiple xmp documents describing it.
160 * For example in jpeg's with extendedXMP
162 private function resetXMLParser() {
164 if ( $this->xmlParser
) {
166 xml_parser_free( $this->xmlParser
);
169 $this->xmlParser
= xml_parser_create_ns( 'UTF-8', ' ' );
170 xml_parser_set_option( $this->xmlParser
, XML_OPTION_CASE_FOLDING
, 0 );
171 xml_parser_set_option( $this->xmlParser
, XML_OPTION_SKIP_WHITE
, 1 );
173 xml_set_element_handler( $this->xmlParser
,
174 array( $this, 'startElement' ),
175 array( $this, 'endElement' ) );
177 xml_set_character_data_handler( $this->xmlParser
, array( $this, 'char' ) );
179 $this->parsable
= self
::PARSABLE_UNKNOWN
;
180 $this->xmlParsableBuffer
= '';
183 /** Destroy the xml parser
185 * Not sure if this is actually needed.
187 function __destruct() {
188 // not sure if this is needed.
189 xml_parser_free( $this->xmlParser
);
193 * Check if this instance supports using this class
195 public static function isSupported() {
196 return function_exists( 'xml_parser_create_ns' ) && class_exists( 'XMLReader' );
199 /** Get the result array. Do some post-processing before returning
200 * the array, and transform any metadata that is special-cased.
202 * @return array Array of results as an array of arrays suitable for
203 * FormatMetadata::getFormattedData().
205 public function getResults() {
206 // xmp-special is for metadata that affects how stuff
207 // is extracted. For example xmpNote:HasExtendedXMP.
209 // It is also used to handle photoshop:AuthorsPosition
210 // which is weird and really part of another property,
211 // see 2:85 in IPTC. See also pg 21 of IPTC4XMP standard.
212 // The location fields also use it.
214 $data = $this->results
;
216 if ( isset( $data['xmp-special']['AuthorsPosition'] )
217 && is_string( $data['xmp-special']['AuthorsPosition'] )
218 && isset( $data['xmp-general']['Artist'][0] )
220 // Note, if there is more than one creator,
221 // this only applies to first. This also will
222 // only apply to the dc:Creator prop, not the
225 $data['xmp-general']['Artist'][0] =
226 $data['xmp-special']['AuthorsPosition'] . ', '
227 . $data['xmp-general']['Artist'][0];
230 // Go through the LocationShown and LocationCreated
231 // changing it to the non-hierarchal form used by
232 // the other location fields.
234 if ( isset( $data['xmp-special']['LocationShown'][0] )
235 && is_array( $data['xmp-special']['LocationShown'][0] )
237 // the is_array is just paranoia. It should always
239 foreach ( $data['xmp-special']['LocationShown'] as $loc ) {
240 if ( !is_array( $loc ) ) {
241 // To avoid copying over the _type meta-fields.
244 foreach ( $loc as $field => $val ) {
245 $data['xmp-general'][$field . 'Dest'][] = $val;
249 if ( isset( $data['xmp-special']['LocationCreated'][0] )
250 && is_array( $data['xmp-special']['LocationCreated'][0] )
252 // the is_array is just paranoia. It should always
254 foreach ( $data['xmp-special']['LocationCreated'] as $loc ) {
255 if ( !is_array( $loc ) ) {
256 // To avoid copying over the _type meta-fields.
259 foreach ( $loc as $field => $val ) {
260 $data['xmp-general'][$field . 'Created'][] = $val;
265 // We don't want to return the special values, since they're
266 // special and not info to be stored about the file.
267 unset( $data['xmp-special'] );
269 // Convert GPSAltitude to negative if below sea level.
270 if ( isset( $data['xmp-exif']['GPSAltitudeRef'] )
271 && isset( $data['xmp-exif']['GPSAltitude'] )
274 // Must convert to a real before multiplying by -1
275 // XMPValidate guarantees there will always be a '/' in this value.
276 list( $nom, $denom ) = explode( '/', $data['xmp-exif']['GPSAltitude'] );
277 $data['xmp-exif']['GPSAltitude'] = $nom / $denom;
279 if ( $data['xmp-exif']['GPSAltitudeRef'] == '1' ) {
280 $data['xmp-exif']['GPSAltitude'] *= -1;
282 unset( $data['xmp-exif']['GPSAltitudeRef'] );
289 * Main function to call to parse XMP. Use getResults to
292 * Also catches any errors during processing, writes them to
293 * debug log, blanks result array and returns false.
295 * @param string $content XMP data
296 * @param bool $allOfIt If this is all the data (true) or if its split up (false). Default true
297 * @param bool $reset Does xml parser need to be reset. Default false
298 * @throws RuntimeException
299 * @return bool Success.
301 public function parse( $content, $allOfIt = true, $reset = false ) {
303 $this->resetXMLParser();
307 // detect encoding by looking for BOM which is supposed to be in processing instruction.
308 // see page 12 of http://www.adobe.com/devnet/xmp/pdfs/XMPSpecificationPart3.pdf
309 if ( !$this->charset
) {
311 if ( preg_match( '/\xEF\xBB\xBF|\xFE\xFF|\x00\x00\xFE\xFF|\xFF\xFE\x00\x00|\xFF\xFE/',
316 $this->charset
= 'UTF-16BE';
319 $this->charset
= 'UTF-16LE';
321 case "\x00\x00\xFE\xFF":
322 $this->charset
= 'UTF-32BE';
324 case "\xFF\xFE\x00\x00":
325 $this->charset
= 'UTF-32LE';
328 $this->charset
= 'UTF-8';
331 //this should be impossible to get to
332 throw new RuntimeException( "Invalid BOM" );
335 // standard specifically says, if no bom assume utf-8
336 $this->charset
= 'UTF-8';
339 if ( $this->charset
!== 'UTF-8' ) {
340 //don't convert if already utf-8
341 wfSuppressWarnings();
342 $content = iconv( $this->charset
, 'UTF-8//IGNORE', $content );
346 // Ensure the XMP block does not have an xml doctype declaration, which
347 // could declare entities unsafe to parse with xml_parse (T85848/T71210).
348 if ( $this->parsable
!== self
::PARSABLE_OK
) {
349 if ( $this->parsable
=== self
::PARSABLE_NO
) {
350 throw new Exception( 'Unsafe doctype declaration in XML.' );
353 $content = $this->xmlParsableBuffer
. $content;
354 if ( !$this->checkParseSafety( $content ) ) {
355 if ( !$allOfIt && $this->parsable
!== self
::PARSABLE_NO
) {
356 // parse wasn't Unsuccessful yet, so return true
360 $msg = ( $this->parsable
=== self
::PARSABLE_NO
) ?
361 'Unsafe doctype declaration in XML.' :
362 'No root element found in XML.';
363 throw new Exception( $msg );
367 $ok = xml_parse( $this->xmlParser
, $content, $allOfIt );
369 $error = xml_error_string( xml_get_error_code( $this->xmlParser
) );
370 $where = 'line: ' . xml_get_current_line_number( $this->xmlParser
)
371 . ' column: ' . xml_get_current_column_number( $this->xmlParser
)
372 . ' byte offset: ' . xml_get_current_byte_index( $this->xmlParser
);
374 $this->logger
->info( "XMPReader::parse : Error reading XMP content: $error ($where)" );
375 $this->results
= array(); // blank if error.
378 } catch ( Exception
$e ) {
379 $this->logger
->info( 'XMP parse error: ' . $e );
380 $this->results
= array();
388 /** Entry point for XMPExtended blocks in jpeg files
390 * @todo In serious need of testing
391 * @see http://www.adobe.ge/devnet/xmp/pdfs/XMPSpecificationPart3.pdf XMP spec part 3 page 20
392 * @param string $content XMPExtended block minus the namespace signature
393 * @return bool If it succeeded.
395 public function parseExtended( $content ) {
396 // @todo FIXME: This is untested. Hard to find example files
397 // or programs that make such files..
398 $guid = substr( $content, 0, 32 );
399 if ( !isset( $this->results
['xmp-special']['HasExtendedXMP'] )
400 ||
$this->results
['xmp-special']['HasExtendedXMP'] !== $guid
402 $this->logger
->info( __METHOD__
.
403 " Ignoring XMPExtended block due to wrong guid (guid= '$guid')" );
407 $len = unpack( 'Nlength/Noffset', substr( $content, 32, 8 ) );
409 if ( !$len ||
$len['length'] < 4 ||
$len['offset'] < 0 ||
$len['offset'] > $len['length'] ) {
410 $this->logger
->info( __METHOD__
. 'Error reading extended XMP block, invalid length or offset.' );
415 // we're not very robust here. we should accept it in the wrong order.
416 // To quote the XMP standard:
417 // "A JPEG writer should write the ExtendedXMP marker segments in order,
418 // immediately following the StandardXMP. However, the JPEG standard
419 // does not require preservation of marker segment order. A robust JPEG
420 // reader should tolerate the marker segments in any order."
422 // otoh the probability that an image will have more than 128k of
423 // metadata is rather low... so the probability that it will have
424 // > 128k, and be in the wrong order is very low...
426 if ( $len['offset'] !== $this->extendedXMPOffset
) {
427 $this->logger
->info( __METHOD__
. 'Ignoring XMPExtended block due to wrong order. (Offset was '
428 . $len['offset'] . ' but expected ' . $this->extendedXMPOffset
. ')' );
433 if ( $len['offset'] === 0 ) {
434 // if we're starting the extended block, we've probably already
435 // done the XMPStandard block, so reset.
436 $this->resetXMLParser();
439 $this->extendedXMPOffset +
= $len['length'];
441 $actualContent = substr( $content, 40 );
443 if ( $this->extendedXMPOffset
=== strlen( $actualContent ) ) {
449 $this->logger
->debug( __METHOD__
. 'Parsing a XMPExtended block' );
451 return $this->parse( $actualContent, $atEnd );
455 * Character data handler
456 * Called whenever character data is found in the xmp document.
458 * does nothing if we're in MODE_IGNORE or if the data is whitespace
459 * throws an error if we're not in MODE_SIMPLE (as we're not allowed to have character
460 * data in the other modes).
462 * As an example, this happens when we encounter XMP like:
463 * <exif:DigitalZoomRatio>0/10</exif:DigitalZoomRatio>
464 * and are processing the 0/10 bit.
466 * @param XMLParser $parser XMLParser reference to the xml parser
467 * @param string $data Character data
468 * @throws RuntimeException On invalid data
470 function char( $parser, $data ) {
472 $data = trim( $data );
473 if ( trim( $data ) === "" ) {
477 if ( !isset( $this->mode
[0] ) ) {
478 throw new RuntimeException( 'Unexpected character data before first rdf:Description element' );
481 if ( $this->mode
[0] === self
::MODE_IGNORE
) {
485 if ( $this->mode
[0] !== self
::MODE_SIMPLE
486 && $this->mode
[0] !== self
::MODE_QDESC
488 throw new RuntimeException( 'character data where not expected. (mode ' . $this->mode
[0] . ')' );
491 // to check, how does this handle w.s.
492 if ( $this->charContent
=== false ) {
493 $this->charContent
= $data;
495 $this->charContent
.= $data;
500 * Check if a block of XML is safe to pass to xml_parse, i.e. doesn't
501 * contain a doctype declaration which could contain a dos attack if we
502 * parse it and expand internal entities (T85848).
504 * @param string $content xml string to check for parse safety
505 * @return bool true if the xml is safe to parse, false otherwise
507 private function checkParseSafety( $content ) {
508 $reader = new XMLReader();
511 // For XMLReader to parse incomplete/invalid XML, it has to be open()'ed
512 // instead of using XML().
514 'data://text/plain,' . urlencode( $content ),
516 LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_NONET
519 $oldDisable = libxml_disable_entity_loader( true );
520 $reset = new ScopedCallback(
521 'libxml_disable_entity_loader',
524 $reader->setParserProperty( XMLReader
::SUBST_ENTITIES
, false );
526 // Even with LIBXML_NOWARNING set, XMLReader::read gives a warning
527 // when parsing truncated XML, which causes unit tests to fail.
528 wfSuppressWarnings();
529 while ( $reader->read() ) {
530 if ( $reader->nodeType
=== XMLReader
::ELEMENT
) {
531 // Reached the first element without hitting a doctype declaration
532 $this->parsable
= self
::PARSABLE_OK
;
536 if ( $reader->nodeType
=== XMLReader
::DOC_TYPE
) {
537 $this->parsable
= self
::PARSABLE_NO
;
544 if ( !is_null( $result ) ) {
548 // Reached the end of the parsable xml without finding an element
549 // or doctype. Buffer and try again.
550 $this->parsable
= self
::PARSABLE_BUFFERING
;
551 $this->xmlParsableBuffer
= $content;
555 /** When we hit a closing element in MODE_IGNORE
556 * Check to see if this is the element we started to ignore,
557 * in which case we get out of MODE_IGNORE
559 * @param string $elm Namespace of element followed by a space and then tag name of element.
561 private function endElementModeIgnore( $elm ) {
562 if ( $this->curItem
[0] === $elm ) {
563 array_shift( $this->curItem
);
564 array_shift( $this->mode
);
569 * Hit a closing element when in MODE_SIMPLE.
570 * This generally means that we finished processing a
571 * property value, and now have to save the result to the
574 * For example, when processing:
575 * <exif:DigitalZoomRatio>0/10</exif:DigitalZoomRatio>
576 * this deals with when we hit </exif:DigitalZoomRatio>.
578 * Or it could be if we hit the end element of a property
579 * of a compound data structure (like a member of an array).
581 * @param string $elm Namespace, space, and tag name.
583 private function endElementModeSimple( $elm ) {
584 if ( $this->charContent
!== false ) {
585 if ( $this->processingArray
) {
586 // if we're processing an array, use the original element
587 // name instead of rdf:li.
588 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
590 list( $ns, $tag ) = explode( ' ', $elm, 2 );
592 $this->saveValue( $ns, $tag, $this->charContent
);
594 $this->charContent
= false; // reset
596 array_shift( $this->curItem
);
597 array_shift( $this->mode
);
601 * Hit a closing element in MODE_STRUCT, MODE_SEQ, MODE_BAG
602 * generally means we've finished processing a nested structure.
603 * resets some internal variables to indicate that.
605 * Note this means we hit the closing element not the "</rdf:Seq>".
607 * @par For example, when processing:
609 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
610 * </rdf:Seq> </exif:ISOSpeedRatings>
613 * This method is called when we hit the "</exif:ISOSpeedRatings>" tag.
615 * @param string $elm Namespace . space . tag name.
616 * @throws RuntimeException
618 private function endElementNested( $elm ) {
620 /* cur item must be the same as $elm, unless if in MODE_STRUCT
621 in which case it could also be rdf:Description */
622 if ( $this->curItem
[0] !== $elm
623 && !( $elm === self
::NS_RDF
. ' Description'
624 && $this->mode
[0] === self
::MODE_STRUCT
)
626 throw new RuntimeException( "nesting mismatch. got a </$elm> but expected a </" .
627 $this->curItem
[0] . '>' );
630 // Validate structures.
631 list( $ns, $tag ) = explode( ' ', $elm, 2 );
632 if ( isset( $this->items
[$ns][$tag]['validate'] ) ) {
634 $info =& $this->items
[$ns][$tag];
635 $finalName = isset( $info['map_name'] )
636 ?
$info['map_name'] : $tag;
638 if ( is_array( $info['validate'] ) ) {
639 $validate = $info['validate'];
641 $validator = new XMPValidate( $this->logger
);
642 $validate = array( $validator, $info['validate'] );
645 if ( !isset( $this->results
['xmp-' . $info['map_group']][$finalName] ) ) {
646 // This can happen if all the members of the struct failed validation.
647 $this->logger
->debug( __METHOD__
. " <$ns:$tag> has no valid members." );
648 } elseif ( is_callable( $validate ) ) {
649 $val =& $this->results
['xmp-' . $info['map_group']][$finalName];
650 call_user_func_array( $validate, array( $info, &$val, false ) );
651 if ( is_null( $val ) ) {
652 // the idea being the validation function will unset the variable if
654 $this->logger
->info( __METHOD__
. " <$ns:$tag> failed validation." );
655 unset( $this->results
['xmp-' . $info['map_group']][$finalName] );
658 $this->logger
->warning( __METHOD__
. " Validation function for $finalName ("
659 . $validate[0] . '::' . $validate[1] . '()) is not callable.' );
663 array_shift( $this->curItem
);
664 array_shift( $this->mode
);
665 $this->ancestorStruct
= false;
666 $this->processingArray
= false;
667 $this->itemLang
= false;
671 * Hit a closing element in MODE_LI (either rdf:Seq, or rdf:Bag )
672 * Add information about what type of element this is.
674 * Note we still have to hit the outer "</property>"
676 * @par For example, when processing:
678 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
679 * </rdf:Seq> </exif:ISOSpeedRatings>
682 * This method is called when we hit the "</rdf:Seq>".
683 * (For comparison, we call endElementModeSimple when we
684 * hit the "</rdf:li>")
686 * @param string $elm Namespace . ' ' . element name
687 * @throws RuntimeException
689 private function endElementModeLi( $elm ) {
691 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
692 $info = $this->items
[$ns][$tag];
693 $finalName = isset( $info['map_name'] )
694 ?
$info['map_name'] : $tag;
696 array_shift( $this->mode
);
698 if ( !isset( $this->results
['xmp-' . $info['map_group']][$finalName] ) ) {
699 $this->logger
->debug( __METHOD__
. " Empty compund element $finalName." );
704 if ( $elm === self
::NS_RDF
. ' Seq' ) {
705 $this->results
['xmp-' . $info['map_group']][$finalName]['_type'] = 'ol';
706 } elseif ( $elm === self
::NS_RDF
. ' Bag' ) {
707 $this->results
['xmp-' . $info['map_group']][$finalName]['_type'] = 'ul';
708 } elseif ( $elm === self
::NS_RDF
. ' Alt' ) {
709 // extra if needed as you could theoretically have a non-language alt.
710 if ( $info['mode'] === self
::MODE_LANG
) {
711 $this->results
['xmp-' . $info['map_group']][$finalName]['_type'] = 'lang';
714 throw new RuntimeException( __METHOD__
. " expected </rdf:seq> or </rdf:bag> but instead got $elm." );
719 * End element while in MODE_QDESC
720 * mostly when ending an element when we have a simple value
721 * that has qualifiers.
723 * Qualifiers aren't all that common, and we don't do anything
726 * @param string $elm Namespace and element
728 private function endElementModeQDesc( $elm ) {
730 if ( $elm === self
::NS_RDF
. ' value' ) {
731 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
732 $this->saveValue( $ns, $tag, $this->charContent
);
736 array_shift( $this->mode
);
737 array_shift( $this->curItem
);
742 * Handler for hitting a closing element.
744 * generally just calls a helper function depending on what
747 * Ignores the outer wrapping elements that are optional in
748 * xmp and have no meaning.
750 * @param XMLParser $parser
751 * @param string $elm Namespace . ' ' . element name
752 * @throws RuntimeException
754 function endElement( $parser, $elm ) {
755 if ( $elm === ( self
::NS_RDF
. ' RDF' )
756 ||
$elm === 'adobe:ns:meta/ xmpmeta'
757 ||
$elm === 'adobe:ns:meta/ xapmeta'
763 if ( $elm === self
::NS_RDF
. ' type' ) {
764 // these aren't really supported properly yet.
765 // However, it appears they almost never used.
766 $this->logger
->info( __METHOD__
. ' encountered <rdf:type>' );
769 if ( strpos( $elm, ' ' ) === false ) {
770 // This probably shouldn't happen.
771 // However, there is a bug in an adobe product
772 // that forgets the namespace on some things.
773 // (Luckily they are unimportant things).
774 $this->logger
->info( __METHOD__
. " Encountered </$elm> which has no namespace. Skipping." );
779 if ( count( $this->mode
[0] ) === 0 ) {
780 // This should never ever happen and means
781 // there is a pretty major bug in this class.
782 throw new RuntimeException( 'Encountered end element with no mode' );
785 if ( count( $this->curItem
) == 0 && $this->mode
[0] !== self
::MODE_INITIAL
) {
786 // just to be paranoid. Should always have a curItem, except for initially
787 // (aka during MODE_INITAL).
788 throw new RuntimeException( "Hit end element </$elm> but no curItem" );
791 switch ( $this->mode
[0] ) {
792 case self
::MODE_IGNORE
:
793 $this->endElementModeIgnore( $elm );
795 case self
::MODE_SIMPLE
:
796 $this->endElementModeSimple( $elm );
798 case self
::MODE_STRUCT
:
801 case self
::MODE_LANG
:
802 case self
::MODE_BAGSTRUCT
:
803 $this->endElementNested( $elm );
805 case self
::MODE_INITIAL
:
806 if ( $elm === self
::NS_RDF
. ' Description' ) {
807 array_shift( $this->mode
);
809 throw new RuntimeException( 'Element ended unexpectedly while in MODE_INITIAL' );
813 case self
::MODE_LI_LANG
:
814 $this->endElementModeLi( $elm );
816 case self
::MODE_QDESC
:
817 $this->endElementModeQDesc( $elm );
820 $this->logger
->warning( __METHOD__
. " no mode (elm = $elm)" );
826 * Hit an opening element while in MODE_IGNORE
828 * XMP is extensible, so ignore any tag we don't understand.
830 * Mostly ignores, unless we encounter the element that we are ignoring.
831 * in which case we add it to the item stack, so we can ignore things
832 * that are nested, correctly.
834 * @param string $elm Namespace . ' ' . tag name
836 private function startElementModeIgnore( $elm ) {
837 if ( $elm === $this->curItem
[0] ) {
838 array_unshift( $this->curItem
, $elm );
839 array_unshift( $this->mode
, self
::MODE_IGNORE
);
844 * Start element in MODE_BAG (unordered array)
845 * this should always be <rdf:Bag>
847 * @param string $elm Namespace . ' ' . tag
848 * @throws RuntimeException If we have an element that's not <rdf:Bag>
850 private function startElementModeBag( $elm ) {
851 if ( $elm === self
::NS_RDF
. ' Bag' ) {
852 array_unshift( $this->mode
, self
::MODE_LI
);
854 throw new RuntimeException( "Expected <rdf:Bag> but got $elm." );
859 * Start element in MODE_SEQ (ordered array)
860 * this should always be <rdf:Seq>
862 * @param string $elm Namespace . ' ' . tag
863 * @throws RuntimeException If we have an element that's not <rdf:Seq>
865 private function startElementModeSeq( $elm ) {
866 if ( $elm === self
::NS_RDF
. ' Seq' ) {
867 array_unshift( $this->mode
, self
::MODE_LI
);
868 } elseif ( $elm === self
::NS_RDF
. ' Bag' ) {
870 $this->logger
->info( __METHOD__
. ' Expected an rdf:Seq, but got an rdf:Bag. Pretending'
871 . ' it is a Seq, since some buggy software is known to screw this up.' );
872 array_unshift( $this->mode
, self
::MODE_LI
);
874 throw new RuntimeException( "Expected <rdf:Seq> but got $elm." );
879 * Start element in MODE_LANG (language alternative)
880 * this should always be <rdf:Alt>
882 * This tag tends to be used for metadata like describe this
883 * picture, which can be translated into multiple languages.
885 * XMP supports non-linguistic alternative selections,
886 * which are really only used for thumbnails, which
887 * we don't care about.
889 * @param string $elm Namespace . ' ' . tag
890 * @throws RuntimeException If we have an element that's not <rdf:Alt>
892 private function startElementModeLang( $elm ) {
893 if ( $elm === self
::NS_RDF
. ' Alt' ) {
894 array_unshift( $this->mode
, self
::MODE_LI_LANG
);
896 throw new RuntimeException( "Expected <rdf:Seq> but got $elm." );
901 * Handle an opening element when in MODE_SIMPLE
903 * This should not happen often. This is for if a simple element
904 * already opened has a child element. Could happen for a
908 * <exif:DigitalZoomRatio><rdf:Description><rdf:value>0/10</rdf:value>
909 * <foo:someQualifier>Bar</foo:someQualifier> </rdf:Description>
910 * </exif:DigitalZoomRatio>
912 * This method is called when processing the <rdf:Description> element
914 * @param string $elm Namespace and tag names separated by space.
915 * @param array $attribs Attributes of the element.
916 * @throws RuntimeException
918 private function startElementModeSimple( $elm, $attribs ) {
919 if ( $elm === self
::NS_RDF
. ' Description' ) {
920 // If this value has qualifiers
921 array_unshift( $this->mode
, self
::MODE_QDESC
);
922 array_unshift( $this->curItem
, $this->curItem
[0] );
924 if ( isset( $attribs[self
::NS_RDF
. ' value'] ) ) {
925 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
926 $this->saveValue( $ns, $tag, $attribs[self
::NS_RDF
. ' value'] );
928 } elseif ( $elm === self
::NS_RDF
. ' value' ) {
929 // This should not be here.
930 throw new RuntimeException( __METHOD__
. ' Encountered <rdf:value> where it was unexpected.' );
932 // something else we don't recognize, like a qualifier maybe.
933 $this->logger
->info( __METHOD__
.
934 " Encountered element <$elm> where only expecting character data as value of " .
936 array_unshift( $this->mode
, self
::MODE_IGNORE
);
937 array_unshift( $this->curItem
, $elm );
942 * Start an element when in MODE_QDESC.
943 * This generally happens when a simple element has an inner
944 * rdf:Description to hold qualifier elements.
947 * <exif:DigitalZoomRatio><rdf:Description><rdf:value>0/10</rdf:value>
948 * <foo:someQualifier>Bar</foo:someQualifier> </rdf:Description>
949 * </exif:DigitalZoomRatio>
950 * Called when processing the <rdf:value> or <foo:someQualifier>.
952 * @param string $elm Namespace and tag name separated by a space.
955 private function startElementModeQDesc( $elm ) {
956 if ( $elm === self
::NS_RDF
. ' value' ) {
957 return; // do nothing
959 // otherwise its a qualifier, which we ignore
960 array_unshift( $this->mode
, self
::MODE_IGNORE
);
961 array_unshift( $this->curItem
, $elm );
966 * Starting an element when in MODE_INITIAL
967 * This usually happens when we hit an element inside
968 * the outer rdf:Description
970 * This is generally where most properties start.
972 * @param string $ns Namespace
973 * @param string $tag Tag name (without namespace prefix)
974 * @param array $attribs Array of attributes
975 * @throws RuntimeException
977 private function startElementModeInitial( $ns, $tag, $attribs ) {
978 if ( $ns !== self
::NS_RDF
) {
980 if ( isset( $this->items
[$ns][$tag] ) ) {
981 if ( isset( $this->items
[$ns][$tag]['structPart'] ) ) {
982 // If this element is supposed to appear only as
983 // a child of a structure, but appears here (not as
984 // a child of a struct), then something weird is
985 // happening, so ignore this element and its children.
987 $this->logger
->warning( "Encountered <$ns:$tag> outside"
988 . " of its expected parent. Ignoring." );
990 array_unshift( $this->mode
, self
::MODE_IGNORE
);
991 array_unshift( $this->curItem
, $ns . ' ' . $tag );
995 $mode = $this->items
[$ns][$tag]['mode'];
996 array_unshift( $this->mode
, $mode );
997 array_unshift( $this->curItem
, $ns . ' ' . $tag );
998 if ( $mode === self
::MODE_STRUCT
) {
999 $this->ancestorStruct
= isset( $this->items
[$ns][$tag]['map_name'] )
1000 ?
$this->items
[$ns][$tag]['map_name'] : $tag;
1002 if ( $this->charContent
!== false ) {
1004 // Should not happen in valid XMP.
1005 throw new RuntimeException( 'tag nested in non-whitespace characters.' );
1008 // This element is not on our list of allowed elements so ignore.
1009 $this->logger
->debug( __METHOD__
. " Ignoring unrecognized element <$ns:$tag>." );
1010 array_unshift( $this->mode
, self
::MODE_IGNORE
);
1011 array_unshift( $this->curItem
, $ns . ' ' . $tag );
1016 // process attributes
1017 $this->doAttribs( $attribs );
1021 * Hit an opening element when in a Struct (MODE_STRUCT)
1022 * This is generally for fields of a compound property.
1024 * Example of a struct (abbreviated; flash has more properties):
1026 * <exif:Flash> <rdf:Description> <exif:Fired>True</exif:Fired>
1027 * <exif:Mode>1</exif:Mode></rdf:Description></exif:Flash>
1031 * <exif:Flash rdf:parseType='Resource'> <exif:Fired>True</exif:Fired>
1032 * <exif:Mode>1</exif:Mode></exif:Flash>
1034 * @param string $ns Namespace
1035 * @param string $tag Tag name (no ns)
1036 * @param array $attribs Array of attribs w/ values.
1037 * @throws RuntimeException
1039 private function startElementModeStruct( $ns, $tag, $attribs ) {
1040 if ( $ns !== self
::NS_RDF
) {
1042 if ( isset( $this->items
[$ns][$tag] ) ) {
1043 if ( isset( $this->items
[$ns][$this->ancestorStruct
]['children'] )
1044 && !isset( $this->items
[$ns][$this->ancestorStruct
]['children'][$tag] )
1046 // This assumes that we don't have inter-namespace nesting
1047 // which we don't in all the properties we're interested in.
1048 throw new RuntimeException( " <$tag> appeared nested in <" . $this->ancestorStruct
1049 . "> where it is not allowed." );
1051 array_unshift( $this->mode
, $this->items
[$ns][$tag]['mode'] );
1052 array_unshift( $this->curItem
, $ns . ' ' . $tag );
1053 if ( $this->charContent
!== false ) {
1055 // Should not happen in valid XMP.
1056 throw new RuntimeException( "tag <$tag> nested in non-whitespace characters (" .
1057 $this->charContent
. ")." );
1060 array_unshift( $this->mode
, self
::MODE_IGNORE
);
1061 array_unshift( $this->curItem
, $elm );
1067 if ( $ns === self
::NS_RDF
&& $tag === 'Description' ) {
1068 $this->doAttribs( $attribs );
1069 array_unshift( $this->mode
, self
::MODE_STRUCT
);
1070 array_unshift( $this->curItem
, $this->curItem
[0] );
1075 * opening element in MODE_LI
1076 * process elements of arrays.
1079 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
1080 * </rdf:Seq> </exif:ISOSpeedRatings>
1081 * This method is called when we hit the <rdf:li> element.
1083 * @param string $elm Namespace . ' ' . tagname
1084 * @param array $attribs Attributes. (needed for BAGSTRUCTS)
1085 * @throws RuntimeException If gets a tag other than <rdf:li>
1087 private function startElementModeLi( $elm, $attribs ) {
1088 if ( ( $elm ) !== self
::NS_RDF
. ' li' ) {
1089 throw new RuntimeException( "<rdf:li> expected but got $elm." );
1092 if ( !isset( $this->mode
[1] ) ) {
1093 // This should never ever ever happen. Checking for it
1095 throw new RuntimeException( 'In mode Li, but no 2xPrevious mode!' );
1098 if ( $this->mode
[1] === self
::MODE_BAGSTRUCT
) {
1099 // This list item contains a compound (STRUCT) value.
1100 array_unshift( $this->mode
, self
::MODE_STRUCT
);
1101 array_unshift( $this->curItem
, $elm );
1102 $this->processingArray
= true;
1104 if ( !isset( $this->curItem
[1] ) ) {
1106 throw new RuntimeException( 'Can not find parent of BAGSTRUCT.' );
1108 list( $curNS, $curTag ) = explode( ' ', $this->curItem
[1] );
1109 $this->ancestorStruct
= isset( $this->items
[$curNS][$curTag]['map_name'] )
1110 ?
$this->items
[$curNS][$curTag]['map_name'] : $curTag;
1112 $this->doAttribs( $attribs );
1114 // Normal BAG or SEQ containing simple values.
1115 array_unshift( $this->mode
, self
::MODE_SIMPLE
);
1116 // need to add curItem[0] on again since one is for the specific item
1117 // and one is for the entire group.
1118 array_unshift( $this->curItem
, $this->curItem
[0] );
1119 $this->processingArray
= true;
1124 * Opening element in MODE_LI_LANG.
1125 * process elements of language alternatives
1128 * <dc:title> <rdf:Alt> <rdf:li xml:lang="x-default">My house
1129 * </rdf:li> </rdf:Alt> </dc:title>
1131 * This method is called when we hit the <rdf:li> element.
1133 * @param string $elm Namespace . ' ' . tag
1134 * @param array $attribs Array of elements (most importantly xml:lang)
1135 * @throws RuntimeException If gets a tag other than <rdf:li> or if no xml:lang
1137 private function startElementModeLiLang( $elm, $attribs ) {
1138 if ( $elm !== self
::NS_RDF
. ' li' ) {
1139 throw new RuntimeException( __METHOD__
. " <rdf:li> expected but got $elm." );
1141 if ( !isset( $attribs[self
::NS_XML
. ' lang'] )
1142 ||
!preg_match( '/^[-A-Za-z0-9]{2,}$/D', $attribs[self
::NS_XML
. ' lang'] )
1144 throw new RuntimeException( __METHOD__
1145 . " <rdf:li> did not contain, or has invalid xml:lang attribute in lang alternative" );
1148 // Lang is case-insensitive.
1149 $this->itemLang
= strtolower( $attribs[self
::NS_XML
. ' lang'] );
1151 // need to add curItem[0] on again since one is for the specific item
1152 // and one is for the entire group.
1153 array_unshift( $this->curItem
, $this->curItem
[0] );
1154 array_unshift( $this->mode
, self
::MODE_SIMPLE
);
1155 $this->processingArray
= true;
1159 * Hits an opening element.
1160 * Generally just calls a helper based on what MODE we're in.
1161 * Also does some initial set up for the wrapper element
1163 * @param XMLParser $parser
1164 * @param string $elm Namespace "<space>" element
1165 * @param array $attribs Attribute name => value
1166 * @throws RuntimeException
1168 function startElement( $parser, $elm, $attribs ) {
1170 if ( $elm === self
::NS_RDF
. ' RDF'
1171 ||
$elm === 'adobe:ns:meta/ xmpmeta'
1172 ||
$elm === 'adobe:ns:meta/ xapmeta'
1176 } elseif ( $elm === self
::NS_RDF
. ' Description' ) {
1177 if ( count( $this->mode
) === 0 ) {
1179 array_unshift( $this->mode
, self
::MODE_INITIAL
);
1181 } elseif ( $elm === self
::NS_RDF
. ' type' ) {
1182 // This doesn't support rdf:type properly.
1183 // In practise I have yet to see a file that
1184 // uses this element, however it is mentioned
1185 // on page 25 of part 1 of the xmp standard.
1187 // also it seems as if exiv2 and exiftool do not support
1188 // this either (That or I misunderstand the standard)
1189 $this->logger
->info( __METHOD__
. ' Encountered <rdf:type> which isn\'t currently supported' );
1192 if ( strpos( $elm, ' ' ) === false ) {
1193 // This probably shouldn't happen.
1194 $this->logger
->info( __METHOD__
. " Encountered <$elm> which has no namespace. Skipping." );
1199 list( $ns, $tag ) = explode( ' ', $elm, 2 );
1201 if ( count( $this->mode
) === 0 ) {
1202 // This should not happen.
1203 throw new RuntimeException( 'Error extracting XMP, '
1204 . "encountered <$elm> with no mode" );
1207 switch ( $this->mode
[0] ) {
1208 case self
::MODE_IGNORE
:
1209 $this->startElementModeIgnore( $elm );
1211 case self
::MODE_SIMPLE
:
1212 $this->startElementModeSimple( $elm, $attribs );
1214 case self
::MODE_INITIAL
:
1215 $this->startElementModeInitial( $ns, $tag, $attribs );
1217 case self
::MODE_STRUCT
:
1218 $this->startElementModeStruct( $ns, $tag, $attribs );
1220 case self
::MODE_BAG
:
1221 case self
::MODE_BAGSTRUCT
:
1222 $this->startElementModeBag( $elm );
1224 case self
::MODE_SEQ
:
1225 $this->startElementModeSeq( $elm );
1227 case self
::MODE_LANG
:
1228 $this->startElementModeLang( $elm );
1230 case self
::MODE_LI_LANG
:
1231 $this->startElementModeLiLang( $elm, $attribs );
1234 $this->startElementModeLi( $elm, $attribs );
1236 case self
::MODE_QDESC
:
1237 $this->startElementModeQDesc( $elm );
1240 throw new RuntimeException( 'StartElement in unknown mode: ' . $this->mode
[0] );
1245 * Process attributes.
1246 * Simple values can be stored as either a tag or attribute
1248 * Often the initial "<rdf:Description>" tag just has all the simple
1249 * properties as attributes.
1251 * @codingStandardsIgnoreStart Long line that cannot be broken
1254 * <rdf:Description rdf:about="" xmlns:exif="http://ns.adobe.com/exif/1.0/" exif:DigitalZoomRatio="0/10">
1256 * @codingStandardsIgnoreEnd
1258 * @param array $attribs Array attribute=>value
1259 * @throws RuntimeException
1261 private function doAttribs( $attribs ) {
1262 // first check for rdf:parseType attribute, as that can change
1263 // how the attributes are interperted.
1265 if ( isset( $attribs[self
::NS_RDF
. ' parseType'] )
1266 && $attribs[self
::NS_RDF
. ' parseType'] === 'Resource'
1267 && $this->mode
[0] === self
::MODE_SIMPLE
1269 // this is equivalent to having an inner rdf:Description
1270 $this->mode
[0] = self
::MODE_QDESC
;
1272 foreach ( $attribs as $name => $val ) {
1273 if ( strpos( $name, ' ' ) === false ) {
1274 // This shouldn't happen, but so far some old software forgets namespace
1276 $this->logger
->info( __METHOD__
. ' Encountered non-namespaced attribute: '
1277 . " $name=\"$val\". Skipping. " );
1280 list( $ns, $tag ) = explode( ' ', $name, 2 );
1281 if ( $ns === self
::NS_RDF
) {
1282 if ( $tag === 'value' ||
$tag === 'resource' ) {
1283 // resource is for url.
1284 // value attribute is a weird way of just putting the contents.
1285 $this->char( $this->xmlParser
, $val );
1287 } elseif ( isset( $this->items
[$ns][$tag] ) ) {
1288 if ( $this->mode
[0] === self
::MODE_SIMPLE
) {
1289 throw new RuntimeException( __METHOD__
1290 . " $ns:$tag found as attribute where not allowed" );
1292 $this->saveValue( $ns, $tag, $val );
1294 $this->logger
->debug( __METHOD__
. " Ignoring unrecognized element <$ns:$tag>." );
1300 * Given an extracted value, save it to results array
1302 * note also uses $this->ancestorStruct and
1303 * $this->processingArray to determine what name to
1304 * save the value under. (in addition to $tag).
1306 * @param string $ns Namespace of tag this is for
1307 * @param string $tag Tag name
1308 * @param string $val Value to save
1310 private function saveValue( $ns, $tag, $val ) {
1312 $info =& $this->items
[$ns][$tag];
1313 $finalName = isset( $info['map_name'] )
1314 ?
$info['map_name'] : $tag;
1315 if ( isset( $info['validate'] ) ) {
1316 if ( is_array( $info['validate'] ) ) {
1317 $validate = $info['validate'];
1319 $validator = new XMPValidate( $this->logger
);
1320 $validate = array( $validator, $info['validate'] );
1323 if ( is_callable( $validate ) ) {
1324 call_user_func_array( $validate, array( $info, &$val, true ) );
1325 // the reasoning behind using &$val instead of using the return value
1326 // is to be consistent between here and validating structures.
1327 if ( is_null( $val ) ) {
1328 $this->logger
->info( __METHOD__
. " <$ns:$tag> failed validation." );
1333 $this->logger
->warning( __METHOD__
. " Validation function for $finalName ("
1334 . $validate[0] . '::' . $validate[1] . '()) is not callable.' );
1338 if ( $this->ancestorStruct
&& $this->processingArray
) {
1339 // Aka both an array and a struct. ( self::MODE_BAGSTRUCT )
1340 $this->results
['xmp-' . $info['map_group']][$this->ancestorStruct
][][$finalName] = $val;
1341 } elseif ( $this->ancestorStruct
) {
1342 $this->results
['xmp-' . $info['map_group']][$this->ancestorStruct
][$finalName] = $val;
1343 } elseif ( $this->processingArray
) {
1344 if ( $this->itemLang
=== false ) {
1346 $this->results
['xmp-' . $info['map_group']][$finalName][] = $val;
1349 $this->results
['xmp-' . $info['map_group']][$finalName][$this->itemLang
] = $val;
1352 $this->results
['xmp-' . $info['map_group']][$finalName] = $val;