Debian Codegraph @

vendor/wikimedia/xmp-reader/src/Reader.php

raw
1 <?php
2 /**
3 * Reader for XMP data containing properties relevant to images.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Media
22 */
23
24 namespace Wikimedia\XMPReader;
25
26 use Exception;
27 use Psr\Log\LoggerAwareInterface;
28 use Psr\Log\LoggerAwareTrait;
29 use Psr\Log\LoggerInterface;
30 use Psr\Log\NullLogger;
31 use RuntimeException;
32 use Wikimedia\ScopedCallback;
33 use XMLParser;
34 use XMLReader;
35
36 /**
37 * Class for reading xmp data containing properties relevant to
38 * images, and spitting out an array that FormatMetadata accepts.
39 *
40 * Note, this is not meant to recognize every possible thing you can
41 * encode in XMP. It should recognize all the properties we want.
42 * For example, it doesn't have support for structures with multiple
43 * nesting levels, as none of the properties we're supporting use that
44 * feature. If it comes across properties it doesn't recognize, it should
45 * ignore them.
46 *
47 * The public methods one would call in this class are
48 * - parse( $content )
49 * Reads in xmp content.
50 * Can potentially be called multiple times with partial data each time.
51 * - parseExtended( $content )
52 * Reads XMPExtended blocks (jpeg files only).
53 * - getResults
54 * Outputs a results array.
55 *
56 * Note XMP kind of looks like rdf. They are not the same thing - XMP is
57 * encoded as a specific subset of rdf. This class can read XMP. It cannot
58 * read rdf.
59 */
60 class Reader implements LoggerAwareInterface {
61 use LoggerAwareTrait;
62
63 /** @var array XMP item configuration array */
64 protected array $items;
65
66 /** @var array Array to hold the current element (and previous element, and so on) */
67 private array $curItem = [];
68
69 /** @var bool|string The structure name when processing nested structures. */
70 private $ancestorStruct = false;
71
72 /** @var bool|string Temporary holder for character data that appears in xmp doc. */
73 private $charContent = false;
74
75 /** @var array Stores the state the xmpreader is in (see MODE_FOO constants) */
76 private array $mode = [];
77
78 /** @var array Array to hold results */
79 private array $results = [];
80
81 /** @var bool If we're doing a seq or bag. */
82 private bool $processingArray = false;
83
84 /** @var bool|string Used for lang alts only */
85 private $itemLang = false;
86
87 /** @var XMLParser|null A resource handle for the XML parser */
88 private $xmlParser;
89
90 /** @var bool|string Character set like 'UTF-8' */
91 private $charset = false;
92
93 /** @var int */
94 private int $extendedXMPOffset = 0;
95
96 /** @var int Flag determining if the XMP is safe to parse */
97 private int $parsable = 0;
98
99 /** @var string Buffer of XML to parse */
100 private string $xmlParsableBuffer = '';
101
102 /**
103 * @var string
104 */
105 private string $filename;
106
107 /**
108 * These are various mode constants.
109 * they are used to figure out what to do
110 * with an element when its encountered.
111 *
112 * For example, MODE_IGNORE is used when processing
113 * a property we're not interested in. So if a new
114 * element pops up when we're in that mode, we ignore it.
115 */
116 private const MODE_INITIAL = 0;
117 private const MODE_IGNORE = 1;
118 private const MODE_LI = 2;
119 private const MODE_LI_LANG = 3;
120 private const MODE_QDESC = 4;
121
122 // The following MODE constants are also used in the
123 // $items array to denote what type of property the item is.
124 public const MODE_SIMPLE = 10;
125 // structure (associative array)
126 public const MODE_STRUCT = 11;
127 // ordered list
128 public const MODE_SEQ = 12;
129 // unordered list
130 public const MODE_BAG = 13;
131 public const MODE_LANG = 14;
132 // non-language alt. Currently not implemented, and not needed atm.
133 public const MODE_ALT = 15;
134 // A BAG of Structs.
135 public const MODE_BAGSTRUCT = 16;
136
137 private const NS_RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
138 private const NS_XML = 'http://www.w3.org/XML/1998/namespace';
139
140 // States used while determining if XML is safe to parse
141 private const PARSABLE_UNKNOWN = 0;
142 private const PARSABLE_OK = 1;
143 private const PARSABLE_BUFFERING = 2;
144 private const PARSABLE_NO = 3;
145
146 /**
147 * Primary job is to initialize the XMLParser
148 *
149 * @param LoggerInterface|null $logger Logger instance if available
150 * @param string $filename
151 */
152 public function __construct( ?LoggerInterface $logger = null, $filename = 'unknown' ) {
153 if ( $logger ) {
154 $this->setLogger( $logger );
155 } else {
156 $this->setLogger( new NullLogger() );
157 }
158 $this->filename = $filename;
159
160 $this->items = Info::getItems();
161
162 $this->resetXMLParser();
163 }
164
165 /**
166 * Destroy the XML parser, usually after errors.
167 */
168 private function destroyXMLParser(): void {
169 if ( $this->xmlParser ) {
170 $this->xmlParser = null;
171 }
172 }
173
174 /**
175 * Main use is if a single item has multiple xmp documents describing it.
176 * For example in jpeg's with extendedXMP
177 */
178 private function resetXMLParser(): void {
179 $this->destroyXMLParser();
180
181 $this->xmlParser = xml_parser_create_ns( 'UTF-8', ' ' );
182 xml_parser_set_option( $this->xmlParser, XML_OPTION_CASE_FOLDING, 0 );
183 xml_parser_set_option( $this->xmlParser, XML_OPTION_SKIP_WHITE, 1 );
184
185 xml_set_element_handler( $this->xmlParser,
186 [ $this, 'startElement' ],
187 [ $this, 'endElement' ] );
188
189 xml_set_character_data_handler( $this->xmlParser, [ $this, 'char' ] );
190
191 $this->parsable = self::PARSABLE_UNKNOWN;
192 $this->xmlParsableBuffer = '';
193 }
194
195 /**
196 * Check if this instance supports using this class
197 *
198 * @return bool
199 */
200 public static function isSupported(): bool {
201 return function_exists( 'xml_parser_create_ns' ) && class_exists( XMLReader::class );
202 }
203
204 /**
205 * Get the result array. Do some post-processing before returning
206 * the array, and transform any metadata that is special-cased.
207 *
208 * @return array Array of results as an array of arrays suitable for
209 * FormatMetadata::getFormattedData().
210 */
211 public function getResults(): array {
212 // xmp-special is for metadata that affects how stuff
213 // is extracted. For example xmpNote:HasExtendedXMP.
214
215 // It is also used to handle photoshop:AuthorsPosition
216 // which is weird and really part of another property,
217 // see 2:85 in IPTC. See also pg 21 of IPTC4XMP standard.
218 // The location fields also use it.
219
220 $data = $this->results;
221
222 if ( isset( $data['xmp-special']['AuthorsPosition'] )
223 && is_string( $data['xmp-special']['AuthorsPosition'] )
224 && isset( $data['xmp-general']['Artist'] )
225 ) {
226 if ( is_string( $data['xmp-general']['Artist'] ) ) {
227 // Not clear if this is reachable, as simple value Artist
228 // should always be xmp-general not xmp-exif
229 $data['xmp-general']['Artist'] = $data['xmp-special']['AuthorsPosition'] . ', '
230 . $data['xmp-general']['Artist'];
231 } elseif ( isset( $data['xmp-general']['Artist'][0] ) ) {
232 // Note, if there is more than one creator, this only applies to first.
233 $data['xmp-general']['Artist'][0] = $data['xmp-special']['AuthorsPosition'] . ', '
234 . $data['xmp-general']['Artist'][0];
235 }
236 }
237
238 // Go through the LocationShown and LocationCreated
239 // changing it to the non-hierarchical form used by
240 // the other location fields.
241
242 if ( isset( $data['xmp-special']['LocationShown'][0] )
243 // @phan-suppress-next-line PhanTypeArraySuspiciousNull, PhanTypeInvalidDimOffset
244 && is_array( $data['xmp-special']['LocationShown'][0] )
245 ) {
246 // the is_array is just paranoia. It should always
247 // be an array.
248 foreach ( $data['xmp-special']['LocationShown'] as $loc ) {
249 if ( !is_array( $loc ) ) {
250 // To avoid copying over the _type meta-fields.
251 continue;
252 }
253 foreach ( $loc as $field => $val ) {
254 $data['xmp-general'][$field . 'Dest'][] = $val;
255 }
256 }
257 }
258 if ( isset( $data['xmp-special']['LocationCreated'][0] )
259 // @phan-suppress-next-line PhanTypeArraySuspiciousNull, PhanTypeInvalidDimOffset
260 && is_array( $data['xmp-special']['LocationCreated'][0] )
261 ) {
262 // the is_array is just paranoia. It should always
263 // be an array.
264 foreach ( $data['xmp-special']['LocationCreated'] as $loc ) {
265 if ( !is_array( $loc ) ) {
266 // To avoid copying over the _type meta-fields.
267 continue;
268 }
269 foreach ( $loc as $field => $val ) {
270 $data['xmp-general'][$field . 'Created'][] = $val;
271 }
272 }
273 }
274
275 // We don't want to return the special values, since they're
276 // special and not info to be stored about the file.
277 unset( $data['xmp-special'] );
278
279 // Convert GPSAltitude to negative if below sea level.
280 if ( isset( $data['xmp-exif']['GPSAltitudeRef'] )
281 && isset( $data['xmp-exif']['GPSAltitude'] )
282 ) {
283 // Must convert to a real before multiplying by -1
284 // Validate guarantees there will always be a '/' in this value.
285 [ $nom, $denom ] = explode( '/', $data['xmp-exif']['GPSAltitude'] );
286 // @phan-suppress-next-line PhanTypeInvalidLeftOperandOfNumericOp, PhanTypeInvalidRightOperandOfNumericOp
287 $data['xmp-exif']['GPSAltitude'] = $nom / $denom;
288
289 // @phan-suppress-next-line PhanTypeInvalidDimOffset
290 if ( $data['xmp-exif']['GPSAltitudeRef'] == '1' ) {
291 $data['xmp-exif']['GPSAltitude'] *= -1;
292 }
293 unset( $data['xmp-exif']['GPSAltitudeRef'] );
294 }
295
296 return $data;
297 }
298
299 /**
300 * Main function to parse XMP. Use getResults to get results.
301 *
302 * Also catches any errors during processing, writes them to
303 * debug log, blanks result array and returns false.
304 *
305 * @param string $content XMP data
306 * @param bool $allOfIt If this is all the data (true), or if it's split up (false). Default true
307 * @throws RuntimeException
308 * @return bool Success.
309 */
310 public function parse( $content, $allOfIt = true ): bool {
311 if ( !$this->xmlParser ) {
312 $this->resetXMLParser();
313 }
314 try {
315
316 // detect encoding by looking for BOM which is supposed to be in processing instruction.
317 // see page 12 of http://www.adobe.com/devnet/xmp/pdfs/XMPSpecificationPart3.pdf
318 if ( !$this->charset ) {
319 $bom = [];
320 if ( preg_match( '/\xEF\xBB\xBF|\xFE\xFF|\x00\x00\xFE\xFF|\xFF\xFE\x00\x00|\xFF\xFE/',
321 $content, $bom )
322 ) {
323 $this->charset = match ( $bom[0] ) {
324 "\xFE\xFF" => 'UTF-16BE',
325 "\xFF\xFE" => 'UTF-16LE',
326 "\x00\x00\xFE\xFF" => 'UTF-32BE',
327 "\xFF\xFE\x00\x00" => 'UTF-32LE',
328 "\xEF\xBB\xBF" => 'UTF-8',
329 default => throw new RuntimeException( "Invalid BOM" ),
330 };
331 } else {
332 // standard specifically says, if no bom assume utf-8
333 $this->charset = 'UTF-8';
334 }
335 }
336 if ( $this->charset !== 'UTF-8' ) {
337 // don't convert if already utf-8
338 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
339 $content = @iconv( $this->charset, 'UTF-8//IGNORE', $content );
340 }
341
342 // Replace any null bytes with the replacement character (T320282)
343 $content = str_replace( "\0", "\u{FFFD}", $content );
344
345 // Ensure the XMP block does not have an xml doctype declaration, which
346 // could declare entities unsafe to parse with xml_parse (T85848/T71210).
347 if ( $this->parsable !== self::PARSABLE_OK ) {
348 if ( $this->parsable === self::PARSABLE_NO ) {
349 throw new RuntimeException( 'Unsafe doctype declaration in XML.' );
350 }
351
352 $content = $this->xmlParsableBuffer . $content;
353 if ( !$this->checkParseSafety( $content ) ) {
354 if ( !$allOfIt && $this->parsable !== self::PARSABLE_NO ) {
355 // parse wasn't Unsuccessful yet, so return true
356 // in this case.
357 return true;
358 }
359 $msg = ( $this->parsable === self::PARSABLE_NO ) ?
360 'Unsafe doctype declaration in XML.' :
361 'No root element found in XML.';
362 throw new RuntimeException( $msg );
363 }
364 }
365
366 $ok = xml_parse( $this->xmlParser, $content, $allOfIt );
367 if ( !$ok ) {
368 $code = xml_get_error_code( $this->xmlParser );
369 $error = xml_error_string( $code );
370 $line = xml_get_current_line_number( $this->xmlParser );
371 $col = xml_get_current_column_number( $this->xmlParser );
372 $offset = xml_get_current_byte_index( $this->xmlParser );
373
374 $this->logger->info(
375 '{method} : Error reading XMP content: {error} ' .
376 '(file: {file}, line: {line} column: {column} ' .
377 'byte offset: {offset})',
378 [
379 'method' => __METHOD__,
380 'error_code' => $code,
381 'error' => $error,
382 'file' => $this->filename,
383 'line' => $line,
384 'column' => $col,
385 'offset' => $offset,
386 'content' => $content,
387 ]
388 );
389 // blank if error.
390 $this->results = [];
391 $this->destroyXMLParser();
392 return false;
393 }
394 } catch ( Exception $e ) {
395 $this->logger->warning(
396 '{method} {message}',
397 [
398 'method' => __METHOD__,
399 'message' => $e->getMessage(),
400 'exception' => $e,
401 'file' => $this->filename,
402 'content' => $content,
403 ]
404 );
405 $this->results = [];
406 return false;
407 }
408 if ( $allOfIt ) {
409 $this->destroyXMLParser();
410 }
411
412 return true;
413 }
414
415 /** Entry point for XMPExtended blocks in jpeg files
416 *
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.
421 */
422 public function parseExtended( $content ): bool {
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
428 ) {
429 $this->logger->info( __METHOD__ .
430 " Ignoring XMPExtended block due to wrong guid (guid= '{guid}')",
431 [
432 'guid' => $guid,
433 'file' => $this->filename,
434 ] );
435
436 return false;
437 }
438 $len = unpack( 'Nlength/Noffset', substr( $content, 32, 8 ) );
439
440 if ( !$len ||
441 $len['length'] < 4 ||
442 $len['offset'] < 0 ||
443 $len['offset'] > $len['length']
444 ) {
445 $this->logger->info(
446 __METHOD__ . 'Error reading extended XMP block, invalid length or offset.',
447 [ 'file' => $this->filename ]
448 );
449
450 return false;
451 }
452
453 // we're not very robust here. we should accept it in the wrong order.
454 // To quote the XMP standard:
455 // "A JPEG writer should write the ExtendedXMP marker segments in order,
456 // immediately following the StandardXMP. However, the JPEG standard
457 // does not require preservation of marker segment order. A robust JPEG
458 // reader should tolerate the marker segments in any order."
459 // On the other hand, the probability that an image will have more than
460 // 128k of metadata is rather low... so the probability that it will have
461 // > 128k, and be in the wrong order is very low...
462
463 if ( $len['offset'] !== $this->extendedXMPOffset ) {
464 $this->logger->info( __METHOD__ . 'Ignoring XMPExtended block due to wrong order. (Offset was '
465 . $len['offset'] . ' but expected ' . $this->extendedXMPOffset . ')',
466 [ 'file' => $this->filename ]
467 );
468
469 return false;
470 }
471
472 if ( $len['offset'] === 0 ) {
473 // if we're starting the extended block, we've probably already
474 // done the XMPStandard block, so reset.
475 $this->resetXMLParser();
476 }
477
478 $this->extendedXMPOffset += $len['length'];
479
480 $actualContent = substr( $content, 40 );
481
482 $atEnd = ( $this->extendedXMPOffset === strlen( $actualContent ) );
483
484 $this->logger->debug(
485 __METHOD__ . 'Parsing a XMPExtended block',
486 [ 'file' => $this->filename ]
487 );
488
489 return $this->parse( $actualContent, $atEnd );
490 }
491
492 /**
493 * Character data handler
494 * Called whenever character data is found in the xmp document.
495 *
496 * does nothing if we're in MODE_IGNORE or if the data is whitespace
497 * throws an error if we're not in MODE_SIMPLE (as we're not allowed to have character
498 * data in the other modes).
499 *
500 * As an example, this happens when we encounter XMP like:
501 * <exif:DigitalZoomRatio>0/10</exif:DigitalZoomRatio>
502 * and are processing the 0/10 bit.
503 *
504 * @param XMLParser $parser XMLParser reference to the xml parser
505 * @param string $data Character data
506 * @throws RuntimeException On invalid data
507 */
508 public function char( $parser, $data ): void {
509 $data = trim( $data );
510 if ( trim( $data ) === "" ) {
511 return;
512 }
513
514 if ( !isset( $this->mode[0] ) ) {
515 throw new RuntimeException( 'Unexpected character data before first rdf:Description element' );
516 }
517
518 if ( $this->mode[0] === self::MODE_IGNORE ) {
519 return;
520 }
521
522 if ( $this->mode[0] !== self::MODE_SIMPLE
523 && $this->mode[0] !== self::MODE_QDESC
524 ) {
525 throw new RuntimeException( 'character data where not expected. (mode ' . $this->mode[0] . ')' );
526 }
527
528 // to check, how does this handle w.s.
529 if ( $this->charContent === false ) {
530 $this->charContent = $data;
531 } else {
532 $this->charContent .= $data;
533 }
534 }
535
536 /**
537 * Check if a block of XML is safe to pass to xml_parse, i.e. doesn't
538 * contain a doctype declaration which could contain a dos attack if we
539 * parse it and expand internal entities (T85848).
540 *
541 * @param string $content xml string to check for parse safety
542 * @return bool true if the xml is safe to parse, false otherwise
543 */
544 private function checkParseSafety( $content ): bool {
545 $reader = new XMLReader();
546 $result = null;
547
548 // Pull in the arbitrary MAX_URI_LENGTH from libxml2...
549 $maxUriLength = 1024 * 1024;
550 $dataUri = 'data://text/plain,' . urlencode( $content );
551 if ( strlen( $dataUri ) > $maxUriLength ) {
552 // libxml2 won't parse this file as a data URI due to the length.
553 return false;
554 }
555
556 // For XMLReader to parse incomplete/invalid XML, it has to be open()'ed
557 // instead of using XML().
558 if ( !$reader->open(
559 $dataUri,
560 null,
561 LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_NONET
562 ) ) {
563 return false;
564 }
565
566 // 2.9.0 released Feb 2022 - https://gitlab.gnome.org/GNOME/libxml2/-/releases/v2.9.0
567 // https://www.php.net/manual/en/libxml.requirements.php
568 // > This extension requires » libxml >= 2.9.4 as of PHP 8.4.0, libxml >= 2.9.0
569 // > prior to PHP 8.4.0, and libxml >= 2.6.0 prior to PHP 8.0.0.
570 // So this can probably be removed when we require PHP >= 8.4.0!
571 if ( LIBXML_VERSION < 20900 ) {
572 // @codeCoverageIgnoreStart
573 $oldDisable = libxml_disable_entity_loader( true );
574 /** @noinspection PhpUnusedLocalVariableInspection */
575 $reset = new ScopedCallback(
576 'libxml_disable_entity_loader',
577 [ $oldDisable ]
578 );
579 // @codeCoverageIgnoreEnd
580 }
581
582 $reader->setParserProperty( XMLReader::SUBST_ENTITIES, false );
583
584 // Even with LIBXML_NOWARNING set, XMLReader::read gives a warning
585 // when parsing truncated XML, which causes unit tests to fail.
586 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
587 while ( @$reader->read() ) {
588 if ( $reader->nodeType === XMLReader::ELEMENT ) {
589 // Reached the first element without hitting a doctype declaration
590 $this->parsable = self::PARSABLE_OK;
591 $result = true;
592 break;
593 }
594 if ( $reader->nodeType === XMLReader::DOC_TYPE ) {
595 $this->parsable = self::PARSABLE_NO;
596 $result = false;
597 break;
598 }
599 }
600
601 if ( $result !== null ) {
602 return $result;
603 }
604
605 // Reached the end of the parsable xml without finding an element
606 // or doctype. Buffer and try again.
607 $this->parsable = self::PARSABLE_BUFFERING;
608 $this->xmlParsableBuffer = $content;
609 return false;
610 }
611
612 /** When we hit a closing element in MODE_IGNORE
613 * Check to see if this is the element we started to ignore,
614 * in which case we get out of MODE_IGNORE
615 *
616 * @param string $elm Namespace of element followed by a space and then tag name of element.
617 */
618 private function endElementModeIgnore( $elm ): void {
619 if ( $this->curItem[0] === $elm ) {
620 array_shift( $this->curItem );
621 array_shift( $this->mode );
622 }
623 }
624
625 /**
626 * Hit a closing element when in MODE_SIMPLE.
627 * This generally means that we finished processing a
628 * property value, and now have to save the result to the
629 * results array
630 *
631 * For example, when processing:
632 * <exif:DigitalZoomRatio>0/10</exif:DigitalZoomRatio>
633 * this deals with when we hit </exif:DigitalZoomRatio>.
634 *
635 * Or it could be if we hit the end element of a property
636 * of a compound data structure (like a member of an array).
637 *
638 * @param string $elm Namespace, space, and tag name.
639 */
640 private function endElementModeSimple( $elm ): void {
641 if ( $this->charContent !== false ) {
642 if ( $this->processingArray ) {
643 // if we're processing an array, use the original element
644 // name instead of rdf:li.
645 [ $ns, $tag ] = explode( ' ', $this->curItem[0], 2 );
646 } else {
647 [ $ns, $tag ] = explode( ' ', $elm, 2 );
648 }
649 $this->saveValue( $ns, $tag, $this->charContent );
650
651 // reset
652 $this->charContent = false;
653 }
654 array_shift( $this->curItem );
655 array_shift( $this->mode );
656 }
657
658 /**
659 * Hit a closing element in MODE_STRUCT, MODE_SEQ, MODE_BAG
660 * generally means we've finished processing a nested structure.
661 * resets some internal variables to indicate that.
662 *
663 * Note this means we hit the closing element not the "</rdf:Seq>".
664 *
665 * @par For example, when processing:
666 * @code{.xml}
667 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
668 * </rdf:Seq> </exif:ISOSpeedRatings>
669 * @endcode
670 *
671 * This method is called when we hit the "</exif:ISOSpeedRatings>" tag.
672 *
673 * @param string $elm Namespace . space . tag name.
674 * @throws RuntimeException
675 */
676 private function endElementNested( $elm ): void {
677 /* cur item must be the same as $elm, unless if in MODE_STRUCT
678 * in which case it could also be rdf:Description */
679 if ( $this->curItem[0] !== $elm
680 && !( $elm === self::NS_RDF . ' Description'
681 && $this->mode[0] === self::MODE_STRUCT )
682 ) {
683 throw new RuntimeException( "nesting mismatch. got a </$elm> but expected a </" .
684 $this->curItem[0] . '>' );
685 }
686
687 // Validate structures.
688 [ $ns, $tag ] = explode( ' ', $elm, 2 );
689 if ( isset( $this->items[$ns][$tag]['validate'] ) ) {
690 $info =& $this->items[$ns][$tag];
691 $finalName = $info['map_name'] ?? $tag;
692
693 $validator = new Validate( $this->logger );
694 $validate = [ $validator, $info['validate'] ];
695
696 if ( !isset( $this->results['xmp-' . $info['map_group']][$finalName] ) ) {
697 // This can happen if all the members of the struct failed validation.
698 $this->logger->debug(
699 __METHOD__ . " <$ns:$tag> has no valid members.",
700 [ 'file' => $this->filename ]
701 );
702 } else {
703 $val =& $this->results['xmp-' . $info['map_group']][$finalName];
704 $validate( $info, $val, false );
705 if ( $val === null ) {
706 // the idea being the validation function will unset the variable if
707 // its invalid.
708 $this->logger->info(
709 __METHOD__ . " <$ns:$tag> failed validation.",
710 [ 'file' => $this->filename ]
711 );
712 unset( $this->results['xmp-' . $info['map_group']][$finalName] );
713 }
714 }
715 }
716
717 array_shift( $this->curItem );
718 array_shift( $this->mode );
719 $this->ancestorStruct = false;
720 $this->processingArray = false;
721 $this->itemLang = false;
722 }
723
724 /**
725 * Hit a closing element in MODE_LI (either rdf:Seq, or rdf:Bag )
726 * Add information about what type of element this is.
727 *
728 * Note we still have to hit the outer "</property>"
729 *
730 * @par For example, when processing:
731 * @code{.xml}
732 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
733 * </rdf:Seq> </exif:ISOSpeedRatings>
734 * @endcode
735 *
736 * This method is called when we hit the "</rdf:Seq>".
737 * (For comparison, we call endElementModeSimple when we
738 * hit the "</rdf:li>")
739 *
740 * @param string $elm Namespace . ' ' . element name
741 * @throws RuntimeException
742 */
743 private function endElementModeLi( $elm ): void {
744 [ $ns, $tag ] = explode( ' ', $this->curItem[0], 2 );
745 $info = $this->items[$ns][$tag];
746 $finalName = $info['map_name'] ?? $tag;
747
748 array_shift( $this->mode );
749
750 if ( !isset( $this->results['xmp-' . $info['map_group']][$finalName] ) ) {
751 $this->logger->debug(
752 __METHOD__ . " Empty compound element $finalName.",
753 [ 'file' => $this->filename ]
754 );
755
756 return;
757 }
758
759 if ( $elm === self::NS_RDF . ' Seq' ) {
760 $this->results['xmp-' . $info['map_group']][$finalName]['_type'] = 'ol';
761 } elseif ( $elm === self::NS_RDF . ' Bag' ) {
762 $this->results['xmp-' . $info['map_group']][$finalName]['_type'] = 'ul';
763 } elseif ( $elm === self::NS_RDF . ' Alt' ) {
764 // extra if needed as you could theoretically have a non-language alt.
765 if ( $info['mode'] === self::MODE_LANG ) {
766 $this->results['xmp-' . $info['map_group']][$finalName]['_type'] = 'lang';
767 }
768 } else {
769 throw new RuntimeException(
770 __METHOD__ . " expected </rdf:seq> or </rdf:bag> but instead got $elm."
771 );
772 }
773 }
774
775 /**
776 * End element while in MODE_QDESC
777 * mostly when ending an element when we have a simple value
778 * that has qualifiers.
779 *
780 * Qualifiers aren't all that common, and we don't do anything
781 * with them.
782 *
783 * @param string $elm Namespace and element
784 */
785 private function endElementModeQDesc( $elm ): void {
786 if ( $elm === self::NS_RDF . ' value' ) {
787 [ $ns, $tag ] = explode( ' ', $this->curItem[0], 2 );
788 $this->saveValue( $ns, $tag, $this->charContent );
789 $this->charContent = false;
790 return;
791 }
792
793 array_shift( $this->mode );
794 array_shift( $this->curItem );
795 }
796
797 /**
798 * Handler for hitting a closing element.
799 *
800 * generally just calls a helper function depending on what
801 * mode we're in.
802 *
803 * Ignores the outer wrapping elements that are optional in
804 * xmp and have no meaning.
805 *
806 * @param XMLParser $parser
807 * @param string $elm Namespace . ' ' . element name
808 * @throws RuntimeException
809 */
810 public function endElement( $parser, $elm ): void {
811 if ( $elm === ( self::NS_RDF . ' RDF' )
812 || $elm === 'adobe:ns:meta/ xmpmeta'
813 || $elm === 'adobe:ns:meta/ xapmeta'
814 ) {
815 // ignore these.
816 return;
817 }
818
819 if ( $elm === self::NS_RDF . ' type' ) {
820 // these aren't really supported properly yet.
821 // However, it appears they almost never used.
822 $this->logger->info(
823 __METHOD__ . ' encountered <rdf:type>',
824 [ 'file' => $this->filename ]
825 );
826 }
827
828 if ( !str_contains( $elm, ' ' ) ) {
829 // This probably shouldn't happen.
830 // However, there is a bug in an adobe product
831 // that forgets the namespace on some things.
832 // (Luckily they are unimportant things).
833 $this->logger->info(
834 __METHOD__ . " Encountered </$elm> which has no namespace. Skipping.",
835 [ 'file' => $this->filename ]
836 );
837
838 return;
839 }
840
841 if ( count( $this->mode ) === 0 ) {
842 // This should never ever happen and means
843 // there is a pretty major bug in this class.
844 // @codeCoverageIgnoreStart
845 throw new RuntimeException( 'Encountered end element with no mode' );
846 // @codeCoverageIgnoreEnd
847 }
848
849 if ( count( $this->curItem ) === 0 && $this->mode[0] !== self::MODE_INITIAL ) {
850 // just to be paranoid. Should always have a curItem, except for initially
851 // (aka during MODE_INITIAL).
852 // @codeCoverageIgnoreStart
853 throw new RuntimeException( "Hit end element </$elm> but no curItem" );
854 // @codeCoverageIgnoreEnd
855 }
856
857 switch ( $this->mode[0] ) {
858 case self::MODE_IGNORE:
859 $this->endElementModeIgnore( $elm );
860 break;
861 case self::MODE_SIMPLE:
862 $this->endElementModeSimple( $elm );
863 break;
864 case self::MODE_STRUCT:
865 case self::MODE_SEQ:
866 case self::MODE_BAG:
867 case self::MODE_LANG:
868 case self::MODE_BAGSTRUCT:
869 $this->endElementNested( $elm );
870 break;
871 case self::MODE_INITIAL:
872 if ( $elm === self::NS_RDF . ' Description' ) {
873 array_shift( $this->mode );
874 } else {
875 // @codeCoverageIgnoreStart
876 throw new RuntimeException( 'Element ended unexpectedly while in MODE_INITIAL' );
877 // @codeCoverageIgnoreEnd
878 }
879 break;
880 case self::MODE_LI:
881 case self::MODE_LI_LANG:
882 $this->endElementModeLi( $elm );
883 break;
884 case self::MODE_QDESC:
885 $this->endElementModeQDesc( $elm );
886 break;
887 default:
888 // @codeCoverageIgnoreStart
889 $this->logger->info(
890 __METHOD__ . " no mode (elm = $elm)",
891 [ 'file' => $this->filename ]
892 );
893 break;
894 // @codeCoverageIgnoreEnd
895 }
896 }
897
898 /**
899 * Hit an opening element while in MODE_IGNORE
900 *
901 * XMP is extensible, so ignore any tag we don't understand.
902 *
903 * Mostly ignores, unless we encounter the element that we are ignoring.
904 * in which case we add it to the item stack, so we can ignore things
905 * that are nested, correctly.
906 *
907 * @param string $elm Namespace . ' ' . tag name
908 */
909 private function startElementModeIgnore( $elm ): void {
910 if ( $elm === $this->curItem[0] ) {
911 array_unshift( $this->curItem, $elm );
912 array_unshift( $this->mode, self::MODE_IGNORE );
913 }
914 }
915
916 /**
917 * Start element in MODE_BAG (unordered array)
918 * this should always be <rdf:Bag>
919 *
920 * @param string $elm Namespace . ' ' . tag
921 * @throws RuntimeException If we have an element that's not <rdf:Bag>
922 */
923 private function startElementModeBag( $elm ): void {
924 if ( $elm === self::NS_RDF . ' Bag' ) {
925 array_unshift( $this->mode, self::MODE_LI );
926 } else {
927 throw new RuntimeException( "Expected <rdf:Bag> but got $elm." );
928 }
929 }
930
931 /**
932 * Start element in MODE_SEQ (ordered array)
933 * this should always be <rdf:Seq>
934 *
935 * @param string $elm Namespace . ' ' . tag
936 * @throws RuntimeException If we have an element that's not <rdf:Seq>
937 */
938 private function startElementModeSeq( $elm ): void {
939 if ( $elm === self::NS_RDF . ' Seq' ) {
940 array_unshift( $this->mode, self::MODE_LI );
941 } elseif ( $elm === self::NS_RDF . ' Bag' ) {
942 # T29105
943 $this->logger->info(
944 __METHOD__ . ' Expected an rdf:Seq, but got an rdf:Bag. Pretending' .
945 ' it is a Seq, since some buggy software is known to screw this up.',
946 [ 'file' => $this->filename ]
947 );
948 array_unshift( $this->mode, self::MODE_LI );
949 } else {
950 throw new RuntimeException( "Expected <rdf:Seq> but got $elm." );
951 }
952 }
953
954 /**
955 * Start element in MODE_LANG (language alternative)
956 * this should always be <rdf:Alt>
957 *
958 * This tag tends to be used for metadata like describe this
959 * picture, which can be translated into multiple languages.
960 *
961 * XMP supports non-linguistic alternative selections,
962 * which are really only used for thumbnails, which
963 * we don't care about.
964 *
965 * @param string $elm Namespace . ' ' . tag
966 * @throws RuntimeException If we have an element that's not <rdf:Alt>
967 */
968 private function startElementModeLang( $elm ): void {
969 if ( $elm === self::NS_RDF . ' Alt' ) {
970 array_unshift( $this->mode, self::MODE_LI_LANG );
971 } else {
972 throw new RuntimeException( "Expected <rdf:Alt> but got $elm." );
973 }
974 }
975
976 /**
977 * Handle an opening element when in MODE_SIMPLE
978 *
979 * This should not happen often. This is for if a simple element
980 * already opened has a child element. Could happen for a
981 * qualified element.
982 *
983 * For example:
984 * <exif:DigitalZoomRatio><rdf:Description><rdf:value>0/10</rdf:value>
985 * <foo:someQualifier>Bar</foo:someQualifier> </rdf:Description>
986 * </exif:DigitalZoomRatio>
987 *
988 * This method is called when processing the <rdf:Description> element
989 *
990 * @param string $elm Namespace and tag names separated by space.
991 * @param array $attribs Attributes of the element.
992 * @throws RuntimeException
993 */
994 private function startElementModeSimple( $elm, $attribs ): void {
995 if ( $elm === self::NS_RDF . ' Description' ) {
996 // If this value has qualifiers
997 array_unshift( $this->mode, self::MODE_QDESC );
998 array_unshift( $this->curItem, $this->curItem[0] );
999
1000 if ( isset( $attribs[self::NS_RDF . ' value'] ) ) {
1001 [ $ns, $tag ] = explode( ' ', $this->curItem[0], 2 );
1002 $this->saveValue( $ns, $tag, $attribs[self::NS_RDF . ' value'] );
1003 }
1004 } elseif ( $elm === self::NS_RDF . ' value' ) {
1005 // This should not be here.
1006 throw new RuntimeException( __METHOD__ . ' Encountered <rdf:value> where it was unexpected.' );
1007 } else {
1008 // something else we don't recognize, like a qualifier maybe.
1009 $this->logger->info( __METHOD__ .
1010 " Encountered element <{element}> where only expecting character data as value of {curitem}",
1011 [
1012 'element' => $elm,
1013 'curitem' => $this->curItem[0],
1014 'file' => $this->filename,
1015 ]
1016 );
1017 array_unshift( $this->mode, self::MODE_IGNORE );
1018 array_unshift( $this->curItem, $elm );
1019 }
1020 }
1021
1022 /**
1023 * Start an element when in MODE_QDESC.
1024 * This generally happens when a simple element has an inner
1025 * rdf:Description to hold qualifier elements.
1026 *
1027 * For example in:
1028 * <exif:DigitalZoomRatio><rdf:Description><rdf:value>0/10</rdf:value>
1029 * <foo:someQualifier>Bar</foo:someQualifier> </rdf:Description>
1030 * </exif:DigitalZoomRatio>
1031 * Called when processing the <rdf:value> or <foo:someQualifier>.
1032 *
1033 * @param string $elm Namespace and tag name separated by a space.
1034 * @param array $attribs Array of attributes
1035 */
1036 private function startElementModeQDesc( $elm, $attribs ): void {
1037 if ( $elm === self::NS_RDF . ' value' ) {
1038 // URL values use rdf:resource attribute instead of text content.
1039 if ( isset( $attribs[ self::NS_RDF . ' resource' ] ) ) {
1040 $this->char( $this->xmlParser, $attribs[ self::NS_RDF . ' resource' ] );
1041 }
1042 // do nothing
1043 return;
1044 }
1045
1046 // otherwise its a qualifier, which we ignore
1047 array_unshift( $this->mode, self::MODE_IGNORE );
1048 array_unshift( $this->curItem, $elm );
1049 }
1050
1051 /**
1052 * Starting an element when in MODE_INITIAL
1053 * This usually happens when we hit an element inside
1054 * the outer rdf:Description
1055 *
1056 * This is generally where most properties start.
1057 *
1058 * @param string $ns Namespace
1059 * @param string $tag Tag name (without namespace prefix)
1060 * @param array $attribs Array of attributes
1061 * @throws RuntimeException
1062 */
1063 private function startElementModeInitial( $ns, $tag, $attribs ): void {
1064 if ( $ns === self::NS_RDF && $tag === 'type' ) {
1065 // Ignore top level rdf:type. See XMP spec part 1 section 7.9.2.5.
1066 array_unshift( $this->mode, self::MODE_IGNORE );
1067 array_unshift( $this->curItem, $ns . ' ' . $tag );
1068 return;
1069 }
1070 if ( $ns !== self::NS_RDF ) {
1071 if ( isset( $this->items[$ns][$tag] ) ) {
1072 if ( isset( $this->items[$ns][$tag]['structPart'] ) ) {
1073 // If this element is supposed to appear only as
1074 // a child of a structure, but appears here (not as
1075 // a child of a struct), then something weird is
1076 // happening, so ignore this element and its children.
1077
1078 $this->logger->info(
1079 'Encountered <{element}> outside of its expected parent. Ignoring.',
1080 [ 'element' => "$ns:$tag", 'file' => $this->filename ]
1081 );
1082
1083 array_unshift( $this->mode, self::MODE_IGNORE );
1084 array_unshift( $this->curItem, $ns . ' ' . $tag );
1085
1086 return;
1087 }
1088 $mode = $this->items[$ns][$tag]['mode'];
1089 array_unshift( $this->mode, $mode );
1090 array_unshift( $this->curItem, $ns . ' ' . $tag );
1091 if ( $mode === self::MODE_STRUCT ) {
1092 $this->ancestorStruct = $this->items[$ns][$tag]['map_name'] ?? $tag;
1093 }
1094 if ( $this->charContent !== false ) {
1095 // Something weird.
1096 // Should not happen in valid XMP.
1097 // char() should also throw an exception before
1098 // we hit this.
1099 throw new RuntimeException( 'tag nested in non-whitespace characters.' );
1100 }
1101 } else {
1102 // This element is not on our list of allowed elements so ignore.
1103 $this->logger->debug( __METHOD__ . ' Ignoring unrecognized element <{element}>.',
1104 [ 'element' => "$ns:$tag", 'file' => $this->filename ] );
1105 array_unshift( $this->mode, self::MODE_IGNORE );
1106 array_unshift( $this->curItem, $ns . ' ' . $tag );
1107
1108 return;
1109 }
1110 }
1111 // process attributes
1112 $this->doAttribs( $attribs );
1113 }
1114
1115 /**
1116 * Hit an opening element when in a Struct (MODE_STRUCT)
1117 * This is generally for fields of a compound property.
1118 *
1119 * Example of a struct (abbreviated; flash has more properties):
1120 *
1121 * <exif:Flash> <rdf:Description> <exif:Fired>True</exif:Fired>
1122 * <exif:Mode>1</exif:Mode></rdf:Description></exif:Flash>
1123 *
1124 * or:
1125 *
1126 * <exif:Flash rdf:parseType='Resource'> <exif:Fired>True</exif:Fired>
1127 * <exif:Mode>1</exif:Mode></exif:Flash>
1128 *
1129 * @param string $ns Namespace
1130 * @param string $tag Tag name (no ns)
1131 * @param array $attribs Array of attribs w/ values.
1132 * @throws RuntimeException
1133 */
1134 private function startElementModeStruct( $ns, $tag, $attribs ): void {
1135 if ( $ns !== self::NS_RDF ) {
1136 if ( isset( $this->items[$ns][$tag] ) ) {
1137 if ( isset( $this->items[$ns][$this->ancestorStruct]['children'] )
1138 && !isset( $this->items[$ns][$this->ancestorStruct]['children'][$tag] )
1139 ) {
1140 // This assumes that we don't have inter-namespace nesting
1141 // which we don't in all the properties we're interested in.
1142 throw new RuntimeException( " <$tag> appeared nested in <" . $this->ancestorStruct
1143 . "> where it is not allowed." );
1144 }
1145 array_unshift( $this->mode, $this->items[$ns][$tag]['mode'] );
1146 array_unshift( $this->curItem, $ns . ' ' . $tag );
1147 if ( $this->charContent !== false ) {
1148 // Something weird.
1149 // Should not happen in valid XMP.
1150 throw new RuntimeException( "tag <$tag> nested in non-whitespace characters (" .
1151 $this->charContent . ")." );
1152 }
1153 } else {
1154 array_unshift( $this->mode, self::MODE_IGNORE );
1155 array_unshift( $this->curItem, $ns . ' ' . $tag );
1156
1157 return;
1158 }
1159 }
1160
1161 if ( $ns === self::NS_RDF && $tag === 'Description' ) {
1162 $this->doAttribs( $attribs );
1163 array_unshift( $this->mode, self::MODE_STRUCT );
1164 array_unshift( $this->curItem, $this->curItem[0] );
1165 }
1166 }
1167
1168 /**
1169 * opening element in MODE_LI
1170 * process elements of arrays.
1171 *
1172 * Example:
1173 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
1174 * </rdf:Seq> </exif:ISOSpeedRatings>
1175 * This method is called when we hit the <rdf:li> element.
1176 *
1177 * @param string $elm Namespace . ' ' . tagname
1178 * @param array $attribs Attributes. (needed for BAGSTRUCTS)
1179 * @throws RuntimeException If it gets a tag other than <rdf:li>
1180 */
1181 private function startElementModeLi( $elm, $attribs ): void {
1182 if ( ( $elm ) !== self::NS_RDF . ' li' ) {
1183 throw new RuntimeException( "<rdf:li> expected but got $elm." );
1184 }
1185
1186 if ( !isset( $this->mode[1] ) ) {
1187 // This should never ever ever happen. Checking for it
1188 // to be paranoid.
1189 // @codeCoverageIgnoreStart
1190 throw new RuntimeException( 'In mode Li, but no 2xPrevious mode!' );
1191 // @codeCoverageIgnoreEnd
1192 }
1193
1194 if ( $this->mode[1] === self::MODE_BAGSTRUCT ) {
1195 // This list item contains a compound (STRUCT) value.
1196 array_unshift( $this->mode, self::MODE_STRUCT );
1197 array_unshift( $this->curItem, $elm );
1198 $this->processingArray = true;
1199
1200 if ( !isset( $this->curItem[1] ) ) {
1201 // be paranoid.
1202 // @codeCoverageIgnoreStart
1203 throw new RuntimeException( 'Can not find parent of BAGSTRUCT.' );
1204 // @codeCoverageIgnoreEnd
1205 }
1206 [ $curNS, $curTag ] = explode( ' ', $this->curItem[1] );
1207 $this->ancestorStruct = $this->items[$curNS][$curTag]['map_name'] ?? $curTag;
1208
1209 $this->doAttribs( $attribs );
1210 } else {
1211 // Normal BAG or SEQ containing simple values.
1212 array_unshift( $this->mode, self::MODE_SIMPLE );
1213 // need to add curItem[0] on again since one is for the specific item
1214 // and one is for the entire group.
1215 array_unshift( $this->curItem, $this->curItem[0] );
1216 $this->processingArray = true;
1217 }
1218 }
1219
1220 /**
1221 * Opening element in MODE_LI_LANG.
1222 * process elements of language alternatives
1223 *
1224 * Example:
1225 * <dc:title> <rdf:Alt> <rdf:li xml:lang="x-default">My house
1226 * </rdf:li> </rdf:Alt> </dc:title>
1227 *
1228 * This method is called when we hit the <rdf:li> element.
1229 *
1230 * @param string $elm Namespace . ' ' . tag
1231 * @param array $attribs Array of elements (most importantly xml:lang)
1232 * @throws RuntimeException If it gets a tag other than <rdf:li> or if no xml:lang
1233 */
1234 private function startElementModeLiLang( $elm, $attribs ): void {
1235 if ( $elm !== self::NS_RDF . ' li' ) {
1236 throw new RuntimeException( __METHOD__ . " <rdf:li> expected but got $elm." );
1237 }
1238 if ( !isset( $attribs[self::NS_XML . ' lang'] )
1239 || !preg_match( '/^[-A-Za-z0-9]{2,}$/D', $attribs[self::NS_XML . ' lang'] )
1240 ) {
1241 throw new RuntimeException( __METHOD__
1242 . " <rdf:li> did not contain, or has invalid xml:lang attribute in lang alternative" );
1243 }
1244
1245 // Lang is case-insensitive.
1246 $this->itemLang = strtolower( $attribs[self::NS_XML . ' lang'] );
1247
1248 // need to add curItem[0] on again since one is for the specific item
1249 // and one is for the entire group.
1250 array_unshift( $this->curItem, $this->curItem[0] );
1251 array_unshift( $this->mode, self::MODE_SIMPLE );
1252 $this->processingArray = true;
1253 }
1254
1255 /**
1256 * Hits an opening element.
1257 * Generally just calls a helper based on what MODE we're in.
1258 * Also does some initial set up for the wrapper element
1259 *
1260 * @param XMLParser $parser
1261 * @param string $elm Namespace "<space>" element
1262 * @param array $attribs Attribute name => value
1263 * @throws RuntimeException
1264 */
1265 public function startElement( $parser, $elm, $attribs ): void {
1266 if ( $elm === self::NS_RDF . ' RDF'
1267 || $elm === 'adobe:ns:meta/ xmpmeta'
1268 || $elm === 'adobe:ns:meta/ xapmeta'
1269 ) {
1270 /* ignore. */
1271 return;
1272 }
1273
1274 if ( $elm === self::NS_RDF . ' Description' ) {
1275 if ( count( $this->mode ) === 0 ) {
1276 // outer rdf:desc
1277 array_unshift( $this->mode, self::MODE_INITIAL );
1278 }
1279 } elseif ( $elm === self::NS_RDF . ' type' ) {
1280 // This doesn't support rdf:type properly.
1281 // In practise, I have yet to see a file that
1282 // uses this element, however it is mentioned
1283 // on page 25 of part 1 of the xmp standard.
1284 // Also, it seems as if exiv2 and exiftool do not support
1285 // this either (That or I misunderstand the standard)
1286 $this->logger->info(
1287 __METHOD__ . ' Encountered <rdf:type> which isn\'t currently supported',
1288 [ 'file' => $this->filename ]
1289 );
1290 }
1291
1292 if ( !str_contains( $elm, ' ' ) ) {
1293 // This probably shouldn't happen.
1294 $this->logger->info(
1295 __METHOD__ . " Encountered <$elm> which has no namespace. Skipping.",
1296 [ 'file' => $this->filename ]
1297 );
1298
1299 return;
1300 }
1301
1302 [ $ns, $tag ] = explode( ' ', $elm, 2 );
1303
1304 if ( count( $this->mode ) === 0 ) {
1305 // This should not happen.
1306 // @codeCoverageIgnoreStart
1307 throw new RuntimeException( 'Error extracting XMP, '
1308 . "encountered <$elm> with no mode" );
1309 // @codeCoverageIgnoreEnd
1310 }
1311
1312 switch ( $this->mode[0] ) {
1313 case self::MODE_IGNORE:
1314 $this->startElementModeIgnore( $elm );
1315 break;
1316 case self::MODE_SIMPLE:
1317 $this->startElementModeSimple( $elm, $attribs );
1318 break;
1319 case self::MODE_INITIAL:
1320 $this->startElementModeInitial( $ns, $tag, $attribs );
1321 break;
1322 case self::MODE_STRUCT:
1323 $this->startElementModeStruct( $ns, $tag, $attribs );
1324 break;
1325 case self::MODE_BAG:
1326 case self::MODE_BAGSTRUCT:
1327 $this->startElementModeBag( $elm );
1328 break;
1329 case self::MODE_SEQ:
1330 $this->startElementModeSeq( $elm );
1331 break;
1332 case self::MODE_LANG:
1333 $this->startElementModeLang( $elm );
1334 break;
1335 case self::MODE_LI_LANG:
1336 $this->startElementModeLiLang( $elm, $attribs );
1337 break;
1338 case self::MODE_LI:
1339 $this->startElementModeLi( $elm, $attribs );
1340 break;
1341 case self::MODE_QDESC:
1342 $this->startElementModeQDesc( $elm, $attribs );
1343 break;
1344 default:
1345 // @codeCoverageIgnoreStart
1346 throw new RuntimeException( 'StartElement in unknown mode: ' . $this->mode[0] );
1347 // @codeCoverageIgnoreEnd
1348 }
1349 }
1350
1351 /**
1352 * Process attributes.
1353 * Simple values can be stored as either a tag or attribute
1354 *
1355 * Often the initial "<rdf:Description>" tag just has all the simple
1356 * properties as attributes.
1357 *
1358 * @par Example:
1359 * @code
1360 * <rdf:Description rdf:about=""
1361 * xmlns:exif="http://ns.adobe.com/exif/1.0/" exif:DigitalZoomRatio="0/10">
1362 * @endcode
1363 *
1364 * @param array $attribs Array attribute=>value
1365 * @throws RuntimeException
1366 */
1367 private function doAttribs( $attribs ): void {
1368 // first check for rdf:parseType attribute, as that can change
1369 // how the attributes are interpreted.
1370
1371 if ( isset( $attribs[self::NS_RDF . ' parseType'] )
1372 && $attribs[self::NS_RDF . ' parseType'] === 'Resource'
1373 && $this->mode[0] === self::MODE_SIMPLE
1374 ) {
1375 // this is equivalent to having an inner rdf:Description
1376 $this->mode[0] = self::MODE_QDESC;
1377 }
1378 foreach ( $attribs as $name => $val ) {
1379 if ( !str_contains( $name, ' ' ) ) {
1380 // This shouldn't happen, but so far some old software forgets namespace
1381 // on rdf:about.
1382 $this->logger->info(
1383 __METHOD__ . ' Encountered non-namespaced attribute: ' .
1384 " $name=\"$val\". Skipping.",
1385 [ 'file' => $this->filename ]
1386 );
1387 continue;
1388 }
1389 [ $ns, $tag ] = explode( ' ', $name, 2 );
1390 if ( $ns === self::NS_RDF ) {
1391 if ( $tag === 'value' || $tag === 'resource' ) {
1392 // resource is for url.
1393 // value attribute is a weird way of just putting the contents.
1394 $this->char( $this->xmlParser, $val );
1395 }
1396 } elseif ( isset( $this->items[$ns][$tag] ) ) {
1397 if ( $this->mode[0] === self::MODE_SIMPLE ) {
1398 throw new RuntimeException( __METHOD__
1399 . " $ns:$tag found as attribute where not allowed" );
1400 }
1401 $this->saveValue( $ns, $tag, $val );
1402 } else {
1403 $this->logger->debug(
1404 __METHOD__ . " Ignoring unrecognized element <$ns:$tag>.",
1405 [ 'file' => $this->filename ]
1406 );
1407 }
1408 }
1409 }
1410
1411 /**
1412 * Given an extracted value, save it to results array
1413 *
1414 * note also uses $this->ancestorStruct and
1415 * $this->processingArray to determine what name to
1416 * save the value under. (in addition to $tag).
1417 *
1418 * @param string $ns Namespace of tag this is for
1419 * @param string $tag Tag name
1420 * @param string $val Value to save
1421 */
1422 private function saveValue( $ns, $tag, $val ): void {
1423 $info =& $this->items[$ns][$tag];
1424 $finalName = $info['map_name'] ?? $tag;
1425 if ( isset( $info['validate'] ) ) {
1426 $validator = new Validate( $this->logger );
1427 $validate = [ $validator, $info['validate'] ];
1428
1429 $validate( $info, $val, true );
1430 // the reasoning behind using &$val instead of using the return value
1431 // is to be consistent between here and validating structures.
1432 if ( $val === null ) {
1433 $this->logger->info(
1434 __METHOD__ . " <$ns:$tag> failed validation.",
1435 [ 'file' => $this->filename ]
1436 );
1437
1438 return;
1439 }
1440 }
1441
1442 if ( $this->ancestorStruct && $this->processingArray ) {
1443 // Aka both an array and a struct. ( self::MODE_BAGSTRUCT )
1444 $this->results['xmp-' . $info['map_group']][$this->ancestorStruct][][$finalName] = $val;
1445 } elseif ( $this->ancestorStruct ) {
1446 $this->results['xmp-' . $info['map_group']][$this->ancestorStruct][$finalName] = $val;
1447 } elseif ( $this->processingArray ) {
1448 if ( $this->itemLang === false ) {
1449 // normal array
1450 $this->results['xmp-' . $info['map_group']][$finalName][] = $val;
1451 } else {
1452 // lang array.
1453 $this->results['xmp-' . $info['map_group']][$finalName][$this->itemLang] = $val;
1454 }
1455 } else {
1456 $this->results['xmp-' . $info['map_group']][$finalName] = $val;
1457 }
1458 }
1459 }