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 * free the XML parser.
161 * @note It is unclear to me if we really need to do this ourselves
162 * or if php garbage collection will automatically free the xmlParser
163 * when it is no longer needed.
165 private function destroyXMLParser() {
166 if ( $this->xmlParser
) {
167 xml_parser_free( $this->xmlParser
);
168 $this->xmlParser
= null;
173 * Main use is if a single item has multiple xmp documents describing it.
174 * For example in jpeg's with extendedXMP
176 private function resetXMLParser() {
178 $this->destroyXMLParser();
180 $this->xmlParser
= xml_parser_create_ns( 'UTF-8', ' ' );
181 xml_parser_set_option( $this->xmlParser
, XML_OPTION_CASE_FOLDING
, 0 );
182 xml_parser_set_option( $this->xmlParser
, XML_OPTION_SKIP_WHITE
, 1 );
184 xml_set_element_handler( $this->xmlParser
,
185 array( $this, 'startElement' ),
186 array( $this, 'endElement' ) );
188 xml_set_character_data_handler( $this->xmlParser
, array( $this, 'char' ) );
190 $this->parsable
= self
::PARSABLE_UNKNOWN
;
191 $this->xmlParsableBuffer
= '';
195 * Check if this instance supports using this class
197 public static function isSupported() {
198 return function_exists( 'xml_parser_create_ns' ) && class_exists( 'XMLReader' );
201 /** Get the result array. Do some post-processing before returning
202 * the array, and transform any metadata that is special-cased.
204 * @return array Array of results as an array of arrays suitable for
205 * FormatMetadata::getFormattedData().
207 public function getResults() {
208 // xmp-special is for metadata that affects how stuff
209 // is extracted. For example xmpNote:HasExtendedXMP.
211 // It is also used to handle photoshop:AuthorsPosition
212 // which is weird and really part of another property,
213 // see 2:85 in IPTC. See also pg 21 of IPTC4XMP standard.
214 // The location fields also use it.
216 $data = $this->results
;
218 if ( isset( $data['xmp-special']['AuthorsPosition'] )
219 && is_string( $data['xmp-special']['AuthorsPosition'] )
220 && isset( $data['xmp-general']['Artist'][0] )
222 // Note, if there is more than one creator,
223 // this only applies to first. This also will
224 // only apply to the dc:Creator prop, not the
227 $data['xmp-general']['Artist'][0] =
228 $data['xmp-special']['AuthorsPosition'] . ', '
229 . $data['xmp-general']['Artist'][0];
232 // Go through the LocationShown and LocationCreated
233 // changing it to the non-hierarchal form used by
234 // the other location fields.
236 if ( isset( $data['xmp-special']['LocationShown'][0] )
237 && is_array( $data['xmp-special']['LocationShown'][0] )
239 // the is_array is just paranoia. It should always
241 foreach ( $data['xmp-special']['LocationShown'] as $loc ) {
242 if ( !is_array( $loc ) ) {
243 // To avoid copying over the _type meta-fields.
246 foreach ( $loc as $field => $val ) {
247 $data['xmp-general'][$field . 'Dest'][] = $val;
251 if ( isset( $data['xmp-special']['LocationCreated'][0] )
252 && is_array( $data['xmp-special']['LocationCreated'][0] )
254 // the is_array is just paranoia. It should always
256 foreach ( $data['xmp-special']['LocationCreated'] as $loc ) {
257 if ( !is_array( $loc ) ) {
258 // To avoid copying over the _type meta-fields.
261 foreach ( $loc as $field => $val ) {
262 $data['xmp-general'][$field . 'Created'][] = $val;
267 // We don't want to return the special values, since they're
268 // special and not info to be stored about the file.
269 unset( $data['xmp-special'] );
271 // Convert GPSAltitude to negative if below sea level.
272 if ( isset( $data['xmp-exif']['GPSAltitudeRef'] )
273 && isset( $data['xmp-exif']['GPSAltitude'] )
276 // Must convert to a real before multiplying by -1
277 // XMPValidate guarantees there will always be a '/' in this value.
278 list( $nom, $denom ) = explode( '/', $data['xmp-exif']['GPSAltitude'] );
279 $data['xmp-exif']['GPSAltitude'] = $nom / $denom;
281 if ( $data['xmp-exif']['GPSAltitudeRef'] == '1' ) {
282 $data['xmp-exif']['GPSAltitude'] *= -1;
284 unset( $data['xmp-exif']['GPSAltitudeRef'] );
291 * Main function to call to parse XMP. Use getResults to
294 * Also catches any errors during processing, writes them to
295 * debug log, blanks result array and returns false.
297 * @param string $content XMP data
298 * @param bool $allOfIt If this is all the data (true) or if its split up (false). Default true
299 * @throws RuntimeException
300 * @return bool Success.
302 public function parse( $content, $allOfIt = true ) {
303 if ( !$this->xmlParser
) {
304 $this->resetXMLParser();
308 // detect encoding by looking for BOM which is supposed to be in processing instruction.
309 // see page 12 of http://www.adobe.com/devnet/xmp/pdfs/XMPSpecificationPart3.pdf
310 if ( !$this->charset
) {
312 if ( preg_match( '/\xEF\xBB\xBF|\xFE\xFF|\x00\x00\xFE\xFF|\xFF\xFE\x00\x00|\xFF\xFE/',
317 $this->charset
= 'UTF-16BE';
320 $this->charset
= 'UTF-16LE';
322 case "\x00\x00\xFE\xFF":
323 $this->charset
= 'UTF-32BE';
325 case "\xFF\xFE\x00\x00":
326 $this->charset
= 'UTF-32LE';
329 $this->charset
= 'UTF-8';
332 //this should be impossible to get to
333 throw new RuntimeException( "Invalid BOM" );
336 // standard specifically says, if no bom assume utf-8
337 $this->charset
= 'UTF-8';
340 if ( $this->charset
!== 'UTF-8' ) {
341 //don't convert if already utf-8
342 MediaWiki\
suppressWarnings();
343 $content = iconv( $this->charset
, 'UTF-8//IGNORE', $content );
344 MediaWiki\restoreWarnings
();
347 // Ensure the XMP block does not have an xml doctype declaration, which
348 // could declare entities unsafe to parse with xml_parse (T85848/T71210).
349 if ( $this->parsable
!== self
::PARSABLE_OK
) {
350 if ( $this->parsable
=== self
::PARSABLE_NO
) {
351 throw new RuntimeException( 'Unsafe doctype declaration in XML.' );
354 $content = $this->xmlParsableBuffer
. $content;
355 if ( !$this->checkParseSafety( $content ) ) {
356 if ( !$allOfIt && $this->parsable
!== self
::PARSABLE_NO
) {
357 // parse wasn't Unsuccessful yet, so return true
361 $msg = ( $this->parsable
=== self
::PARSABLE_NO
) ?
362 'Unsafe doctype declaration in XML.' :
363 'No root element found in XML.';
364 throw new RuntimeException( $msg );
368 $ok = xml_parse( $this->xmlParser
, $content, $allOfIt );
370 $code = xml_get_error_code( $this->xmlParser
);
371 $error = xml_error_string( $code );
372 $line = xml_get_current_line_number( $this->xmlParser
);
373 $col = xml_get_current_column_number( $this->xmlParser
);
374 $offset = xml_get_current_byte_index( $this->xmlParser
);
376 $this->logger
->warning(
377 '{method} : Error reading XMP content: {error} ' .
378 '(line: {line} column: {column} byte offset: {offset})',
380 'method' => __METHOD__
,
381 'error_code' => $code,
386 'content' => $content,
388 $this->results
= array(); // blank if error.
389 $this->destroyXMLParser();
392 } catch ( Exception
$e ) {
393 $this->logger
->warning(
394 '{method} Exception caught while parsing: ' . $e->getMessage(),
396 'method' => __METHOD__
,
398 'content' => $content,
401 $this->results
= array();
404 $this->destroyXMLParser();
409 $this->destroyXMLParser();
415 /** Entry point for XMPExtended blocks in jpeg files
417 * @todo In serious need of testing
418 * @see http://www.adobe.ge/devnet/xmp/pdfs/XMPSpecificationPart3.pdf XMP spec part 3 page 20
419 * @param string $content XMPExtended block minus the namespace signature
420 * @return bool If it succeeded.
422 public function parseExtended( $content ) {
423 // @todo FIXME: This is untested. Hard to find example files
424 // or programs that make such files..
425 $guid = substr( $content, 0, 32 );
426 if ( !isset( $this->results
['xmp-special']['HasExtendedXMP'] )
427 ||
$this->results
['xmp-special']['HasExtendedXMP'] !== $guid
429 $this->logger
->info( __METHOD__
.
430 " Ignoring XMPExtended block due to wrong guid (guid= '$guid')" );
434 $len = unpack( 'Nlength/Noffset', substr( $content, 32, 8 ) );
436 if ( !$len ||
$len['length'] < 4 ||
$len['offset'] < 0 ||
$len['offset'] > $len['length'] ) {
437 $this->logger
->info( __METHOD__
. 'Error reading extended XMP block, invalid length or offset.' );
442 // we're not very robust here. we should accept it in the wrong order.
443 // To quote the XMP standard:
444 // "A JPEG writer should write the ExtendedXMP marker segments in order,
445 // immediately following the StandardXMP. However, the JPEG standard
446 // does not require preservation of marker segment order. A robust JPEG
447 // reader should tolerate the marker segments in any order."
449 // otoh the probability that an image will have more than 128k of
450 // metadata is rather low... so the probability that it will have
451 // > 128k, and be in the wrong order is very low...
453 if ( $len['offset'] !== $this->extendedXMPOffset
) {
454 $this->logger
->info( __METHOD__
. 'Ignoring XMPExtended block due to wrong order. (Offset was '
455 . $len['offset'] . ' but expected ' . $this->extendedXMPOffset
. ')' );
460 if ( $len['offset'] === 0 ) {
461 // if we're starting the extended block, we've probably already
462 // done the XMPStandard block, so reset.
463 $this->resetXMLParser();
466 $this->extendedXMPOffset +
= $len['length'];
468 $actualContent = substr( $content, 40 );
470 if ( $this->extendedXMPOffset
=== strlen( $actualContent ) ) {
476 $this->logger
->debug( __METHOD__
. 'Parsing a XMPExtended block' );
478 return $this->parse( $actualContent, $atEnd );
482 * Character data handler
483 * Called whenever character data is found in the xmp document.
485 * does nothing if we're in MODE_IGNORE or if the data is whitespace
486 * throws an error if we're not in MODE_SIMPLE (as we're not allowed to have character
487 * data in the other modes).
489 * As an example, this happens when we encounter XMP like:
490 * <exif:DigitalZoomRatio>0/10</exif:DigitalZoomRatio>
491 * and are processing the 0/10 bit.
493 * @param XMLParser $parser XMLParser reference to the xml parser
494 * @param string $data Character data
495 * @throws RuntimeException On invalid data
497 function char( $parser, $data ) {
499 $data = trim( $data );
500 if ( trim( $data ) === "" ) {
504 if ( !isset( $this->mode
[0] ) ) {
505 throw new RuntimeException( 'Unexpected character data before first rdf:Description element' );
508 if ( $this->mode
[0] === self
::MODE_IGNORE
) {
512 if ( $this->mode
[0] !== self
::MODE_SIMPLE
513 && $this->mode
[0] !== self
::MODE_QDESC
515 throw new RuntimeException( 'character data where not expected. (mode ' . $this->mode
[0] . ')' );
518 // to check, how does this handle w.s.
519 if ( $this->charContent
=== false ) {
520 $this->charContent
= $data;
522 $this->charContent
.= $data;
527 * Check if a block of XML is safe to pass to xml_parse, i.e. doesn't
528 * contain a doctype declaration which could contain a dos attack if we
529 * parse it and expand internal entities (T85848).
531 * @param string $content xml string to check for parse safety
532 * @return bool true if the xml is safe to parse, false otherwise
534 private function checkParseSafety( $content ) {
535 $reader = new XMLReader();
538 // For XMLReader to parse incomplete/invalid XML, it has to be open()'ed
539 // instead of using XML().
541 'data://text/plain,' . urlencode( $content ),
543 LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_NONET
546 $oldDisable = libxml_disable_entity_loader( true );
547 /** @noinspection PhpUnusedLocalVariableInspection */
548 $reset = new ScopedCallback(
549 'libxml_disable_entity_loader',
552 $reader->setParserProperty( XMLReader
::SUBST_ENTITIES
, false );
554 // Even with LIBXML_NOWARNING set, XMLReader::read gives a warning
555 // when parsing truncated XML, which causes unit tests to fail.
556 MediaWiki\
suppressWarnings();
557 while ( $reader->read() ) {
558 if ( $reader->nodeType
=== XMLReader
::ELEMENT
) {
559 // Reached the first element without hitting a doctype declaration
560 $this->parsable
= self
::PARSABLE_OK
;
564 if ( $reader->nodeType
=== XMLReader
::DOC_TYPE
) {
565 $this->parsable
= self
::PARSABLE_NO
;
570 MediaWiki\restoreWarnings
();
572 if ( !is_null( $result ) ) {
576 // Reached the end of the parsable xml without finding an element
577 // or doctype. Buffer and try again.
578 $this->parsable
= self
::PARSABLE_BUFFERING
;
579 $this->xmlParsableBuffer
= $content;
583 /** When we hit a closing element in MODE_IGNORE
584 * Check to see if this is the element we started to ignore,
585 * in which case we get out of MODE_IGNORE
587 * @param string $elm Namespace of element followed by a space and then tag name of element.
589 private function endElementModeIgnore( $elm ) {
590 if ( $this->curItem
[0] === $elm ) {
591 array_shift( $this->curItem
);
592 array_shift( $this->mode
);
597 * Hit a closing element when in MODE_SIMPLE.
598 * This generally means that we finished processing a
599 * property value, and now have to save the result to the
602 * For example, when processing:
603 * <exif:DigitalZoomRatio>0/10</exif:DigitalZoomRatio>
604 * this deals with when we hit </exif:DigitalZoomRatio>.
606 * Or it could be if we hit the end element of a property
607 * of a compound data structure (like a member of an array).
609 * @param string $elm Namespace, space, and tag name.
611 private function endElementModeSimple( $elm ) {
612 if ( $this->charContent
!== false ) {
613 if ( $this->processingArray
) {
614 // if we're processing an array, use the original element
615 // name instead of rdf:li.
616 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
618 list( $ns, $tag ) = explode( ' ', $elm, 2 );
620 $this->saveValue( $ns, $tag, $this->charContent
);
622 $this->charContent
= false; // reset
624 array_shift( $this->curItem
);
625 array_shift( $this->mode
);
629 * Hit a closing element in MODE_STRUCT, MODE_SEQ, MODE_BAG
630 * generally means we've finished processing a nested structure.
631 * resets some internal variables to indicate that.
633 * Note this means we hit the closing element not the "</rdf:Seq>".
635 * @par For example, when processing:
637 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
638 * </rdf:Seq> </exif:ISOSpeedRatings>
641 * This method is called when we hit the "</exif:ISOSpeedRatings>" tag.
643 * @param string $elm Namespace . space . tag name.
644 * @throws RuntimeException
646 private function endElementNested( $elm ) {
648 /* cur item must be the same as $elm, unless if in MODE_STRUCT
649 in which case it could also be rdf:Description */
650 if ( $this->curItem
[0] !== $elm
651 && !( $elm === self
::NS_RDF
. ' Description'
652 && $this->mode
[0] === self
::MODE_STRUCT
)
654 throw new RuntimeException( "nesting mismatch. got a </$elm> but expected a </" .
655 $this->curItem
[0] . '>' );
658 // Validate structures.
659 list( $ns, $tag ) = explode( ' ', $elm, 2 );
660 if ( isset( $this->items
[$ns][$tag]['validate'] ) ) {
661 $info =& $this->items
[$ns][$tag];
662 $finalName = isset( $info['map_name'] )
663 ?
$info['map_name'] : $tag;
665 if ( is_array( $info['validate'] ) ) {
666 $validate = $info['validate'];
668 $validator = new XMPValidate( $this->logger
);
669 $validate = array( $validator, $info['validate'] );
672 if ( !isset( $this->results
['xmp-' . $info['map_group']][$finalName] ) ) {
673 // This can happen if all the members of the struct failed validation.
674 $this->logger
->debug( __METHOD__
. " <$ns:$tag> has no valid members." );
675 } elseif ( is_callable( $validate ) ) {
676 $val =& $this->results
['xmp-' . $info['map_group']][$finalName];
677 call_user_func_array( $validate, array( $info, &$val, false ) );
678 if ( is_null( $val ) ) {
679 // the idea being the validation function will unset the variable if
681 $this->logger
->info( __METHOD__
. " <$ns:$tag> failed validation." );
682 unset( $this->results
['xmp-' . $info['map_group']][$finalName] );
685 $this->logger
->warning( __METHOD__
. " Validation function for $finalName ("
686 . $validate[0] . '::' . $validate[1] . '()) is not callable.' );
690 array_shift( $this->curItem
);
691 array_shift( $this->mode
);
692 $this->ancestorStruct
= false;
693 $this->processingArray
= false;
694 $this->itemLang
= false;
698 * Hit a closing element in MODE_LI (either rdf:Seq, or rdf:Bag )
699 * Add information about what type of element this is.
701 * Note we still have to hit the outer "</property>"
703 * @par For example, when processing:
705 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
706 * </rdf:Seq> </exif:ISOSpeedRatings>
709 * This method is called when we hit the "</rdf:Seq>".
710 * (For comparison, we call endElementModeSimple when we
711 * hit the "</rdf:li>")
713 * @param string $elm Namespace . ' ' . element name
714 * @throws RuntimeException
716 private function endElementModeLi( $elm ) {
718 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
719 $info = $this->items
[$ns][$tag];
720 $finalName = isset( $info['map_name'] )
721 ?
$info['map_name'] : $tag;
723 array_shift( $this->mode
);
725 if ( !isset( $this->results
['xmp-' . $info['map_group']][$finalName] ) ) {
726 $this->logger
->debug( __METHOD__
. " Empty compund element $finalName." );
731 if ( $elm === self
::NS_RDF
. ' Seq' ) {
732 $this->results
['xmp-' . $info['map_group']][$finalName]['_type'] = 'ol';
733 } elseif ( $elm === self
::NS_RDF
. ' Bag' ) {
734 $this->results
['xmp-' . $info['map_group']][$finalName]['_type'] = 'ul';
735 } elseif ( $elm === self
::NS_RDF
. ' Alt' ) {
736 // extra if needed as you could theoretically have a non-language alt.
737 if ( $info['mode'] === self
::MODE_LANG
) {
738 $this->results
['xmp-' . $info['map_group']][$finalName]['_type'] = 'lang';
741 throw new RuntimeException( __METHOD__
. " expected </rdf:seq> or </rdf:bag> but instead got $elm." );
746 * End element while in MODE_QDESC
747 * mostly when ending an element when we have a simple value
748 * that has qualifiers.
750 * Qualifiers aren't all that common, and we don't do anything
753 * @param string $elm Namespace and element
755 private function endElementModeQDesc( $elm ) {
757 if ( $elm === self
::NS_RDF
. ' value' ) {
758 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
759 $this->saveValue( $ns, $tag, $this->charContent
);
763 array_shift( $this->mode
);
764 array_shift( $this->curItem
);
769 * Handler for hitting a closing element.
771 * generally just calls a helper function depending on what
774 * Ignores the outer wrapping elements that are optional in
775 * xmp and have no meaning.
777 * @param XMLParser $parser
778 * @param string $elm Namespace . ' ' . element name
779 * @throws RuntimeException
781 function endElement( $parser, $elm ) {
782 if ( $elm === ( self
::NS_RDF
. ' RDF' )
783 ||
$elm === 'adobe:ns:meta/ xmpmeta'
784 ||
$elm === 'adobe:ns:meta/ xapmeta'
790 if ( $elm === self
::NS_RDF
. ' type' ) {
791 // these aren't really supported properly yet.
792 // However, it appears they almost never used.
793 $this->logger
->info( __METHOD__
. ' encountered <rdf:type>' );
796 if ( strpos( $elm, ' ' ) === false ) {
797 // This probably shouldn't happen.
798 // However, there is a bug in an adobe product
799 // that forgets the namespace on some things.
800 // (Luckily they are unimportant things).
801 $this->logger
->info( __METHOD__
. " Encountered </$elm> which has no namespace. Skipping." );
806 if ( count( $this->mode
[0] ) === 0 ) {
807 // This should never ever happen and means
808 // there is a pretty major bug in this class.
809 throw new RuntimeException( 'Encountered end element with no mode' );
812 if ( count( $this->curItem
) == 0 && $this->mode
[0] !== self
::MODE_INITIAL
) {
813 // just to be paranoid. Should always have a curItem, except for initially
814 // (aka during MODE_INITAL).
815 throw new RuntimeException( "Hit end element </$elm> but no curItem" );
818 switch ( $this->mode
[0] ) {
819 case self
::MODE_IGNORE
:
820 $this->endElementModeIgnore( $elm );
822 case self
::MODE_SIMPLE
:
823 $this->endElementModeSimple( $elm );
825 case self
::MODE_STRUCT
:
828 case self
::MODE_LANG
:
829 case self
::MODE_BAGSTRUCT
:
830 $this->endElementNested( $elm );
832 case self
::MODE_INITIAL
:
833 if ( $elm === self
::NS_RDF
. ' Description' ) {
834 array_shift( $this->mode
);
836 throw new RuntimeException( 'Element ended unexpectedly while in MODE_INITIAL' );
840 case self
::MODE_LI_LANG
:
841 $this->endElementModeLi( $elm );
843 case self
::MODE_QDESC
:
844 $this->endElementModeQDesc( $elm );
847 $this->logger
->warning( __METHOD__
. " no mode (elm = $elm)" );
853 * Hit an opening element while in MODE_IGNORE
855 * XMP is extensible, so ignore any tag we don't understand.
857 * Mostly ignores, unless we encounter the element that we are ignoring.
858 * in which case we add it to the item stack, so we can ignore things
859 * that are nested, correctly.
861 * @param string $elm Namespace . ' ' . tag name
863 private function startElementModeIgnore( $elm ) {
864 if ( $elm === $this->curItem
[0] ) {
865 array_unshift( $this->curItem
, $elm );
866 array_unshift( $this->mode
, self
::MODE_IGNORE
);
871 * Start element in MODE_BAG (unordered array)
872 * this should always be <rdf:Bag>
874 * @param string $elm Namespace . ' ' . tag
875 * @throws RuntimeException If we have an element that's not <rdf:Bag>
877 private function startElementModeBag( $elm ) {
878 if ( $elm === self
::NS_RDF
. ' Bag' ) {
879 array_unshift( $this->mode
, self
::MODE_LI
);
881 throw new RuntimeException( "Expected <rdf:Bag> but got $elm." );
886 * Start element in MODE_SEQ (ordered array)
887 * this should always be <rdf:Seq>
889 * @param string $elm Namespace . ' ' . tag
890 * @throws RuntimeException If we have an element that's not <rdf:Seq>
892 private function startElementModeSeq( $elm ) {
893 if ( $elm === self
::NS_RDF
. ' Seq' ) {
894 array_unshift( $this->mode
, self
::MODE_LI
);
895 } elseif ( $elm === self
::NS_RDF
. ' Bag' ) {
897 $this->logger
->info( __METHOD__
. ' Expected an rdf:Seq, but got an rdf:Bag. Pretending'
898 . ' it is a Seq, since some buggy software is known to screw this up.' );
899 array_unshift( $this->mode
, self
::MODE_LI
);
901 throw new RuntimeException( "Expected <rdf:Seq> but got $elm." );
906 * Start element in MODE_LANG (language alternative)
907 * this should always be <rdf:Alt>
909 * This tag tends to be used for metadata like describe this
910 * picture, which can be translated into multiple languages.
912 * XMP supports non-linguistic alternative selections,
913 * which are really only used for thumbnails, which
914 * we don't care about.
916 * @param string $elm Namespace . ' ' . tag
917 * @throws RuntimeException If we have an element that's not <rdf:Alt>
919 private function startElementModeLang( $elm ) {
920 if ( $elm === self
::NS_RDF
. ' Alt' ) {
921 array_unshift( $this->mode
, self
::MODE_LI_LANG
);
923 throw new RuntimeException( "Expected <rdf:Seq> but got $elm." );
928 * Handle an opening element when in MODE_SIMPLE
930 * This should not happen often. This is for if a simple element
931 * already opened has a child element. Could happen for a
935 * <exif:DigitalZoomRatio><rdf:Description><rdf:value>0/10</rdf:value>
936 * <foo:someQualifier>Bar</foo:someQualifier> </rdf:Description>
937 * </exif:DigitalZoomRatio>
939 * This method is called when processing the <rdf:Description> element
941 * @param string $elm Namespace and tag names separated by space.
942 * @param array $attribs Attributes of the element.
943 * @throws RuntimeException
945 private function startElementModeSimple( $elm, $attribs ) {
946 if ( $elm === self
::NS_RDF
. ' Description' ) {
947 // If this value has qualifiers
948 array_unshift( $this->mode
, self
::MODE_QDESC
);
949 array_unshift( $this->curItem
, $this->curItem
[0] );
951 if ( isset( $attribs[self
::NS_RDF
. ' value'] ) ) {
952 list( $ns, $tag ) = explode( ' ', $this->curItem
[0], 2 );
953 $this->saveValue( $ns, $tag, $attribs[self
::NS_RDF
. ' value'] );
955 } elseif ( $elm === self
::NS_RDF
. ' value' ) {
956 // This should not be here.
957 throw new RuntimeException( __METHOD__
. ' Encountered <rdf:value> where it was unexpected.' );
959 // something else we don't recognize, like a qualifier maybe.
960 $this->logger
->info( __METHOD__
.
961 " Encountered element <$elm> where only expecting character data as value of " .
963 array_unshift( $this->mode
, self
::MODE_IGNORE
);
964 array_unshift( $this->curItem
, $elm );
969 * Start an element when in MODE_QDESC.
970 * This generally happens when a simple element has an inner
971 * rdf:Description to hold qualifier elements.
974 * <exif:DigitalZoomRatio><rdf:Description><rdf:value>0/10</rdf:value>
975 * <foo:someQualifier>Bar</foo:someQualifier> </rdf:Description>
976 * </exif:DigitalZoomRatio>
977 * Called when processing the <rdf:value> or <foo:someQualifier>.
979 * @param string $elm Namespace and tag name separated by a space.
982 private function startElementModeQDesc( $elm ) {
983 if ( $elm === self
::NS_RDF
. ' value' ) {
984 return; // do nothing
986 // otherwise its a qualifier, which we ignore
987 array_unshift( $this->mode
, self
::MODE_IGNORE
);
988 array_unshift( $this->curItem
, $elm );
993 * Starting an element when in MODE_INITIAL
994 * This usually happens when we hit an element inside
995 * the outer rdf:Description
997 * This is generally where most properties start.
999 * @param string $ns Namespace
1000 * @param string $tag Tag name (without namespace prefix)
1001 * @param array $attribs Array of attributes
1002 * @throws RuntimeException
1004 private function startElementModeInitial( $ns, $tag, $attribs ) {
1005 if ( $ns !== self
::NS_RDF
) {
1007 if ( isset( $this->items
[$ns][$tag] ) ) {
1008 if ( isset( $this->items
[$ns][$tag]['structPart'] ) ) {
1009 // If this element is supposed to appear only as
1010 // a child of a structure, but appears here (not as
1011 // a child of a struct), then something weird is
1012 // happening, so ignore this element and its children.
1014 $this->logger
->warning( "Encountered <$ns:$tag> outside"
1015 . " of its expected parent. Ignoring." );
1017 array_unshift( $this->mode
, self
::MODE_IGNORE
);
1018 array_unshift( $this->curItem
, $ns . ' ' . $tag );
1022 $mode = $this->items
[$ns][$tag]['mode'];
1023 array_unshift( $this->mode
, $mode );
1024 array_unshift( $this->curItem
, $ns . ' ' . $tag );
1025 if ( $mode === self
::MODE_STRUCT
) {
1026 $this->ancestorStruct
= isset( $this->items
[$ns][$tag]['map_name'] )
1027 ?
$this->items
[$ns][$tag]['map_name'] : $tag;
1029 if ( $this->charContent
!== false ) {
1031 // Should not happen in valid XMP.
1032 throw new RuntimeException( 'tag nested in non-whitespace characters.' );
1035 // This element is not on our list of allowed elements so ignore.
1036 $this->logger
->debug( __METHOD__
. " Ignoring unrecognized element <$ns:$tag>." );
1037 array_unshift( $this->mode
, self
::MODE_IGNORE
);
1038 array_unshift( $this->curItem
, $ns . ' ' . $tag );
1043 // process attributes
1044 $this->doAttribs( $attribs );
1048 * Hit an opening element when in a Struct (MODE_STRUCT)
1049 * This is generally for fields of a compound property.
1051 * Example of a struct (abbreviated; flash has more properties):
1053 * <exif:Flash> <rdf:Description> <exif:Fired>True</exif:Fired>
1054 * <exif:Mode>1</exif:Mode></rdf:Description></exif:Flash>
1058 * <exif:Flash rdf:parseType='Resource'> <exif:Fired>True</exif:Fired>
1059 * <exif:Mode>1</exif:Mode></exif:Flash>
1061 * @param string $ns Namespace
1062 * @param string $tag Tag name (no ns)
1063 * @param array $attribs Array of attribs w/ values.
1064 * @throws RuntimeException
1066 private function startElementModeStruct( $ns, $tag, $attribs ) {
1067 if ( $ns !== self
::NS_RDF
) {
1069 if ( isset( $this->items
[$ns][$tag] ) ) {
1070 if ( isset( $this->items
[$ns][$this->ancestorStruct
]['children'] )
1071 && !isset( $this->items
[$ns][$this->ancestorStruct
]['children'][$tag] )
1073 // This assumes that we don't have inter-namespace nesting
1074 // which we don't in all the properties we're interested in.
1075 throw new RuntimeException( " <$tag> appeared nested in <" . $this->ancestorStruct
1076 . "> where it is not allowed." );
1078 array_unshift( $this->mode
, $this->items
[$ns][$tag]['mode'] );
1079 array_unshift( $this->curItem
, $ns . ' ' . $tag );
1080 if ( $this->charContent
!== false ) {
1082 // Should not happen in valid XMP.
1083 throw new RuntimeException( "tag <$tag> nested in non-whitespace characters (" .
1084 $this->charContent
. ")." );
1087 array_unshift( $this->mode
, self
::MODE_IGNORE
);
1088 array_unshift( $this->curItem
, $elm );
1094 if ( $ns === self
::NS_RDF
&& $tag === 'Description' ) {
1095 $this->doAttribs( $attribs );
1096 array_unshift( $this->mode
, self
::MODE_STRUCT
);
1097 array_unshift( $this->curItem
, $this->curItem
[0] );
1102 * opening element in MODE_LI
1103 * process elements of arrays.
1106 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
1107 * </rdf:Seq> </exif:ISOSpeedRatings>
1108 * This method is called when we hit the <rdf:li> element.
1110 * @param string $elm Namespace . ' ' . tagname
1111 * @param array $attribs Attributes. (needed for BAGSTRUCTS)
1112 * @throws RuntimeException If gets a tag other than <rdf:li>
1114 private function startElementModeLi( $elm, $attribs ) {
1115 if ( ( $elm ) !== self
::NS_RDF
. ' li' ) {
1116 throw new RuntimeException( "<rdf:li> expected but got $elm." );
1119 if ( !isset( $this->mode
[1] ) ) {
1120 // This should never ever ever happen. Checking for it
1122 throw new RuntimeException( 'In mode Li, but no 2xPrevious mode!' );
1125 if ( $this->mode
[1] === self
::MODE_BAGSTRUCT
) {
1126 // This list item contains a compound (STRUCT) value.
1127 array_unshift( $this->mode
, self
::MODE_STRUCT
);
1128 array_unshift( $this->curItem
, $elm );
1129 $this->processingArray
= true;
1131 if ( !isset( $this->curItem
[1] ) ) {
1133 throw new RuntimeException( 'Can not find parent of BAGSTRUCT.' );
1135 list( $curNS, $curTag ) = explode( ' ', $this->curItem
[1] );
1136 $this->ancestorStruct
= isset( $this->items
[$curNS][$curTag]['map_name'] )
1137 ?
$this->items
[$curNS][$curTag]['map_name'] : $curTag;
1139 $this->doAttribs( $attribs );
1141 // Normal BAG or SEQ containing simple values.
1142 array_unshift( $this->mode
, self
::MODE_SIMPLE
);
1143 // need to add curItem[0] on again since one is for the specific item
1144 // and one is for the entire group.
1145 array_unshift( $this->curItem
, $this->curItem
[0] );
1146 $this->processingArray
= true;
1151 * Opening element in MODE_LI_LANG.
1152 * process elements of language alternatives
1155 * <dc:title> <rdf:Alt> <rdf:li xml:lang="x-default">My house
1156 * </rdf:li> </rdf:Alt> </dc:title>
1158 * This method is called when we hit the <rdf:li> element.
1160 * @param string $elm Namespace . ' ' . tag
1161 * @param array $attribs Array of elements (most importantly xml:lang)
1162 * @throws RuntimeException If gets a tag other than <rdf:li> or if no xml:lang
1164 private function startElementModeLiLang( $elm, $attribs ) {
1165 if ( $elm !== self
::NS_RDF
. ' li' ) {
1166 throw new RuntimeException( __METHOD__
. " <rdf:li> expected but got $elm." );
1168 if ( !isset( $attribs[self
::NS_XML
. ' lang'] )
1169 ||
!preg_match( '/^[-A-Za-z0-9]{2,}$/D', $attribs[self
::NS_XML
. ' lang'] )
1171 throw new RuntimeException( __METHOD__
1172 . " <rdf:li> did not contain, or has invalid xml:lang attribute in lang alternative" );
1175 // Lang is case-insensitive.
1176 $this->itemLang
= strtolower( $attribs[self
::NS_XML
. ' lang'] );
1178 // need to add curItem[0] on again since one is for the specific item
1179 // and one is for the entire group.
1180 array_unshift( $this->curItem
, $this->curItem
[0] );
1181 array_unshift( $this->mode
, self
::MODE_SIMPLE
);
1182 $this->processingArray
= true;
1186 * Hits an opening element.
1187 * Generally just calls a helper based on what MODE we're in.
1188 * Also does some initial set up for the wrapper element
1190 * @param XMLParser $parser
1191 * @param string $elm Namespace "<space>" element
1192 * @param array $attribs Attribute name => value
1193 * @throws RuntimeException
1195 function startElement( $parser, $elm, $attribs ) {
1197 if ( $elm === self
::NS_RDF
. ' RDF'
1198 ||
$elm === 'adobe:ns:meta/ xmpmeta'
1199 ||
$elm === 'adobe:ns:meta/ xapmeta'
1203 } elseif ( $elm === self
::NS_RDF
. ' Description' ) {
1204 if ( count( $this->mode
) === 0 ) {
1206 array_unshift( $this->mode
, self
::MODE_INITIAL
);
1208 } elseif ( $elm === self
::NS_RDF
. ' type' ) {
1209 // This doesn't support rdf:type properly.
1210 // In practise I have yet to see a file that
1211 // uses this element, however it is mentioned
1212 // on page 25 of part 1 of the xmp standard.
1214 // also it seems as if exiv2 and exiftool do not support
1215 // this either (That or I misunderstand the standard)
1216 $this->logger
->info( __METHOD__
. ' Encountered <rdf:type> which isn\'t currently supported' );
1219 if ( strpos( $elm, ' ' ) === false ) {
1220 // This probably shouldn't happen.
1221 $this->logger
->info( __METHOD__
. " Encountered <$elm> which has no namespace. Skipping." );
1226 list( $ns, $tag ) = explode( ' ', $elm, 2 );
1228 if ( count( $this->mode
) === 0 ) {
1229 // This should not happen.
1230 throw new RuntimeException( 'Error extracting XMP, '
1231 . "encountered <$elm> with no mode" );
1234 switch ( $this->mode
[0] ) {
1235 case self
::MODE_IGNORE
:
1236 $this->startElementModeIgnore( $elm );
1238 case self
::MODE_SIMPLE
:
1239 $this->startElementModeSimple( $elm, $attribs );
1241 case self
::MODE_INITIAL
:
1242 $this->startElementModeInitial( $ns, $tag, $attribs );
1244 case self
::MODE_STRUCT
:
1245 $this->startElementModeStruct( $ns, $tag, $attribs );
1247 case self
::MODE_BAG
:
1248 case self
::MODE_BAGSTRUCT
:
1249 $this->startElementModeBag( $elm );
1251 case self
::MODE_SEQ
:
1252 $this->startElementModeSeq( $elm );
1254 case self
::MODE_LANG
:
1255 $this->startElementModeLang( $elm );
1257 case self
::MODE_LI_LANG
:
1258 $this->startElementModeLiLang( $elm, $attribs );
1261 $this->startElementModeLi( $elm, $attribs );
1263 case self
::MODE_QDESC
:
1264 $this->startElementModeQDesc( $elm );
1267 throw new RuntimeException( 'StartElement in unknown mode: ' . $this->mode
[0] );
1272 * Process attributes.
1273 * Simple values can be stored as either a tag or attribute
1275 * Often the initial "<rdf:Description>" tag just has all the simple
1276 * properties as attributes.
1278 * @codingStandardsIgnoreStart Long line that cannot be broken
1281 * <rdf:Description rdf:about="" xmlns:exif="http://ns.adobe.com/exif/1.0/" exif:DigitalZoomRatio="0/10">
1283 * @codingStandardsIgnoreEnd
1285 * @param array $attribs Array attribute=>value
1286 * @throws RuntimeException
1288 private function doAttribs( $attribs ) {
1289 // first check for rdf:parseType attribute, as that can change
1290 // how the attributes are interperted.
1292 if ( isset( $attribs[self
::NS_RDF
. ' parseType'] )
1293 && $attribs[self
::NS_RDF
. ' parseType'] === 'Resource'
1294 && $this->mode
[0] === self
::MODE_SIMPLE
1296 // this is equivalent to having an inner rdf:Description
1297 $this->mode
[0] = self
::MODE_QDESC
;
1299 foreach ( $attribs as $name => $val ) {
1300 if ( strpos( $name, ' ' ) === false ) {
1301 // This shouldn't happen, but so far some old software forgets namespace
1303 $this->logger
->info( __METHOD__
. ' Encountered non-namespaced attribute: '
1304 . " $name=\"$val\". Skipping. " );
1307 list( $ns, $tag ) = explode( ' ', $name, 2 );
1308 if ( $ns === self
::NS_RDF
) {
1309 if ( $tag === 'value' ||
$tag === 'resource' ) {
1310 // resource is for url.
1311 // value attribute is a weird way of just putting the contents.
1312 $this->char( $this->xmlParser
, $val );
1314 } elseif ( isset( $this->items
[$ns][$tag] ) ) {
1315 if ( $this->mode
[0] === self
::MODE_SIMPLE
) {
1316 throw new RuntimeException( __METHOD__
1317 . " $ns:$tag found as attribute where not allowed" );
1319 $this->saveValue( $ns, $tag, $val );
1321 $this->logger
->debug( __METHOD__
. " Ignoring unrecognized element <$ns:$tag>." );
1327 * Given an extracted value, save it to results array
1329 * note also uses $this->ancestorStruct and
1330 * $this->processingArray to determine what name to
1331 * save the value under. (in addition to $tag).
1333 * @param string $ns Namespace of tag this is for
1334 * @param string $tag Tag name
1335 * @param string $val Value to save
1337 private function saveValue( $ns, $tag, $val ) {
1339 $info =& $this->items
[$ns][$tag];
1340 $finalName = isset( $info['map_name'] )
1341 ?
$info['map_name'] : $tag;
1342 if ( isset( $info['validate'] ) ) {
1343 if ( is_array( $info['validate'] ) ) {
1344 $validate = $info['validate'];
1346 $validator = new XMPValidate( $this->logger
);
1347 $validate = array( $validator, $info['validate'] );
1350 if ( is_callable( $validate ) ) {
1351 call_user_func_array( $validate, array( $info, &$val, true ) );
1352 // the reasoning behind using &$val instead of using the return value
1353 // is to be consistent between here and validating structures.
1354 if ( is_null( $val ) ) {
1355 $this->logger
->info( __METHOD__
. " <$ns:$tag> failed validation." );
1360 $this->logger
->warning( __METHOD__
. " Validation function for $finalName ("
1361 . $validate[0] . '::' . $validate[1] . '()) is not callable.' );
1365 if ( $this->ancestorStruct
&& $this->processingArray
) {
1366 // Aka both an array and a struct. ( self::MODE_BAGSTRUCT )
1367 $this->results
['xmp-' . $info['map_group']][$this->ancestorStruct
][][$finalName] = $val;
1368 } elseif ( $this->ancestorStruct
) {
1369 $this->results
['xmp-' . $info['map_group']][$this->ancestorStruct
][$finalName] = $val;
1370 } elseif ( $this->processingArray
) {
1371 if ( $this->itemLang
=== false ) {
1373 $this->results
['xmp-' . $info['map_group']][$finalName][] = $val;
1376 $this->results
['xmp-' . $info['map_group']][$finalName][$this->itemLang
] = $val;
1379 $this->results
['xmp-' . $info['map_group']][$finalName] = $val;