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