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