Merge "Fixed wrong EnqueueJob comment"
[mediawiki.git] / includes / media / XMP.php
blob50f04ae9c7f140717fcef2178cf7ced112da26be
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 FormatMetadata 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 {
50 /** @var array XMP item configuration array */
51 protected $items;
53 /** @var array Array to hold the current element (and previous element, and so on) */
54 private $curItem = array();
56 /** @var bool|string The structure name when processing nested structures. */
57 private $ancestorStruct = false;
59 /** @var bool|string Temporary holder for character data that appears in xmp doc. */
60 private $charContent = false;
62 /** @var array Stores the state the xmpreader is in (see MODE_FOO constants) */
63 private $mode = array();
65 /** @var array Array to hold results */
66 private $results = array();
68 /** @var bool If we're doing a seq or bag. */
69 private $processingArray = false;
71 /** @var bool|string Used for lang alts only */
72 private $itemLang = false;
74 /** @var resource A resource handle for the XML parser */
75 private $xmlParser;
77 /** @var bool|string Character set like 'UTF-8' */
78 private $charset = false;
80 /** @var int */
81 private $extendedXMPOffset = 0;
83 /** @var int Flag determining if the XMP is safe to parse **/
84 private $parsable = 0;
86 /** @var string Buffer of XML to parse **/
87 private $xmlParsableBuffer = '';
89 /**
90 * These are various mode constants.
91 * they are used to figure out what to do
92 * with an element when its encountered.
94 * For example, MODE_IGNORE is used when processing
95 * a property we're not interested in. So if a new
96 * element pops up when we're in that mode, we ignore it.
98 const MODE_INITIAL = 0;
99 const MODE_IGNORE = 1;
100 const MODE_LI = 2;
101 const MODE_LI_LANG = 3;
102 const MODE_QDESC = 4;
104 // The following MODE constants are also used in the
105 // $items array to denote what type of property the item is.
106 const MODE_SIMPLE = 10;
107 const MODE_STRUCT = 11; // structure (associative array)
108 const MODE_SEQ = 12; // ordered list
109 const MODE_BAG = 13; // unordered list
110 const MODE_LANG = 14;
111 const MODE_ALT = 15; // non-language alt. Currently not implemented, and not needed atm.
112 const MODE_BAGSTRUCT = 16; // A BAG of Structs.
114 const NS_RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
115 const NS_XML = 'http://www.w3.org/XML/1998/namespace';
117 // States used while determining if XML is safe to parse
118 const PARSABLE_UNKNOWN = 0;
119 const PARSABLE_OK = 1;
120 const PARSABLE_BUFFERING = 2;
121 const PARSABLE_NO = 3;
124 * Constructor.
126 * Primary job is to initialize the XMLParser
128 function __construct() {
130 if ( !function_exists( 'xml_parser_create_ns' ) ) {
131 // this should already be checked by this point
132 throw new MWException( 'XMP support requires XML Parser' );
135 $this->items = XMPInfo::getItems();
137 $this->resetXMLParser();
141 * Main use is if a single item has multiple xmp documents describing it.
142 * For example in jpeg's with extendedXMP
144 private function resetXMLParser() {
146 if ( $this->xmlParser ) {
147 //is this needed?
148 xml_parser_free( $this->xmlParser );
151 $this->xmlParser = xml_parser_create_ns( 'UTF-8', ' ' );
152 xml_parser_set_option( $this->xmlParser, XML_OPTION_CASE_FOLDING, 0 );
153 xml_parser_set_option( $this->xmlParser, XML_OPTION_SKIP_WHITE, 1 );
155 xml_set_element_handler( $this->xmlParser,
156 array( $this, 'startElement' ),
157 array( $this, 'endElement' ) );
159 xml_set_character_data_handler( $this->xmlParser, array( $this, 'char' ) );
161 $this->parsable = self::PARSABLE_UNKNOWN;
162 $this->xmlParsableBuffer = '';
165 /** Destroy the xml parser
167 * Not sure if this is actually needed.
169 function __destruct() {
170 // not sure if this is needed.
171 xml_parser_free( $this->xmlParser );
175 * Check if this instance supports using this class
177 public static function isSupported() {
178 return function_exists( 'xml_parser_create_ns' ) && class_exists( 'XMLReader' );
181 /** Get the result array. Do some post-processing before returning
182 * the array, and transform any metadata that is special-cased.
184 * @return array Array of results as an array of arrays suitable for
185 * FormatMetadata::getFormattedData().
187 public function getResults() {
188 // xmp-special is for metadata that affects how stuff
189 // is extracted. For example xmpNote:HasExtendedXMP.
191 // It is also used to handle photoshop:AuthorsPosition
192 // which is weird and really part of another property,
193 // see 2:85 in IPTC. See also pg 21 of IPTC4XMP standard.
194 // The location fields also use it.
196 $data = $this->results;
198 Hooks::run( 'XMPGetResults', array( &$data ) );
200 if ( isset( $data['xmp-special']['AuthorsPosition'] )
201 && is_string( $data['xmp-special']['AuthorsPosition'] )
202 && isset( $data['xmp-general']['Artist'][0] )
204 // Note, if there is more than one creator,
205 // this only applies to first. This also will
206 // only apply to the dc:Creator prop, not the
207 // exif:Artist prop.
209 $data['xmp-general']['Artist'][0] =
210 $data['xmp-special']['AuthorsPosition'] . ', '
211 . $data['xmp-general']['Artist'][0];
214 // Go through the LocationShown and LocationCreated
215 // changing it to the non-hierarchal form used by
216 // the other location fields.
218 if ( isset( $data['xmp-special']['LocationShown'][0] )
219 && is_array( $data['xmp-special']['LocationShown'][0] )
221 // the is_array is just paranoia. It should always
222 // be an array.
223 foreach ( $data['xmp-special']['LocationShown'] as $loc ) {
224 if ( !is_array( $loc ) ) {
225 // To avoid copying over the _type meta-fields.
226 continue;
228 foreach ( $loc as $field => $val ) {
229 $data['xmp-general'][$field . 'Dest'][] = $val;
233 if ( isset( $data['xmp-special']['LocationCreated'][0] )
234 && is_array( $data['xmp-special']['LocationCreated'][0] )
236 // the is_array is just paranoia. It should always
237 // be an array.
238 foreach ( $data['xmp-special']['LocationCreated'] as $loc ) {
239 if ( !is_array( $loc ) ) {
240 // To avoid copying over the _type meta-fields.
241 continue;
243 foreach ( $loc as $field => $val ) {
244 $data['xmp-general'][$field . 'Created'][] = $val;
249 // We don't want to return the special values, since they're
250 // special and not info to be stored about the file.
251 unset( $data['xmp-special'] );
253 // Convert GPSAltitude to negative if below sea level.
254 if ( isset( $data['xmp-exif']['GPSAltitudeRef'] )
255 && isset( $data['xmp-exif']['GPSAltitude'] )
258 // Must convert to a real before multiplying by -1
259 // XMPValidate guarantees there will always be a '/' in this value.
260 list( $nom, $denom ) = explode( '/', $data['xmp-exif']['GPSAltitude'] );
261 $data['xmp-exif']['GPSAltitude'] = $nom / $denom;
263 if ( $data['xmp-exif']['GPSAltitudeRef'] == '1' ) {
264 $data['xmp-exif']['GPSAltitude'] *= -1;
266 unset( $data['xmp-exif']['GPSAltitudeRef'] );
269 return $data;
273 * Main function to call to parse XMP. Use getResults to
274 * get results.
276 * Also catches any errors during processing, writes them to
277 * debug log, blanks result array and returns false.
279 * @param string $content XMP data
280 * @param bool $allOfIt If this is all the data (true) or if its split up (false). Default true
281 * @param bool $reset Does xml parser need to be reset. Default false
282 * @throws MWException
283 * @return bool Success.
285 public function parse( $content, $allOfIt = true, $reset = false ) {
286 if ( $reset ) {
287 $this->resetXMLParser();
289 try {
291 // detect encoding by looking for BOM which is supposed to be in processing instruction.
292 // see page 12 of http://www.adobe.com/devnet/xmp/pdfs/XMPSpecificationPart3.pdf
293 if ( !$this->charset ) {
294 $bom = array();
295 if ( preg_match( '/\xEF\xBB\xBF|\xFE\xFF|\x00\x00\xFE\xFF|\xFF\xFE\x00\x00|\xFF\xFE/',
296 $content, $bom )
298 switch ( $bom[0] ) {
299 case "\xFE\xFF":
300 $this->charset = 'UTF-16BE';
301 break;
302 case "\xFF\xFE":
303 $this->charset = 'UTF-16LE';
304 break;
305 case "\x00\x00\xFE\xFF":
306 $this->charset = 'UTF-32BE';
307 break;
308 case "\xFF\xFE\x00\x00":
309 $this->charset = 'UTF-32LE';
310 break;
311 case "\xEF\xBB\xBF":
312 $this->charset = 'UTF-8';
313 break;
314 default:
315 //this should be impossible to get to
316 throw new MWException( "Invalid BOM" );
318 } else {
319 // standard specifically says, if no bom assume utf-8
320 $this->charset = 'UTF-8';
323 if ( $this->charset !== 'UTF-8' ) {
324 //don't convert if already utf-8
325 wfSuppressWarnings();
326 $content = iconv( $this->charset, 'UTF-8//IGNORE', $content );
327 wfRestoreWarnings();
330 // Ensure the XMP block does not have an xml doctype declaration, which
331 // could declare entities unsafe to parse with xml_parse (T85848/T71210).
332 if ( $this->parsable !== self::PARSABLE_OK ) {
333 if ( $this->parsable === self::PARSABLE_NO ) {
334 throw new Exception( 'Unsafe doctype declaration in XML.' );
337 $content = $this->xmlParsableBuffer . $content;
338 if ( !$this->checkParseSafety( $content ) ) {
339 if ( !$allOfIt && $this->parsable !== self::PARSABLE_NO ) {
340 // parse wasn't Unsuccessful yet, so return true
341 // in this case.
342 return true;
344 $msg = ( $this->parsable === self::PARSABLE_NO ) ?
345 'Unsafe doctype declaration in XML.' :
346 'No root element found in XML.';
347 throw new Exception( $msg );
351 $ok = xml_parse( $this->xmlParser, $content, $allOfIt );
352 if ( !$ok ) {
353 $error = xml_error_string( xml_get_error_code( $this->xmlParser ) );
354 $where = 'line: ' . xml_get_current_line_number( $this->xmlParser )
355 . ' column: ' . xml_get_current_column_number( $this->xmlParser )
356 . ' byte offset: ' . xml_get_current_byte_index( $this->xmlParser );
358 wfDebugLog( 'XMP', "XMPReader::parse : Error reading XMP content: $error ($where)" );
359 $this->results = array(); // blank if error.
360 return false;
362 } catch ( Exception $e ) {
363 wfDebugLog( 'XMP', 'XMP parse error: ' . $e );
364 $this->results = array();
366 return false;
369 return true;
372 /** Entry point for XMPExtended blocks in jpeg files
374 * @todo In serious need of testing
375 * @see http://www.adobe.ge/devnet/xmp/pdfs/XMPSpecificationPart3.pdf XMP spec part 3 page 20
376 * @param string $content XMPExtended block minus the namespace signature
377 * @return bool If it succeeded.
379 public function parseExtended( $content ) {
380 // @todo FIXME: This is untested. Hard to find example files
381 // or programs that make such files..
382 $guid = substr( $content, 0, 32 );
383 if ( !isset( $this->results['xmp-special']['HasExtendedXMP'] )
384 || $this->results['xmp-special']['HasExtendedXMP'] !== $guid
386 wfDebugLog( 'XMP', __METHOD__ .
387 " Ignoring XMPExtended block due to wrong guid (guid= '$guid')" );
389 return false;
391 $len = unpack( 'Nlength/Noffset', substr( $content, 32, 8 ) );
393 if ( !$len || $len['length'] < 4 || $len['offset'] < 0 || $len['offset'] > $len['length'] ) {
394 wfDebugLog( 'XMP', __METHOD__ . 'Error reading extended XMP block, invalid length or offset.' );
396 return false;
399 // we're not very robust here. we should accept it in the wrong order.
400 // To quote the XMP standard:
401 // "A JPEG writer should write the ExtendedXMP marker segments in order,
402 // immediately following the StandardXMP. However, the JPEG standard
403 // does not require preservation of marker segment order. A robust JPEG
404 // reader should tolerate the marker segments in any order."
406 // otoh the probability that an image will have more than 128k of
407 // metadata is rather low... so the probability that it will have
408 // > 128k, and be in the wrong order is very low...
410 if ( $len['offset'] !== $this->extendedXMPOffset ) {
411 wfDebugLog( 'XMP', __METHOD__ . 'Ignoring XMPExtended block due to wrong order. (Offset was '
412 . $len['offset'] . ' but expected ' . $this->extendedXMPOffset . ')' );
414 return false;
417 if ( $len['offset'] === 0 ) {
418 // if we're starting the extended block, we've probably already
419 // done the XMPStandard block, so reset.
420 $this->resetXMLParser();
423 $this->extendedXMPOffset += $len['length'];
425 $actualContent = substr( $content, 40 );
427 if ( $this->extendedXMPOffset === strlen( $actualContent ) ) {
428 $atEnd = true;
429 } else {
430 $atEnd = false;
433 wfDebugLog( 'XMP', __METHOD__ . 'Parsing a XMPExtended block' );
435 return $this->parse( $actualContent, $atEnd );
439 * Character data handler
440 * Called whenever character data is found in the xmp document.
442 * does nothing if we're in MODE_IGNORE or if the data is whitespace
443 * throws an error if we're not in MODE_SIMPLE (as we're not allowed to have character
444 * data in the other modes).
446 * As an example, this happens when we encounter XMP like:
447 * <exif:DigitalZoomRatio>0/10</exif:DigitalZoomRatio>
448 * and are processing the 0/10 bit.
450 * @param XMLParser $parser XMLParser reference to the xml parser
451 * @param string $data Character data
452 * @throws MWException On invalid data
454 function char( $parser, $data ) {
456 $data = trim( $data );
457 if ( trim( $data ) === "" ) {
458 return;
461 if ( !isset( $this->mode[0] ) ) {
462 throw new MWException( 'Unexpected character data before first rdf:Description element' );
465 if ( $this->mode[0] === self::MODE_IGNORE ) {
466 return;
469 if ( $this->mode[0] !== self::MODE_SIMPLE
470 && $this->mode[0] !== self::MODE_QDESC
472 throw new MWException( 'character data where not expected. (mode ' . $this->mode[0] . ')' );
475 // to check, how does this handle w.s.
476 if ( $this->charContent === false ) {
477 $this->charContent = $data;
478 } else {
479 $this->charContent .= $data;
484 * Check if a block of XML is safe to pass to xml_parse, i.e. doesn't
485 * contain a doctype declaration which could contain a dos attack if we
486 * parse it and expand internal entities (T85848).
488 * @param string $content xml string to check for parse safety
489 * @return bool true if the xml is safe to parse, false otherwise
491 private function checkParseSafety( $content ) {
492 $reader = new XMLReader();
493 $result = null;
495 // For XMLReader to parse incomplete/invalid XML, it has to be open()'ed
496 // instead of using XML().
497 $reader->open(
498 'data://text/plain,' . urlencode( $content ),
499 null,
500 LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_NONET
503 $oldDisable = libxml_disable_entity_loader( true );
504 $reset = new ScopedCallback(
505 'libxml_disable_entity_loader',
506 array( $oldDisable )
508 $reader->setParserProperty( XMLReader::SUBST_ENTITIES, false );
510 // Even with LIBXML_NOWARNING set, XMLReader::read gives a warning
511 // when parsing truncated XML, which causes unit tests to fail.
512 wfSuppressWarnings();
513 while ( $reader->read() ) {
514 if ( $reader->nodeType === XMLReader::ELEMENT ) {
515 // Reached the first element without hitting a doctype declaration
516 $this->parsable = self::PARSABLE_OK;
517 $result = true;
518 break;
520 if ( $reader->nodeType === XMLReader::DOC_TYPE ) {
521 $this->parsable = self::PARSABLE_NO;
522 $result = false;
523 break;
526 wfRestoreWarnings();
528 if ( !is_null( $result ) ) {
529 return $result;
532 // Reached the end of the parsable xml without finding an element
533 // or doctype. Buffer and try again.
534 $this->parsable = self::PARSABLE_BUFFERING;
535 $this->xmlParsableBuffer = $content;
536 return false;
539 /** When we hit a closing element in MODE_IGNORE
540 * Check to see if this is the element we started to ignore,
541 * in which case we get out of MODE_IGNORE
543 * @param string $elm Namespace of element followed by a space and then tag name of element.
545 private function endElementModeIgnore( $elm ) {
546 if ( $this->curItem[0] === $elm ) {
547 array_shift( $this->curItem );
548 array_shift( $this->mode );
553 * Hit a closing element when in MODE_SIMPLE.
554 * This generally means that we finished processing a
555 * property value, and now have to save the result to the
556 * results array
558 * For example, when processing:
559 * <exif:DigitalZoomRatio>0/10</exif:DigitalZoomRatio>
560 * this deals with when we hit </exif:DigitalZoomRatio>.
562 * Or it could be if we hit the end element of a property
563 * of a compound data structure (like a member of an array).
565 * @param string $elm Namespace, space, and tag name.
567 private function endElementModeSimple( $elm ) {
568 if ( $this->charContent !== false ) {
569 if ( $this->processingArray ) {
570 // if we're processing an array, use the original element
571 // name instead of rdf:li.
572 list( $ns, $tag ) = explode( ' ', $this->curItem[0], 2 );
573 } else {
574 list( $ns, $tag ) = explode( ' ', $elm, 2 );
576 $this->saveValue( $ns, $tag, $this->charContent );
578 $this->charContent = false; // reset
580 array_shift( $this->curItem );
581 array_shift( $this->mode );
585 * Hit a closing element in MODE_STRUCT, MODE_SEQ, MODE_BAG
586 * generally means we've finished processing a nested structure.
587 * resets some internal variables to indicate that.
589 * Note this means we hit the closing element not the "</rdf:Seq>".
591 * @par For example, when processing:
592 * @code{,xml}
593 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
594 * </rdf:Seq> </exif:ISOSpeedRatings>
595 * @endcode
597 * This method is called when we hit the "</exif:ISOSpeedRatings>" tag.
599 * @param string $elm Namespace . space . tag name.
600 * @throws MWException
602 private function endElementNested( $elm ) {
604 /* cur item must be the same as $elm, unless if in MODE_STRUCT
605 in which case it could also be rdf:Description */
606 if ( $this->curItem[0] !== $elm
607 && !( $elm === self::NS_RDF . ' Description'
608 && $this->mode[0] === self::MODE_STRUCT )
610 throw new MWException( "nesting mismatch. got a </$elm> but expected a </" .
611 $this->curItem[0] . '>' );
614 // Validate structures.
615 list( $ns, $tag ) = explode( ' ', $elm, 2 );
616 if ( isset( $this->items[$ns][$tag]['validate'] ) ) {
618 $info =& $this->items[$ns][$tag];
619 $finalName = isset( $info['map_name'] )
620 ? $info['map_name'] : $tag;
622 $validate = is_array( $info['validate'] ) ? $info['validate']
623 : array( 'XMPValidate', $info['validate'] );
625 if ( !isset( $this->results['xmp-' . $info['map_group']][$finalName] ) ) {
626 // This can happen if all the members of the struct failed validation.
627 wfDebugLog( 'XMP', __METHOD__ . " <$ns:$tag> has no valid members." );
628 } elseif ( is_callable( $validate ) ) {
629 $val =& $this->results['xmp-' . $info['map_group']][$finalName];
630 call_user_func_array( $validate, array( $info, &$val, false ) );
631 if ( is_null( $val ) ) {
632 // the idea being the validation function will unset the variable if
633 // its invalid.
634 wfDebugLog( 'XMP', __METHOD__ . " <$ns:$tag> failed validation." );
635 unset( $this->results['xmp-' . $info['map_group']][$finalName] );
637 } else {
638 wfDebugLog( 'XMP', __METHOD__ . " Validation function for $finalName ("
639 . $validate[0] . '::' . $validate[1] . '()) is not callable.' );
643 array_shift( $this->curItem );
644 array_shift( $this->mode );
645 $this->ancestorStruct = false;
646 $this->processingArray = false;
647 $this->itemLang = false;
651 * Hit a closing element in MODE_LI (either rdf:Seq, or rdf:Bag )
652 * Add information about what type of element this is.
654 * Note we still have to hit the outer "</property>"
656 * @par For example, when processing:
657 * @code{,xml}
658 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
659 * </rdf:Seq> </exif:ISOSpeedRatings>
660 * @endcode
662 * This method is called when we hit the "</rdf:Seq>".
663 * (For comparison, we call endElementModeSimple when we
664 * hit the "</rdf:li>")
666 * @param string $elm Namespace . ' ' . element name
667 * @throws MWException
669 private function endElementModeLi( $elm ) {
671 list( $ns, $tag ) = explode( ' ', $this->curItem[0], 2 );
672 $info = $this->items[$ns][$tag];
673 $finalName = isset( $info['map_name'] )
674 ? $info['map_name'] : $tag;
676 array_shift( $this->mode );
678 if ( !isset( $this->results['xmp-' . $info['map_group']][$finalName] ) ) {
679 wfDebugLog( 'XMP', __METHOD__ . " Empty compund element $finalName." );
681 return;
684 if ( $elm === self::NS_RDF . ' Seq' ) {
685 $this->results['xmp-' . $info['map_group']][$finalName]['_type'] = 'ol';
686 } elseif ( $elm === self::NS_RDF . ' Bag' ) {
687 $this->results['xmp-' . $info['map_group']][$finalName]['_type'] = 'ul';
688 } elseif ( $elm === self::NS_RDF . ' Alt' ) {
689 // extra if needed as you could theoretically have a non-language alt.
690 if ( $info['mode'] === self::MODE_LANG ) {
691 $this->results['xmp-' . $info['map_group']][$finalName]['_type'] = 'lang';
693 } else {
694 throw new MWException( __METHOD__ . " expected </rdf:seq> or </rdf:bag> but instead got $elm." );
699 * End element while in MODE_QDESC
700 * mostly when ending an element when we have a simple value
701 * that has qualifiers.
703 * Qualifiers aren't all that common, and we don't do anything
704 * with them.
706 * @param string $elm Namespace and element
708 private function endElementModeQDesc( $elm ) {
710 if ( $elm === self::NS_RDF . ' value' ) {
711 list( $ns, $tag ) = explode( ' ', $this->curItem[0], 2 );
712 $this->saveValue( $ns, $tag, $this->charContent );
714 return;
715 } else {
716 array_shift( $this->mode );
717 array_shift( $this->curItem );
722 * Handler for hitting a closing element.
724 * generally just calls a helper function depending on what
725 * mode we're in.
727 * Ignores the outer wrapping elements that are optional in
728 * xmp and have no meaning.
730 * @param XMLParser $parser
731 * @param string $elm Namespace . ' ' . element name
732 * @throws MWException
734 function endElement( $parser, $elm ) {
735 if ( $elm === ( self::NS_RDF . ' RDF' )
736 || $elm === 'adobe:ns:meta/ xmpmeta'
737 || $elm === 'adobe:ns:meta/ xapmeta'
739 // ignore these.
740 return;
743 if ( $elm === self::NS_RDF . ' type' ) {
744 // these aren't really supported properly yet.
745 // However, it appears they almost never used.
746 wfDebugLog( 'XMP', __METHOD__ . ' encountered <rdf:type>' );
749 if ( strpos( $elm, ' ' ) === false ) {
750 // This probably shouldn't happen.
751 // However, there is a bug in an adobe product
752 // that forgets the namespace on some things.
753 // (Luckily they are unimportant things).
754 wfDebugLog( 'XMP', __METHOD__ . " Encountered </$elm> which has no namespace. Skipping." );
756 return;
759 if ( count( $this->mode[0] ) === 0 ) {
760 // This should never ever happen and means
761 // there is a pretty major bug in this class.
762 throw new MWException( 'Encountered end element with no mode' );
765 if ( count( $this->curItem ) == 0 && $this->mode[0] !== self::MODE_INITIAL ) {
766 // just to be paranoid. Should always have a curItem, except for initially
767 // (aka during MODE_INITAL).
768 throw new MWException( "Hit end element </$elm> but no curItem" );
771 switch ( $this->mode[0] ) {
772 case self::MODE_IGNORE:
773 $this->endElementModeIgnore( $elm );
774 break;
775 case self::MODE_SIMPLE:
776 $this->endElementModeSimple( $elm );
777 break;
778 case self::MODE_STRUCT:
779 case self::MODE_SEQ:
780 case self::MODE_BAG:
781 case self::MODE_LANG:
782 case self::MODE_BAGSTRUCT:
783 $this->endElementNested( $elm );
784 break;
785 case self::MODE_INITIAL:
786 if ( $elm === self::NS_RDF . ' Description' ) {
787 array_shift( $this->mode );
788 } else {
789 throw new MWException( 'Element ended unexpectedly while in MODE_INITIAL' );
791 break;
792 case self::MODE_LI:
793 case self::MODE_LI_LANG:
794 $this->endElementModeLi( $elm );
795 break;
796 case self::MODE_QDESC:
797 $this->endElementModeQDesc( $elm );
798 break;
799 default:
800 wfDebugLog( 'XMP', __METHOD__ . " no mode (elm = $elm)" );
801 break;
806 * Hit an opening element while in MODE_IGNORE
808 * XMP is extensible, so ignore any tag we don't understand.
810 * Mostly ignores, unless we encounter the element that we are ignoring.
811 * in which case we add it to the item stack, so we can ignore things
812 * that are nested, correctly.
814 * @param string $elm Namespace . ' ' . tag name
816 private function startElementModeIgnore( $elm ) {
817 if ( $elm === $this->curItem[0] ) {
818 array_unshift( $this->curItem, $elm );
819 array_unshift( $this->mode, self::MODE_IGNORE );
824 * Start element in MODE_BAG (unordered array)
825 * this should always be <rdf:Bag>
827 * @param string $elm Namespace . ' ' . tag
828 * @throws MWException If we have an element that's not <rdf:Bag>
830 private function startElementModeBag( $elm ) {
831 if ( $elm === self::NS_RDF . ' Bag' ) {
832 array_unshift( $this->mode, self::MODE_LI );
833 } else {
834 throw new MWException( "Expected <rdf:Bag> but got $elm." );
839 * Start element in MODE_SEQ (ordered array)
840 * this should always be <rdf:Seq>
842 * @param string $elm Namespace . ' ' . tag
843 * @throws MWException If we have an element that's not <rdf:Seq>
845 private function startElementModeSeq( $elm ) {
846 if ( $elm === self::NS_RDF . ' Seq' ) {
847 array_unshift( $this->mode, self::MODE_LI );
848 } elseif ( $elm === self::NS_RDF . ' Bag' ) {
849 # bug 27105
850 wfDebugLog( 'XMP', __METHOD__ . ' Expected an rdf:Seq, but got an rdf:Bag. Pretending'
851 . ' it is a Seq, since some buggy software is known to screw this up.' );
852 array_unshift( $this->mode, self::MODE_LI );
853 } else {
854 throw new MWException( "Expected <rdf:Seq> but got $elm." );
859 * Start element in MODE_LANG (language alternative)
860 * this should always be <rdf:Alt>
862 * This tag tends to be used for metadata like describe this
863 * picture, which can be translated into multiple languages.
865 * XMP supports non-linguistic alternative selections,
866 * which are really only used for thumbnails, which
867 * we don't care about.
869 * @param string $elm Namespace . ' ' . tag
870 * @throws MWException If we have an element that's not <rdf:Alt>
872 private function startElementModeLang( $elm ) {
873 if ( $elm === self::NS_RDF . ' Alt' ) {
874 array_unshift( $this->mode, self::MODE_LI_LANG );
875 } else {
876 throw new MWException( "Expected <rdf:Seq> but got $elm." );
881 * Handle an opening element when in MODE_SIMPLE
883 * This should not happen often. This is for if a simple element
884 * already opened has a child element. Could happen for a
885 * qualified element.
887 * For example:
888 * <exif:DigitalZoomRatio><rdf:Description><rdf:value>0/10</rdf:value>
889 * <foo:someQualifier>Bar</foo:someQualifier> </rdf:Description>
890 * </exif:DigitalZoomRatio>
892 * This method is called when processing the <rdf:Description> element
894 * @param string $elm Namespace and tag names separated by space.
895 * @param array $attribs Attributes of the element.
896 * @throws MWException
898 private function startElementModeSimple( $elm, $attribs ) {
899 if ( $elm === self::NS_RDF . ' Description' ) {
900 // If this value has qualifiers
901 array_unshift( $this->mode, self::MODE_QDESC );
902 array_unshift( $this->curItem, $this->curItem[0] );
904 if ( isset( $attribs[self::NS_RDF . ' value'] ) ) {
905 list( $ns, $tag ) = explode( ' ', $this->curItem[0], 2 );
906 $this->saveValue( $ns, $tag, $attribs[self::NS_RDF . ' value'] );
908 } elseif ( $elm === self::NS_RDF . ' value' ) {
909 // This should not be here.
910 throw new MWException( __METHOD__ . ' Encountered <rdf:value> where it was unexpected.' );
911 } else {
912 // something else we don't recognize, like a qualifier maybe.
913 wfDebugLog( 'XMP', __METHOD__ .
914 " Encountered element <$elm> where only expecting character data as value of " .
915 $this->curItem[0] );
916 array_unshift( $this->mode, self::MODE_IGNORE );
917 array_unshift( $this->curItem, $elm );
922 * Start an element when in MODE_QDESC.
923 * This generally happens when a simple element has an inner
924 * rdf:Description to hold qualifier elements.
926 * For example in:
927 * <exif:DigitalZoomRatio><rdf:Description><rdf:value>0/10</rdf:value>
928 * <foo:someQualifier>Bar</foo:someQualifier> </rdf:Description>
929 * </exif:DigitalZoomRatio>
930 * Called when processing the <rdf:value> or <foo:someQualifier>.
932 * @param string $elm Namespace and tag name separated by a space.
935 private function startElementModeQDesc( $elm ) {
936 if ( $elm === self::NS_RDF . ' value' ) {
937 return; // do nothing
938 } else {
939 // otherwise its a qualifier, which we ignore
940 array_unshift( $this->mode, self::MODE_IGNORE );
941 array_unshift( $this->curItem, $elm );
946 * Starting an element when in MODE_INITIAL
947 * This usually happens when we hit an element inside
948 * the outer rdf:Description
950 * This is generally where most properties start.
952 * @param string $ns Namespace
953 * @param string $tag Tag name (without namespace prefix)
954 * @param array $attribs Array of attributes
955 * @throws MWException
957 private function startElementModeInitial( $ns, $tag, $attribs ) {
958 if ( $ns !== self::NS_RDF ) {
960 if ( isset( $this->items[$ns][$tag] ) ) {
961 if ( isset( $this->items[$ns][$tag]['structPart'] ) ) {
962 // If this element is supposed to appear only as
963 // a child of a structure, but appears here (not as
964 // a child of a struct), then something weird is
965 // happening, so ignore this element and its children.
967 wfDebugLog( 'XMP', "Encountered <$ns:$tag> outside"
968 . " of its expected parent. Ignoring." );
970 array_unshift( $this->mode, self::MODE_IGNORE );
971 array_unshift( $this->curItem, $ns . ' ' . $tag );
973 return;
975 $mode = $this->items[$ns][$tag]['mode'];
976 array_unshift( $this->mode, $mode );
977 array_unshift( $this->curItem, $ns . ' ' . $tag );
978 if ( $mode === self::MODE_STRUCT ) {
979 $this->ancestorStruct = isset( $this->items[$ns][$tag]['map_name'] )
980 ? $this->items[$ns][$tag]['map_name'] : $tag;
982 if ( $this->charContent !== false ) {
983 // Something weird.
984 // Should not happen in valid XMP.
985 throw new MWException( 'tag nested in non-whitespace characters.' );
987 } else {
988 // This element is not on our list of allowed elements so ignore.
989 wfDebugLog( 'XMP', __METHOD__ . " Ignoring unrecognized element <$ns:$tag>." );
990 array_unshift( $this->mode, self::MODE_IGNORE );
991 array_unshift( $this->curItem, $ns . ' ' . $tag );
993 return;
996 // process attributes
997 $this->doAttribs( $attribs );
1001 * Hit an opening element when in a Struct (MODE_STRUCT)
1002 * This is generally for fields of a compound property.
1004 * Example of a struct (abbreviated; flash has more properties):
1006 * <exif:Flash> <rdf:Description> <exif:Fired>True</exif:Fired>
1007 * <exif:Mode>1</exif:Mode></rdf:Description></exif:Flash>
1009 * or:
1011 * <exif:Flash rdf:parseType='Resource'> <exif:Fired>True</exif:Fired>
1012 * <exif:Mode>1</exif:Mode></exif:Flash>
1014 * @param string $ns Namespace
1015 * @param string $tag Tag name (no ns)
1016 * @param array $attribs Array of attribs w/ values.
1017 * @throws MWException
1019 private function startElementModeStruct( $ns, $tag, $attribs ) {
1020 if ( $ns !== self::NS_RDF ) {
1022 if ( isset( $this->items[$ns][$tag] ) ) {
1023 if ( isset( $this->items[$ns][$this->ancestorStruct]['children'] )
1024 && !isset( $this->items[$ns][$this->ancestorStruct]['children'][$tag] )
1026 // This assumes that we don't have inter-namespace nesting
1027 // which we don't in all the properties we're interested in.
1028 throw new MWException( " <$tag> appeared nested in <" . $this->ancestorStruct
1029 . "> where it is not allowed." );
1031 array_unshift( $this->mode, $this->items[$ns][$tag]['mode'] );
1032 array_unshift( $this->curItem, $ns . ' ' . $tag );
1033 if ( $this->charContent !== false ) {
1034 // Something weird.
1035 // Should not happen in valid XMP.
1036 throw new MWException( "tag <$tag> nested in non-whitespace characters (" .
1037 $this->charContent . ")." );
1039 } else {
1040 array_unshift( $this->mode, self::MODE_IGNORE );
1041 array_unshift( $this->curItem, $elm );
1043 return;
1047 if ( $ns === self::NS_RDF && $tag === 'Description' ) {
1048 $this->doAttribs( $attribs );
1049 array_unshift( $this->mode, self::MODE_STRUCT );
1050 array_unshift( $this->curItem, $this->curItem[0] );
1055 * opening element in MODE_LI
1056 * process elements of arrays.
1058 * Example:
1059 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
1060 * </rdf:Seq> </exif:ISOSpeedRatings>
1061 * This method is called when we hit the <rdf:li> element.
1063 * @param string $elm Namespace . ' ' . tagname
1064 * @param array $attribs Attributes. (needed for BAGSTRUCTS)
1065 * @throws MWException If gets a tag other than <rdf:li>
1067 private function startElementModeLi( $elm, $attribs ) {
1068 if ( ( $elm ) !== self::NS_RDF . ' li' ) {
1069 throw new MWException( "<rdf:li> expected but got $elm." );
1072 if ( !isset( $this->mode[1] ) ) {
1073 // This should never ever ever happen. Checking for it
1074 // to be paranoid.
1075 throw new MWException( 'In mode Li, but no 2xPrevious mode!' );
1078 if ( $this->mode[1] === self::MODE_BAGSTRUCT ) {
1079 // This list item contains a compound (STRUCT) value.
1080 array_unshift( $this->mode, self::MODE_STRUCT );
1081 array_unshift( $this->curItem, $elm );
1082 $this->processingArray = true;
1084 if ( !isset( $this->curItem[1] ) ) {
1085 // be paranoid.
1086 throw new MWException( 'Can not find parent of BAGSTRUCT.' );
1088 list( $curNS, $curTag ) = explode( ' ', $this->curItem[1] );
1089 $this->ancestorStruct = isset( $this->items[$curNS][$curTag]['map_name'] )
1090 ? $this->items[$curNS][$curTag]['map_name'] : $curTag;
1092 $this->doAttribs( $attribs );
1093 } else {
1094 // Normal BAG or SEQ containing simple values.
1095 array_unshift( $this->mode, self::MODE_SIMPLE );
1096 // need to add curItem[0] on again since one is for the specific item
1097 // and one is for the entire group.
1098 array_unshift( $this->curItem, $this->curItem[0] );
1099 $this->processingArray = true;
1104 * Opening element in MODE_LI_LANG.
1105 * process elements of language alternatives
1107 * Example:
1108 * <dc:title> <rdf:Alt> <rdf:li xml:lang="x-default">My house
1109 * </rdf:li> </rdf:Alt> </dc:title>
1111 * This method is called when we hit the <rdf:li> element.
1113 * @param string $elm Namespace . ' ' . tag
1114 * @param array $attribs Array of elements (most importantly xml:lang)
1115 * @throws MWException If gets a tag other than <rdf:li> or if no xml:lang
1117 private function startElementModeLiLang( $elm, $attribs ) {
1118 if ( $elm !== self::NS_RDF . ' li' ) {
1119 throw new MWException( __METHOD__ . " <rdf:li> expected but got $elm." );
1121 if ( !isset( $attribs[self::NS_XML . ' lang'] )
1122 || !preg_match( '/^[-A-Za-z0-9]{2,}$/D', $attribs[self::NS_XML . ' lang'] )
1124 throw new MWException( __METHOD__
1125 . " <rdf:li> did not contain, or has invalid xml:lang attribute in lang alternative" );
1128 // Lang is case-insensitive.
1129 $this->itemLang = strtolower( $attribs[self::NS_XML . ' lang'] );
1131 // need to add curItem[0] on again since one is for the specific item
1132 // and one is for the entire group.
1133 array_unshift( $this->curItem, $this->curItem[0] );
1134 array_unshift( $this->mode, self::MODE_SIMPLE );
1135 $this->processingArray = true;
1139 * Hits an opening element.
1140 * Generally just calls a helper based on what MODE we're in.
1141 * Also does some initial set up for the wrapper element
1143 * @param XMLParser $parser
1144 * @param string $elm Namespace "<space>" element
1145 * @param array $attribs Attribute name => value
1146 * @throws MWException
1148 function startElement( $parser, $elm, $attribs ) {
1150 if ( $elm === self::NS_RDF . ' RDF'
1151 || $elm === 'adobe:ns:meta/ xmpmeta'
1152 || $elm === 'adobe:ns:meta/ xapmeta'
1154 /* ignore. */
1155 return;
1156 } elseif ( $elm === self::NS_RDF . ' Description' ) {
1157 if ( count( $this->mode ) === 0 ) {
1158 // outer rdf:desc
1159 array_unshift( $this->mode, self::MODE_INITIAL );
1161 } elseif ( $elm === self::NS_RDF . ' type' ) {
1162 // This doesn't support rdf:type properly.
1163 // In practise I have yet to see a file that
1164 // uses this element, however it is mentioned
1165 // on page 25 of part 1 of the xmp standard.
1167 // also it seems as if exiv2 and exiftool do not support
1168 // this either (That or I misunderstand the standard)
1169 wfDebugLog( 'XMP', __METHOD__ . ' Encountered <rdf:type> which isn\'t currently supported' );
1172 if ( strpos( $elm, ' ' ) === false ) {
1173 // This probably shouldn't happen.
1174 wfDebugLog( 'XMP', __METHOD__ . " Encountered <$elm> which has no namespace. Skipping." );
1176 return;
1179 list( $ns, $tag ) = explode( ' ', $elm, 2 );
1181 if ( count( $this->mode ) === 0 ) {
1182 // This should not happen.
1183 throw new MWException( 'Error extracting XMP, '
1184 . "encountered <$elm> with no mode" );
1187 switch ( $this->mode[0] ) {
1188 case self::MODE_IGNORE:
1189 $this->startElementModeIgnore( $elm );
1190 break;
1191 case self::MODE_SIMPLE:
1192 $this->startElementModeSimple( $elm, $attribs );
1193 break;
1194 case self::MODE_INITIAL:
1195 $this->startElementModeInitial( $ns, $tag, $attribs );
1196 break;
1197 case self::MODE_STRUCT:
1198 $this->startElementModeStruct( $ns, $tag, $attribs );
1199 break;
1200 case self::MODE_BAG:
1201 case self::MODE_BAGSTRUCT:
1202 $this->startElementModeBag( $elm );
1203 break;
1204 case self::MODE_SEQ:
1205 $this->startElementModeSeq( $elm );
1206 break;
1207 case self::MODE_LANG:
1208 $this->startElementModeLang( $elm );
1209 break;
1210 case self::MODE_LI_LANG:
1211 $this->startElementModeLiLang( $elm, $attribs );
1212 break;
1213 case self::MODE_LI:
1214 $this->startElementModeLi( $elm, $attribs );
1215 break;
1216 case self::MODE_QDESC:
1217 $this->startElementModeQDesc( $elm );
1218 break;
1219 default:
1220 throw new MWException( 'StartElement in unknown mode: ' . $this->mode[0] );
1225 * Process attributes.
1226 * Simple values can be stored as either a tag or attribute
1228 * Often the initial "<rdf:Description>" tag just has all the simple
1229 * properties as attributes.
1231 * @codingStandardsIgnoreStart Long line that cannot be broken
1232 * @par Example:
1233 * @code
1234 * <rdf:Description rdf:about="" xmlns:exif="http://ns.adobe.com/exif/1.0/" exif:DigitalZoomRatio="0/10">
1235 * @endcode
1236 * @codingStandardsIgnoreEnd
1238 * @param array $attribs Array attribute=>value
1239 * @throws MWException
1241 private function doAttribs( $attribs ) {
1242 // first check for rdf:parseType attribute, as that can change
1243 // how the attributes are interperted.
1245 if ( isset( $attribs[self::NS_RDF . ' parseType'] )
1246 && $attribs[self::NS_RDF . ' parseType'] === 'Resource'
1247 && $this->mode[0] === self::MODE_SIMPLE
1249 // this is equivalent to having an inner rdf:Description
1250 $this->mode[0] = self::MODE_QDESC;
1252 foreach ( $attribs as $name => $val ) {
1253 if ( strpos( $name, ' ' ) === false ) {
1254 // This shouldn't happen, but so far some old software forgets namespace
1255 // on rdf:about.
1256 wfDebugLog( 'XMP', __METHOD__ . ' Encountered non-namespaced attribute: '
1257 . " $name=\"$val\". Skipping. " );
1258 continue;
1260 list( $ns, $tag ) = explode( ' ', $name, 2 );
1261 if ( $ns === self::NS_RDF ) {
1262 if ( $tag === 'value' || $tag === 'resource' ) {
1263 // resource is for url.
1264 // value attribute is a weird way of just putting the contents.
1265 $this->char( $this->xmlParser, $val );
1267 } elseif ( isset( $this->items[$ns][$tag] ) ) {
1268 if ( $this->mode[0] === self::MODE_SIMPLE ) {
1269 throw new MWException( __METHOD__
1270 . " $ns:$tag found as attribute where not allowed" );
1272 $this->saveValue( $ns, $tag, $val );
1273 } else {
1274 wfDebugLog( 'XMP', __METHOD__ . " Ignoring unrecognized element <$ns:$tag>." );
1280 * Given an extracted value, save it to results array
1282 * note also uses $this->ancestorStruct and
1283 * $this->processingArray to determine what name to
1284 * save the value under. (in addition to $tag).
1286 * @param string $ns Namespace of tag this is for
1287 * @param string $tag Tag name
1288 * @param string $val Value to save
1290 private function saveValue( $ns, $tag, $val ) {
1292 $info =& $this->items[$ns][$tag];
1293 $finalName = isset( $info['map_name'] )
1294 ? $info['map_name'] : $tag;
1295 if ( isset( $info['validate'] ) ) {
1296 $validate = is_array( $info['validate'] ) ? $info['validate']
1297 : array( 'XMPValidate', $info['validate'] );
1299 if ( is_callable( $validate ) ) {
1300 call_user_func_array( $validate, array( $info, &$val, true ) );
1301 // the reasoning behind using &$val instead of using the return value
1302 // is to be consistent between here and validating structures.
1303 if ( is_null( $val ) ) {
1304 wfDebugLog( 'XMP', __METHOD__ . " <$ns:$tag> failed validation." );
1306 return;
1308 } else {
1309 wfDebugLog( 'XMP', __METHOD__ . " Validation function for $finalName ("
1310 . $validate[0] . '::' . $validate[1] . '()) is not callable.' );
1314 if ( $this->ancestorStruct && $this->processingArray ) {
1315 // Aka both an array and a struct. ( self::MODE_BAGSTRUCT )
1316 $this->results['xmp-' . $info['map_group']][$this->ancestorStruct][][$finalName] = $val;
1317 } elseif ( $this->ancestorStruct ) {
1318 $this->results['xmp-' . $info['map_group']][$this->ancestorStruct][$finalName] = $val;
1319 } elseif ( $this->processingArray ) {
1320 if ( $this->itemLang === false ) {
1321 // normal array
1322 $this->results['xmp-' . $info['map_group']][$finalName][] = $val;
1323 } else {
1324 // lang array.
1325 $this->results['xmp-' . $info['map_group']][$finalName][$this->itemLang] = $val;
1327 } else {
1328 $this->results['xmp-' . $info['map_group']][$finalName] = $val;