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