Merge "Typo fix"
[mediawiki.git] / includes / media / XMP.php
blob7eb3d19e196389d35a55971c05d29e7ebff47ec0
1 <?php
2 /**
3 * Reader for XMP data containing properties relevant to images.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
21 * @ingroup Media
24 /**
25 * Class for reading xmp data containing properties relevant to
26 * images, and spitting out an array that FormatExif accepts.
28 * Note, this is not meant to recognize every possible thing you can
29 * encode in XMP. It should recognize all the properties we want.
30 * For example it doesn't have support for structures with multiple
31 * nesting levels, as none of the properties we're supporting use that
32 * feature. If it comes across properties it doesn't recognize, it should
33 * ignore them.
35 * The public methods one would call in this class are
36 * - parse( $content )
37 * Reads in xmp content.
38 * Can potentially be called multiple times with partial data each time.
39 * - parseExtended( $content )
40 * Reads XMPExtended blocks (jpeg files only).
41 * - getResults
42 * Outputs a results array.
44 * Note XMP kind of looks like rdf. They are not the same thing - XMP is
45 * encoded as a specific subset of rdf. This class can read XMP. It cannot
46 * read rdf.
49 class XMPReader {
51 private $curItem = array(); // array to hold the current element (and previous element, and so on)
52 private $ancestorStruct = false; // the structure name when processing nested structures.
53 private $charContent = false; // temporary holder for character data that appears in xmp doc.
54 private $mode = array(); // stores the state the xmpreader is in (see MODE_FOO constants)
55 private $results = array(); // array to hold results
56 private $processingArray = false; // if we're doing a seq or bag.
57 private $itemLang = false; // used for lang alts only
59 private $xmlParser;
60 private $charset = false;
61 private $extendedXMPOffset = 0;
63 protected $items;
65 /**
66 * These are various mode constants.
67 * they are used to figure out what to do
68 * with an element when its encountered.
70 * For example, MODE_IGNORE is used when processing
71 * a property we're not interested in. So if a new
72 * element pops up when we're in that mode, we ignore it.
74 const MODE_INITIAL = 0;
75 const MODE_IGNORE = 1;
76 const MODE_LI = 2;
77 const MODE_LI_LANG = 3;
78 const MODE_QDESC = 4;
80 // The following MODE constants are also used in the
81 // $items array to denote what type of property the item is.
82 const MODE_SIMPLE = 10;
83 const MODE_STRUCT = 11; // structure (associative array)
84 const MODE_SEQ = 12; // ordered list
85 const MODE_BAG = 13; // unordered list
86 const MODE_LANG = 14;
87 const MODE_ALT = 15; // non-language alt. Currently not implemented, and not needed atm.
88 const MODE_BAGSTRUCT = 16; // A BAG of Structs.
90 const NS_RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
91 const NS_XML = 'http://www.w3.org/XML/1998/namespace';
93 /**
94 * Constructor.
96 * Primary job is to initialize the XMLParser
98 function __construct() {
100 if ( !function_exists( 'xml_parser_create_ns' ) ) {
101 // this should already be checked by this point
102 throw new MWException( 'XMP support requires XML Parser' );
105 $this->items = XMPInfo::getItems();
107 $this->resetXMLParser();
111 * Main use is if a single item has multiple xmp documents describing it.
112 * For example in jpeg's with extendedXMP
114 private function resetXMLParser() {
116 if ( $this->xmlParser ) {
117 //is this needed?
118 xml_parser_free( $this->xmlParser );
121 $this->xmlParser = xml_parser_create_ns( 'UTF-8', ' ' );
122 xml_parser_set_option( $this->xmlParser, XML_OPTION_CASE_FOLDING, 0 );
123 xml_parser_set_option( $this->xmlParser, XML_OPTION_SKIP_WHITE, 1 );
125 xml_set_element_handler( $this->xmlParser,
126 array( $this, 'startElement' ),
127 array( $this, 'endElement' ) );
129 xml_set_character_data_handler( $this->xmlParser, array( $this, 'char' ) );
132 /** Destroy the xml parser
134 * Not sure if this is actually needed.
136 function __destruct() {
137 // not sure if this is needed.
138 xml_parser_free( $this->xmlParser );
141 /** Get the result array. Do some post-processing before returning
142 * the array, and transform any metadata that is special-cased.
144 * @return Array array of results as an array of arrays suitable for
145 * FormatMetadata::getFormattedData().
147 public function getResults() {
148 // xmp-special is for metadata that affects how stuff
149 // is extracted. For example xmpNote:HasExtendedXMP.
151 // It is also used to handle photoshop:AuthorsPosition
152 // which is weird and really part of another property,
153 // see 2:85 in IPTC. See also pg 21 of IPTC4XMP standard.
154 // The location fields also use it.
156 $data = $this->results;
158 wfRunHooks( 'XMPGetResults', Array( &$data ) );
160 if ( isset( $data['xmp-special']['AuthorsPosition'] )
161 && is_string( $data['xmp-special']['AuthorsPosition'] )
162 && isset( $data['xmp-general']['Artist'][0] )
164 // Note, if there is more than one creator,
165 // this only applies to first. This also will
166 // only apply to the dc:Creator prop, not the
167 // exif:Artist prop.
169 $data['xmp-general']['Artist'][0] =
170 $data['xmp-special']['AuthorsPosition'] . ', '
171 . $data['xmp-general']['Artist'][0];
174 // Go through the LocationShown and LocationCreated
175 // changing it to the non-hierarchal form used by
176 // the other location fields.
178 if ( isset( $data['xmp-special']['LocationShown'][0] )
179 && is_array( $data['xmp-special']['LocationShown'][0] )
181 // the is_array is just paranoia. It should always
182 // be an array.
183 foreach ( $data['xmp-special']['LocationShown'] as $loc ) {
184 if ( !is_array( $loc ) ) {
185 // To avoid copying over the _type meta-fields.
186 continue;
188 foreach ( $loc as $field => $val ) {
189 $data['xmp-general'][$field . 'Dest'][] = $val;
193 if ( isset( $data['xmp-special']['LocationCreated'][0] )
194 && is_array( $data['xmp-special']['LocationCreated'][0] )
196 // the is_array is just paranoia. It should always
197 // be an array.
198 foreach ( $data['xmp-special']['LocationCreated'] as $loc ) {
199 if ( !is_array( $loc ) ) {
200 // To avoid copying over the _type meta-fields.
201 continue;
203 foreach ( $loc as $field => $val ) {
204 $data['xmp-general'][$field . 'Created'][] = $val;
209 // We don't want to return the special values, since they're
210 // special and not info to be stored about the file.
211 unset( $data['xmp-special'] );
213 // Convert GPSAltitude to negative if below sea level.
214 if ( isset( $data['xmp-exif']['GPSAltitudeRef'] )
215 && isset( $data['xmp-exif']['GPSAltitude'] )
218 // Must convert to a real before multiplying by -1
219 // XMPValidate guarantees there will always be a '/' in this value.
220 list( $nom, $denom ) = explode( '/', $data['xmp-exif']['GPSAltitude'] );
221 $data['xmp-exif']['GPSAltitude'] = $nom / $denom;
223 if ( $data['xmp-exif']['GPSAltitudeRef'] == '1' ) {
224 $data['xmp-exif']['GPSAltitude'] *= -1;
226 unset( $data['xmp-exif']['GPSAltitudeRef'] );
229 return $data;
233 * Main function to call to parse XMP. Use getResults to
234 * get results.
236 * Also catches any errors during processing, writes them to
237 * debug log, blanks result array and returns false.
239 * @param string $content XMP data
240 * @param $allOfIt Boolean: If this is all the data (true) or if its split up (false). Default true
241 * @param $reset Boolean: does xml parser need to be reset. Default false
242 * @throws MWException
243 * @return Boolean success.
245 public function parse( $content, $allOfIt = true, $reset = false ) {
246 if ( $reset ) {
247 $this->resetXMLParser();
249 try {
251 // detect encoding by looking for BOM which is supposed to be in processing instruction.
252 // see page 12 of http://www.adobe.com/devnet/xmp/pdfs/XMPSpecificationPart3.pdf
253 if ( !$this->charset ) {
254 $bom = array();
255 if ( preg_match( '/\xEF\xBB\xBF|\xFE\xFF|\x00\x00\xFE\xFF|\xFF\xFE\x00\x00|\xFF\xFE/',
256 $content, $bom )
258 switch ( $bom[0] ) {
259 case "\xFE\xFF":
260 $this->charset = 'UTF-16BE';
261 break;
262 case "\xFF\xFE":
263 $this->charset = 'UTF-16LE';
264 break;
265 case "\x00\x00\xFE\xFF":
266 $this->charset = 'UTF-32BE';
267 break;
268 case "\xFF\xFE\x00\x00":
269 $this->charset = 'UTF-32LE';
270 break;
271 case "\xEF\xBB\xBF":
272 $this->charset = 'UTF-8';
273 break;
274 default:
275 //this should be impossible to get to
276 throw new MWException( "Invalid BOM" );
278 } else {
279 // standard specifically says, if no bom assume utf-8
280 $this->charset = 'UTF-8';
283 if ( $this->charset !== 'UTF-8' ) {
284 //don't convert if already utf-8
285 wfSuppressWarnings();
286 $content = iconv( $this->charset, 'UTF-8//IGNORE', $content );
287 wfRestoreWarnings();
290 $ok = xml_parse( $this->xmlParser, $content, $allOfIt );
291 if ( !$ok ) {
292 $error = xml_error_string( xml_get_error_code( $this->xmlParser ) );
293 $where = 'line: ' . xml_get_current_line_number( $this->xmlParser )
294 . ' column: ' . xml_get_current_column_number( $this->xmlParser )
295 . ' byte offset: ' . xml_get_current_byte_index( $this->xmlParser );
297 wfDebugLog( 'XMP', "XMPReader::parse : Error reading XMP content: $error ($where)" );
298 $this->results = array(); // blank if error.
299 return false;
301 } catch ( MWException $e ) {
302 wfDebugLog( 'XMP', 'XMP parse error: ' . $e );
303 $this->results = array();
304 return false;
306 return true;
309 /** Entry point for XMPExtended blocks in jpeg files
311 * @todo In serious need of testing
312 * @see http://www.adobe.ge/devnet/xmp/pdfs/XMPSpecificationPart3.pdf XMP spec part 3 page 20
313 * @param string $content XMPExtended block minus the namespace signature
314 * @return Boolean If it succeeded.
316 public function parseExtended( $content ) {
317 // @todo FIXME: This is untested. Hard to find example files
318 // or programs that make such files..
319 $guid = substr( $content, 0, 32 );
320 if ( !isset( $this->results['xmp-special']['HasExtendedXMP'] )
321 || $this->results['xmp-special']['HasExtendedXMP'] !== $guid ) {
322 wfDebugLog( 'XMP', __METHOD__ . " Ignoring XMPExtended block due to wrong guid (guid= '$guid')" );
323 return false;
325 $len = unpack( 'Nlength/Noffset', substr( $content, 32, 8 ) );
327 if ( !$len || $len['length'] < 4 || $len['offset'] < 0 || $len['offset'] > $len['length'] ) {
328 wfDebugLog( 'XMP', __METHOD__ . 'Error reading extended XMP block, invalid length or offset.' );
329 return false;
332 // we're not very robust here. we should accept it in the wrong order. To quote
333 // the xmp standard:
334 // "A JPEG writer should write the ExtendedXMP marker segments in order, immediately following the
335 // StandardXMP. However, the JPEG standard does not require preservation of marker segment order. A
336 // robust JPEG reader should tolerate the marker segments in any order."
338 // otoh the probability that an image will have more than 128k of metadata is rather low...
339 // so the probability that it will have > 128k, and be in the wrong order is very low...
341 if ( $len['offset'] !== $this->extendedXMPOffset ) {
342 wfDebugLog( 'XMP', __METHOD__ . 'Ignoring XMPExtended block due to wrong order. (Offset was '
343 . $len['offset'] . ' but expected ' . $this->extendedXMPOffset . ')' );
344 return false;
347 if ( $len['offset'] === 0 ) {
348 // if we're starting the extended block, we've probably already
349 // done the XMPStandard block, so reset.
350 $this->resetXMLParser();
353 $this->extendedXMPOffset += $len['length'];
355 $actualContent = substr( $content, 40 );
357 if ( $this->extendedXMPOffset === strlen( $actualContent ) ) {
358 $atEnd = true;
359 } else {
360 $atEnd = false;
363 wfDebugLog( 'XMP', __METHOD__ . 'Parsing a XMPExtended block' );
364 return $this->parse( $actualContent, $atEnd );
368 * Character data handler
369 * Called whenever character data is found in the xmp document.
371 * does nothing if we're in MODE_IGNORE or if the data is whitespace
372 * throws an error if we're not in MODE_SIMPLE (as we're not allowed to have character
373 * data in the other modes).
375 * As an example, this happens when we encounter XMP like:
376 * <exif:DigitalZoomRatio>0/10</exif:DigitalZoomRatio>
377 * and are processing the 0/10 bit.
379 * @param $parser XMLParser reference to the xml parser
380 * @param string $data Character data
381 * @throws MWException on invalid data
383 function char( $parser, $data ) {
385 $data = trim( $data );
386 if ( trim( $data ) === "" ) {
387 return;
390 if ( !isset( $this->mode[0] ) ) {
391 throw new MWException( 'Unexpected character data before first rdf:Description element' );
394 if ( $this->mode[0] === self::MODE_IGNORE ) {
395 return;
398 if ( $this->mode[0] !== self::MODE_SIMPLE
399 && $this->mode[0] !== self::MODE_QDESC
401 throw new MWException( 'character data where not expected. (mode ' . $this->mode[0] . ')' );
404 // to check, how does this handle w.s.
405 if ( $this->charContent === false ) {
406 $this->charContent = $data;
407 } else {
408 $this->charContent .= $data;
413 /** When we hit a closing element in MODE_IGNORE
414 * Check to see if this is the element we started to ignore,
415 * in which case we get out of MODE_IGNORE
417 * @param string $elm Namespace of element followed by a space and then tag name of element.
419 private function endElementModeIgnore( $elm ) {
420 if ( $this->curItem[0] === $elm ) {
421 array_shift( $this->curItem );
422 array_shift( $this->mode );
427 * Hit a closing element when in MODE_SIMPLE.
428 * This generally means that we finished processing a
429 * property value, and now have to save the result to the
430 * results array
432 * For example, when processing:
433 * <exif:DigitalZoomRatio>0/10</exif:DigitalZoomRatio>
434 * this deals with when we hit </exif:DigitalZoomRatio>.
436 * Or it could be if we hit the end element of a property
437 * of a compound data structure (like a member of an array).
439 * @param string $elm namespace, space, and tag name.
441 private function endElementModeSimple( $elm ) {
442 if ( $this->charContent !== false ) {
443 if ( $this->processingArray ) {
444 // if we're processing an array, use the original element
445 // name instead of rdf:li.
446 list( $ns, $tag ) = explode( ' ', $this->curItem[0], 2 );
447 } else {
448 list( $ns, $tag ) = explode( ' ', $elm, 2 );
450 $this->saveValue( $ns, $tag, $this->charContent );
452 $this->charContent = false; // reset
454 array_shift( $this->curItem );
455 array_shift( $this->mode );
460 * Hit a closing element in MODE_STRUCT, MODE_SEQ, MODE_BAG
461 * generally means we've finished processing a nested structure.
462 * resets some internal variables to indicate that.
464 * Note this means we hit the closing element not the "</rdf:Seq>".
466 * @par For example, when processing:
467 * @code{,xml}
468 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
469 * </rdf:Seq> </exif:ISOSpeedRatings>
470 * @endcode
472 * This method is called when we hit the "</exif:ISOSpeedRatings>" tag.
474 * @param string $elm namespace . space . tag name.
475 * @throws MWException
477 private function endElementNested( $elm ) {
479 /* cur item must be the same as $elm, unless if in MODE_STRUCT
480 in which case it could also be rdf:Description */
481 if ( $this->curItem[0] !== $elm
482 && !( $elm === self::NS_RDF . ' Description'
483 && $this->mode[0] === self::MODE_STRUCT )
485 throw new MWException( "nesting mismatch. got a </$elm> but expected a </" . $this->curItem[0] . '>' );
488 // Validate structures.
489 list( $ns, $tag ) = explode( ' ', $elm, 2 );
490 if ( isset( $this->items[$ns][$tag]['validate'] ) ) {
492 $info =& $this->items[$ns][$tag];
493 $finalName = isset( $info['map_name'] )
494 ? $info['map_name'] : $tag;
496 $validate = is_array( $info['validate'] ) ? $info['validate']
497 : array( 'XMPValidate', $info['validate'] );
499 if ( !isset( $this->results['xmp-' . $info['map_group']][$finalName] ) ) {
500 // This can happen if all the members of the struct failed validation.
501 wfDebugLog( 'XMP', __METHOD__ . " <$ns:$tag> has no valid members." );
503 } elseif ( is_callable( $validate ) ) {
504 $val =& $this->results['xmp-' . $info['map_group']][$finalName];
505 call_user_func_array( $validate, array( $info, &$val, false ) );
506 if ( is_null( $val ) ) {
507 // the idea being the validation function will unset the variable if
508 // its invalid.
509 wfDebugLog( 'XMP', __METHOD__ . " <$ns:$tag> failed validation." );
510 unset( $this->results['xmp-' . $info['map_group']][$finalName] );
512 } else {
513 wfDebugLog( 'XMP', __METHOD__ . " Validation function for $finalName ("
514 . $validate[0] . '::' . $validate[1] . '()) is not callable.' );
518 array_shift( $this->curItem );
519 array_shift( $this->mode );
520 $this->ancestorStruct = false;
521 $this->processingArray = false;
522 $this->itemLang = false;
526 * Hit a closing element in MODE_LI (either rdf:Seq, or rdf:Bag )
527 * Add information about what type of element this is.
529 * Note we still have to hit the outer "</property>"
531 * @par For example, when processing:
532 * @code{,xml}
533 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
534 * </rdf:Seq> </exif:ISOSpeedRatings>
535 * @endcode
537 * This method is called when we hit the "</rdf:Seq>".
538 * (For comparison, we call endElementModeSimple when we
539 * hit the "</rdf:li>")
541 * @param string $elm namespace . ' ' . element name
542 * @throws MWException
544 private function endElementModeLi( $elm ) {
546 list( $ns, $tag ) = explode( ' ', $this->curItem[0], 2 );
547 $info = $this->items[$ns][$tag];
548 $finalName = isset( $info['map_name'] )
549 ? $info['map_name'] : $tag;
551 array_shift( $this->mode );
553 if ( !isset( $this->results['xmp-' . $info['map_group']][$finalName] ) ) {
554 wfDebugLog( 'XMP', __METHOD__ . " Empty compund element $finalName." );
555 return;
558 if ( $elm === self::NS_RDF . ' Seq' ) {
559 $this->results['xmp-' . $info['map_group']][$finalName]['_type'] = 'ol';
560 } elseif ( $elm === self::NS_RDF . ' Bag' ) {
561 $this->results['xmp-' . $info['map_group']][$finalName]['_type'] = 'ul';
562 } elseif ( $elm === self::NS_RDF . ' Alt' ) {
563 // extra if needed as you could theoretically have a non-language alt.
564 if ( $info['mode'] === self::MODE_LANG ) {
565 $this->results['xmp-' . $info['map_group']][$finalName]['_type'] = 'lang';
568 } else {
569 throw new MWException( __METHOD__ . " expected </rdf:seq> or </rdf:bag> but instead got $elm." );
574 * End element while in MODE_QDESC
575 * mostly when ending an element when we have a simple value
576 * that has qualifiers.
578 * Qualifiers aren't all that common, and we don't do anything
579 * with them.
581 * @param string $elm namespace and element
583 private function endElementModeQDesc( $elm ) {
585 if ( $elm === self::NS_RDF . ' value' ) {
586 list( $ns, $tag ) = explode( ' ', $this->curItem[0], 2 );
587 $this->saveValue( $ns, $tag, $this->charContent );
588 return;
589 } else {
590 array_shift( $this->mode );
591 array_shift( $this->curItem );
596 * Handler for hitting a closing element.
598 * generally just calls a helper function depending on what
599 * mode we're in.
601 * Ignores the outer wrapping elements that are optional in
602 * xmp and have no meaning.
604 * @param $parser XMLParser
605 * @param string $elm namespace . ' ' . element name
606 * @throws MWException
608 function endElement( $parser, $elm ) {
609 if ( $elm === ( self::NS_RDF . ' RDF' )
610 || $elm === 'adobe:ns:meta/ xmpmeta'
611 || $elm === 'adobe:ns:meta/ xapmeta' )
613 // ignore these.
614 return;
617 if ( $elm === self::NS_RDF . ' type' ) {
618 // these aren't really supported properly yet.
619 // However, it appears they almost never used.
620 wfDebugLog( 'XMP', __METHOD__ . ' encountered <rdf:type>' );
623 if ( strpos( $elm, ' ' ) === false ) {
624 // This probably shouldn't happen.
625 // However, there is a bug in an adobe product
626 // that forgets the namespace on some things.
627 // (Luckily they are unimportant things).
628 wfDebugLog( 'XMP', __METHOD__ . " Encountered </$elm> which has no namespace. Skipping." );
629 return;
632 if ( count( $this->mode[0] ) === 0 ) {
633 // This should never ever happen and means
634 // there is a pretty major bug in this class.
635 throw new MWException( 'Encountered end element with no mode' );
638 if ( count( $this->curItem ) == 0 && $this->mode[0] !== self::MODE_INITIAL ) {
639 // just to be paranoid. Should always have a curItem, except for initially
640 // (aka during MODE_INITAL).
641 throw new MWException( "Hit end element </$elm> but no curItem" );
644 switch ( $this->mode[0] ) {
645 case self::MODE_IGNORE:
646 $this->endElementModeIgnore( $elm );
647 break;
648 case self::MODE_SIMPLE:
649 $this->endElementModeSimple( $elm );
650 break;
651 case self::MODE_STRUCT:
652 case self::MODE_SEQ:
653 case self::MODE_BAG:
654 case self::MODE_LANG:
655 case self::MODE_BAGSTRUCT:
656 $this->endElementNested( $elm );
657 break;
658 case self::MODE_INITIAL:
659 if ( $elm === self::NS_RDF . ' Description' ) {
660 array_shift( $this->mode );
661 } else {
662 throw new MWException( 'Element ended unexpectedly while in MODE_INITIAL' );
664 break;
665 case self::MODE_LI:
666 case self::MODE_LI_LANG:
667 $this->endElementModeLi( $elm );
668 break;
669 case self::MODE_QDESC:
670 $this->endElementModeQDesc( $elm );
671 break;
672 default:
673 wfDebugLog( 'XMP', __METHOD__ . " no mode (elm = $elm)" );
674 break;
679 * Hit an opening element while in MODE_IGNORE
681 * XMP is extensible, so ignore any tag we don't understand.
683 * Mostly ignores, unless we encounter the element that we are ignoring.
684 * in which case we add it to the item stack, so we can ignore things
685 * that are nested, correctly.
687 * @param string $elm namespace . ' ' . tag name
689 private function startElementModeIgnore( $elm ) {
690 if ( $elm === $this->curItem[0] ) {
691 array_unshift( $this->curItem, $elm );
692 array_unshift( $this->mode, self::MODE_IGNORE );
697 * Start element in MODE_BAG (unordered array)
698 * this should always be <rdf:Bag>
700 * @param string $elm namespace . ' ' . tag
701 * @throws MWException if we have an element that's not <rdf:Bag>
703 private function startElementModeBag( $elm ) {
704 if ( $elm === self::NS_RDF . ' Bag' ) {
705 array_unshift( $this->mode, self::MODE_LI );
706 } else {
707 throw new MWException( "Expected <rdf:Bag> but got $elm." );
713 * Start element in MODE_SEQ (ordered array)
714 * this should always be <rdf:Seq>
716 * @param string $elm namespace . ' ' . tag
717 * @throws MWException if we have an element that's not <rdf:Seq>
719 private function startElementModeSeq( $elm ) {
720 if ( $elm === self::NS_RDF . ' Seq' ) {
721 array_unshift( $this->mode, self::MODE_LI );
722 } elseif ( $elm === self::NS_RDF . ' Bag' ) {
723 # bug 27105
724 wfDebugLog( 'XMP', __METHOD__ . ' Expected an rdf:Seq, but got an rdf:Bag. Pretending'
725 . ' it is a Seq, since some buggy software is known to screw this up.' );
726 array_unshift( $this->mode, self::MODE_LI );
727 } else {
728 throw new MWException( "Expected <rdf:Seq> but got $elm." );
734 * Start element in MODE_LANG (language alternative)
735 * this should always be <rdf:Alt>
737 * This tag tends to be used for metadata like describe this
738 * picture, which can be translated into multiple languages.
740 * XMP supports non-linguistic alternative selections,
741 * which are really only used for thumbnails, which
742 * we don't care about.
744 * @param string $elm namespace . ' ' . tag
745 * @throws MWException if we have an element that's not <rdf:Alt>
747 private function startElementModeLang( $elm ) {
748 if ( $elm === self::NS_RDF . ' Alt' ) {
749 array_unshift( $this->mode, self::MODE_LI_LANG );
750 } else {
751 throw new MWException( "Expected <rdf:Seq> but got $elm." );
757 * Handle an opening element when in MODE_SIMPLE
759 * This should not happen often. This is for if a simple element
760 * already opened has a child element. Could happen for a
761 * qualified element.
763 * For example:
764 * <exif:DigitalZoomRatio><rdf:Description><rdf:value>0/10</rdf:value>
765 * <foo:someQualifier>Bar</foo:someQualifier> </rdf:Description>
766 * </exif:DigitalZoomRatio>
768 * This method is called when processing the <rdf:Description> element
770 * @param string $elm namespace and tag names separated by space.
771 * @param array $attribs Attributes of the element.
772 * @throws MWException
774 private function startElementModeSimple( $elm, $attribs ) {
775 if ( $elm === self::NS_RDF . ' Description' ) {
776 // If this value has qualifiers
777 array_unshift( $this->mode, self::MODE_QDESC );
778 array_unshift( $this->curItem, $this->curItem[0] );
780 if ( isset( $attribs[self::NS_RDF . ' value'] ) ) {
781 list( $ns, $tag ) = explode( ' ', $this->curItem[0], 2 );
782 $this->saveValue( $ns, $tag, $attribs[self::NS_RDF . ' value'] );
784 } elseif ( $elm === self::NS_RDF . ' value' ) {
785 // This should not be here.
786 throw new MWException( __METHOD__ . ' Encountered <rdf:value> where it was unexpected.' );
788 } else {
789 // something else we don't recognize, like a qualifier maybe.
790 wfDebugLog( 'XMP', __METHOD__ . " Encountered element <$elm> where only expecting character data as value of " . $this->curItem[0] );
791 array_unshift( $this->mode, self::MODE_IGNORE );
792 array_unshift( $this->curItem, $elm );
799 * Start an element when in MODE_QDESC.
800 * This generally happens when a simple element has an inner
801 * rdf:Description to hold qualifier elements.
803 * For example in:
804 * <exif:DigitalZoomRatio><rdf:Description><rdf:value>0/10</rdf:value>
805 * <foo:someQualifier>Bar</foo:someQualifier> </rdf:Description>
806 * </exif:DigitalZoomRatio>
807 * Called when processing the <rdf:value> or <foo:someQualifier>.
809 * @param string $elm namespace and tag name separated by a space.
812 private function startElementModeQDesc( $elm ) {
813 if ( $elm === self::NS_RDF . ' value' ) {
814 return; // do nothing
815 } else {
816 // otherwise its a qualifier, which we ignore
817 array_unshift( $this->mode, self::MODE_IGNORE );
818 array_unshift( $this->curItem, $elm );
823 * Starting an element when in MODE_INITIAL
824 * This usually happens when we hit an element inside
825 * the outer rdf:Description
827 * This is generally where most properties start.
829 * @param string $ns Namespace
830 * @param string $tag tag name (without namespace prefix)
831 * @param array $attribs array of attributes
832 * @throws MWException
834 private function startElementModeInitial( $ns, $tag, $attribs ) {
835 if ( $ns !== self::NS_RDF ) {
837 if ( isset( $this->items[$ns][$tag] ) ) {
838 if ( isset( $this->items[$ns][$tag]['structPart'] ) ) {
839 // If this element is supposed to appear only as
840 // a child of a structure, but appears here (not as
841 // a child of a struct), then something weird is
842 // happening, so ignore this element and its children.
844 wfDebugLog( 'XMP', "Encountered <$ns:$tag> outside"
845 . " of its expected parent. Ignoring." );
847 array_unshift( $this->mode, self::MODE_IGNORE );
848 array_unshift( $this->curItem, $ns . ' ' . $tag );
849 return;
851 $mode = $this->items[$ns][$tag]['mode'];
852 array_unshift( $this->mode, $mode );
853 array_unshift( $this->curItem, $ns . ' ' . $tag );
854 if ( $mode === self::MODE_STRUCT ) {
855 $this->ancestorStruct = isset( $this->items[$ns][$tag]['map_name'] )
856 ? $this->items[$ns][$tag]['map_name'] : $tag;
858 if ( $this->charContent !== false ) {
859 // Something weird.
860 // Should not happen in valid XMP.
861 throw new MWException( 'tag nested in non-whitespace characters.' );
863 } else {
864 // This element is not on our list of allowed elements so ignore.
865 wfDebugLog( 'XMP', __METHOD__ . " Ignoring unrecognized element <$ns:$tag>." );
866 array_unshift( $this->mode, self::MODE_IGNORE );
867 array_unshift( $this->curItem, $ns . ' ' . $tag );
868 return;
872 // process attributes
873 $this->doAttribs( $attribs );
877 * Hit an opening element when in a Struct (MODE_STRUCT)
878 * This is generally for fields of a compound property.
880 * Example of a struct (abbreviated; flash has more properties):
882 * <exif:Flash> <rdf:Description> <exif:Fired>True</exif:Fired>
883 * <exif:Mode>1</exif:Mode></rdf:Description></exif:Flash>
885 * or:
887 * <exif:Flash rdf:parseType='Resource'> <exif:Fired>True</exif:Fired>
888 * <exif:Mode>1</exif:Mode></exif:Flash>
890 * @param string $ns namespace
891 * @param string $tag tag name (no ns)
892 * @param array $attribs array of attribs w/ values.
893 * @throws MWException
895 private function startElementModeStruct( $ns, $tag, $attribs ) {
896 if ( $ns !== self::NS_RDF ) {
898 if ( isset( $this->items[$ns][$tag] ) ) {
899 if ( isset( $this->items[$ns][$this->ancestorStruct]['children'] )
900 && !isset( $this->items[$ns][$this->ancestorStruct]['children'][$tag] ) )
902 // This assumes that we don't have inter-namespace nesting
903 // which we don't in all the properties we're interested in.
904 throw new MWException( " <$tag> appeared nested in <" . $this->ancestorStruct
905 . "> where it is not allowed." );
907 array_unshift( $this->mode, $this->items[$ns][$tag]['mode'] );
908 array_unshift( $this->curItem, $ns . ' ' . $tag );
909 if ( $this->charContent !== false ) {
910 // Something weird.
911 // Should not happen in valid XMP.
912 throw new MWException( "tag <$tag> nested in non-whitespace characters (" . $this->charContent . ")." );
914 } else {
915 array_unshift( $this->mode, self::MODE_IGNORE );
916 array_unshift( $this->curItem, $elm );
917 return;
922 if ( $ns === self::NS_RDF && $tag === 'Description' ) {
923 $this->doAttribs( $attribs );
924 array_unshift( $this->mode, self::MODE_STRUCT );
925 array_unshift( $this->curItem, $this->curItem[0] );
930 * opening element in MODE_LI
931 * process elements of arrays.
933 * Example:
934 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
935 * </rdf:Seq> </exif:ISOSpeedRatings>
936 * This method is called when we hit the <rdf:li> element.
938 * @param string $elm namespace . ' ' . tagname
939 * @param array $attribs Attributes. (needed for BAGSTRUCTS)
940 * @throws MWException if gets a tag other than <rdf:li>
942 private function startElementModeLi( $elm, $attribs ) {
943 if ( ( $elm ) !== self::NS_RDF . ' li' ) {
944 throw new MWException( "<rdf:li> expected but got $elm." );
947 if ( !isset( $this->mode[1] ) ) {
948 // This should never ever ever happen. Checking for it
949 // to be paranoid.
950 throw new MWException( 'In mode Li, but no 2xPrevious mode!' );
953 if ( $this->mode[1] === self::MODE_BAGSTRUCT ) {
954 // This list item contains a compound (STRUCT) value.
955 array_unshift( $this->mode, self::MODE_STRUCT );
956 array_unshift( $this->curItem, $elm );
957 $this->processingArray = true;
959 if ( !isset( $this->curItem[1] ) ) {
960 // be paranoid.
961 throw new MWException( 'Can not find parent of BAGSTRUCT.' );
963 list( $curNS, $curTag ) = explode( ' ', $this->curItem[1] );
964 $this->ancestorStruct = isset( $this->items[$curNS][$curTag]['map_name'] )
965 ? $this->items[$curNS][$curTag]['map_name'] : $curTag;
967 $this->doAttribs( $attribs );
969 } else {
970 // Normal BAG or SEQ containing simple values.
971 array_unshift( $this->mode, self::MODE_SIMPLE );
972 // need to add curItem[0] on again since one is for the specific item
973 // and one is for the entire group.
974 array_unshift( $this->curItem, $this->curItem[0] );
975 $this->processingArray = true;
981 * Opening element in MODE_LI_LANG.
982 * process elements of language alternatives
984 * Example:
985 * <dc:title> <rdf:Alt> <rdf:li xml:lang="x-default">My house
986 * </rdf:li> </rdf:Alt> </dc:title>
988 * This method is called when we hit the <rdf:li> element.
990 * @param string $elm namespace . ' ' . tag
991 * @param array $attribs array of elements (most importantly xml:lang)
992 * @throws MWException if gets a tag other than <rdf:li> or if no xml:lang
994 private function startElementModeLiLang( $elm, $attribs ) {
995 if ( $elm !== self::NS_RDF . ' li' ) {
996 throw new MWException( __METHOD__ . " <rdf:li> expected but got $elm." );
998 if ( !isset( $attribs[self::NS_XML . ' lang'] )
999 || !preg_match( '/^[-A-Za-z0-9]{2,}$/D', $attribs[self::NS_XML . ' lang'] ) )
1001 throw new MWException( __METHOD__
1002 . " <rdf:li> did not contain, or has invalid xml:lang attribute in lang alternative" );
1005 // Lang is case-insensitive.
1006 $this->itemLang = strtolower( $attribs[self::NS_XML . ' lang'] );
1008 // need to add curItem[0] on again since one is for the specific item
1009 // and one is for the entire group.
1010 array_unshift( $this->curItem, $this->curItem[0] );
1011 array_unshift( $this->mode, self::MODE_SIMPLE );
1012 $this->processingArray = true;
1016 * Hits an opening element.
1017 * Generally just calls a helper based on what MODE we're in.
1018 * Also does some initial set up for the wrapper element
1020 * @param $parser XMLParser
1021 * @param string $elm namespace "<space>" element
1022 * @param array $attribs attribute name => value
1023 * @throws MWException
1025 function startElement( $parser, $elm, $attribs ) {
1027 if ( $elm === self::NS_RDF . ' RDF'
1028 || $elm === 'adobe:ns:meta/ xmpmeta'
1029 || $elm === 'adobe:ns:meta/ xapmeta' )
1031 /* ignore. */
1032 return;
1033 } elseif ( $elm === self::NS_RDF . ' Description' ) {
1034 if ( count( $this->mode ) === 0 ) {
1035 // outer rdf:desc
1036 array_unshift( $this->mode, self::MODE_INITIAL );
1038 } elseif ( $elm === self::NS_RDF . ' type' ) {
1039 // This doesn't support rdf:type properly.
1040 // In practise I have yet to see a file that
1041 // uses this element, however it is mentioned
1042 // on page 25 of part 1 of the xmp standard.
1044 // also it seems as if exiv2 and exiftool do not support
1045 // this either (That or I misunderstand the standard)
1046 wfDebugLog( 'XMP', __METHOD__ . ' Encountered <rdf:type> which isn\'t currently supported' );
1049 if ( strpos( $elm, ' ' ) === false ) {
1050 // This probably shouldn't happen.
1051 wfDebugLog( 'XMP', __METHOD__ . " Encountered <$elm> which has no namespace. Skipping." );
1052 return;
1055 list( $ns, $tag ) = explode( ' ', $elm, 2 );
1057 if ( count( $this->mode ) === 0 ) {
1058 // This should not happen.
1059 throw new MWException( 'Error extracting XMP, '
1060 . "encountered <$elm> with no mode" );
1063 switch ( $this->mode[0] ) {
1064 case self::MODE_IGNORE:
1065 $this->startElementModeIgnore( $elm );
1066 break;
1067 case self::MODE_SIMPLE:
1068 $this->startElementModeSimple( $elm, $attribs );
1069 break;
1070 case self::MODE_INITIAL:
1071 $this->startElementModeInitial( $ns, $tag, $attribs );
1072 break;
1073 case self::MODE_STRUCT:
1074 $this->startElementModeStruct( $ns, $tag, $attribs );
1075 break;
1076 case self::MODE_BAG:
1077 case self::MODE_BAGSTRUCT:
1078 $this->startElementModeBag( $elm );
1079 break;
1080 case self::MODE_SEQ:
1081 $this->startElementModeSeq( $elm );
1082 break;
1083 case self::MODE_LANG:
1084 $this->startElementModeLang( $elm );
1085 break;
1086 case self::MODE_LI_LANG:
1087 $this->startElementModeLiLang( $elm, $attribs );
1088 break;
1089 case self::MODE_LI:
1090 $this->startElementModeLi( $elm, $attribs );
1091 break;
1092 case self::MODE_QDESC:
1093 $this->startElementModeQDesc( $elm );
1094 break;
1095 default:
1096 throw new MWException( 'StartElement in unknown mode: ' . $this->mode[0] );
1101 * Process attributes.
1102 * Simple values can be stored as either a tag or attribute
1104 * Often the initial "<rdf:Description>" tag just has all the simple
1105 * properties as attributes.
1107 * @par Example:
1108 * @code
1109 * <rdf:Description rdf:about="" xmlns:exif="http://ns.adobe.com/exif/1.0/" exif:DigitalZoomRatio="0/10">
1110 * @endcode
1112 * @param array $attribs attribute=>value array.
1113 * @throws MWException
1115 private function doAttribs( $attribs ) {
1117 // first check for rdf:parseType attribute, as that can change
1118 // how the attributes are interperted.
1120 if ( isset( $attribs[self::NS_RDF . ' parseType'] )
1121 && $attribs[self::NS_RDF . ' parseType'] === 'Resource'
1122 && $this->mode[0] === self::MODE_SIMPLE )
1124 // this is equivalent to having an inner rdf:Description
1125 $this->mode[0] = self::MODE_QDESC;
1127 foreach ( $attribs as $name => $val ) {
1128 if ( strpos( $name, ' ' ) === false ) {
1129 // This shouldn't happen, but so far some old software forgets namespace
1130 // on rdf:about.
1131 wfDebugLog( 'XMP', __METHOD__ . ' Encountered non-namespaced attribute: '
1132 . " $name=\"$val\". Skipping. " );
1133 continue;
1135 list( $ns, $tag ) = explode( ' ', $name, 2 );
1136 if ( $ns === self::NS_RDF ) {
1137 if ( $tag === 'value' || $tag === 'resource' ) {
1138 // resource is for url.
1139 // value attribute is a weird way of just putting the contents.
1140 $this->char( $this->xmlParser, $val );
1142 } elseif ( isset( $this->items[$ns][$tag] ) ) {
1143 if ( $this->mode[0] === self::MODE_SIMPLE ) {
1144 throw new MWException( __METHOD__
1145 . " $ns:$tag found as attribute where not allowed" );
1147 $this->saveValue( $ns, $tag, $val );
1148 } else {
1149 wfDebugLog( 'XMP', __METHOD__ . " Ignoring unrecognized element <$ns:$tag>." );
1155 * Given an extracted value, save it to results array
1157 * note also uses $this->ancestorStruct and
1158 * $this->processingArray to determine what name to
1159 * save the value under. (in addition to $tag).
1161 * @param string $ns namespace of tag this is for
1162 * @param string $tag tag name
1163 * @param string $val value to save
1165 private function saveValue( $ns, $tag, $val ) {
1167 $info =& $this->items[$ns][$tag];
1168 $finalName = isset( $info['map_name'] )
1169 ? $info['map_name'] : $tag;
1170 if ( isset( $info['validate'] ) ) {
1171 $validate = is_array( $info['validate'] ) ? $info['validate']
1172 : array( 'XMPValidate', $info['validate'] );
1174 if ( is_callable( $validate ) ) {
1175 call_user_func_array( $validate, array( $info, &$val, true ) );
1176 // the reasoning behind using &$val instead of using the return value
1177 // is to be consistent between here and validating structures.
1178 if ( is_null( $val ) ) {
1179 wfDebugLog( 'XMP', __METHOD__ . " <$ns:$tag> failed validation." );
1180 return;
1182 } else {
1183 wfDebugLog( 'XMP', __METHOD__ . " Validation function for $finalName ("
1184 . $validate[0] . '::' . $validate[1] . '()) is not callable.' );
1188 if ( $this->ancestorStruct && $this->processingArray ) {
1189 // Aka both an array and a struct. ( self::MODE_BAGSTRUCT )
1190 $this->results['xmp-' . $info['map_group']][$this->ancestorStruct][][$finalName] = $val;
1191 } elseif ( $this->ancestorStruct ) {
1192 $this->results['xmp-' . $info['map_group']][$this->ancestorStruct][$finalName] = $val;
1193 } elseif ( $this->processingArray ) {
1194 if ( $this->itemLang === false ) {
1195 // normal array
1196 $this->results['xmp-' . $info['map_group']][$finalName][] = $val;
1197 } else {
1198 // lang array.
1199 $this->results['xmp-' . $info['map_group']][$finalName][$this->itemLang] = $val;
1201 } else {
1202 $this->results['xmp-' . $info['map_group']][$finalName] = $val;