Merge to trunk everything in img_metadata branch.
[lhc/web/wiklou.git] / includes / media / XMP.php
1 <?php
2 /**
3 * Class for reading xmp data containing properties relevant to
4 * images, and spitting out an array that FormatExif accepts.
5 *
6 * Note, this is not meant to recognize every possible thing you can
7 * encode in XMP. It should recognize all the properties we want.
8 * For example it doesn't have support for structures with multiple
9 * nesting levels, as none of the properties we're supporting use that
10 * feature. If it comes across properties it doesn't recognize, it should
11 * ignore them.
12 *
13 * The public methods one would call in this class are
14 * - parse( $content )
15 * Reads in xmp content.
16 * Can potentially be called multiple times with partial data each time.
17 * - parseExtended( $content )
18 * Reads XMPExtended blocks (jpeg files only).
19 * - getResults
20 * Outputs a results array.
21 *
22 * Note XMP kind of looks like rdf. They are not the same thing - XMP is
23 * encoded as a specific subset of rdf. This class can read XMP. It cannot
24 * read rdf.
25 *
26 */
27 class XMPReader {
28
29 private $curItem = array(); // array to hold the current element (and previous element, and so on)
30 private $ancestorStruct = false; // the structure name when processing nested structures.
31 private $charContent = false; // temporary holder for character data that appears in xmp doc.
32 private $mode = array(); // stores the state the xmpreader is in (see MODE_FOO constants)
33 private $results = array(); // array to hold results
34 private $processingArray = false; // if we're doing a seq or bag.
35 private $itemLang = false; // used for lang alts only
36
37 private $xmlParser;
38 private $charset = false;
39 private $extendedXMPOffset = 0;
40
41 protected $items;
42
43 /*
44 * These are various mode constants.
45 * they are used to figure out what to do
46 * with an element when its encountered.
47 *
48 * For example, MODE_IGNORE is used when processing
49 * a property we're not interested in. So if a new
50 * element pops up when we're in that mode, we ignore it.
51 */
52 const MODE_INITIAL = 0;
53 const MODE_IGNORE = 1;
54 const MODE_LI = 2;
55 const MODE_LI_LANG = 3;
56 const MODE_QDESC = 4;
57
58 // The following MODE constants are also used in the
59 // $items array to denote what type of property the item is.
60 const MODE_SIMPLE = 10;
61 const MODE_STRUCT = 11; // structure (associative array)
62 const MODE_SEQ = 12; // ordered list
63 const MODE_BAG = 13; // unordered list
64 const MODE_LANG = 14;
65 const MODE_ALT = 15; // non-language alt. Currently not implemented, and not needed atm.
66 const MODE_BAGSTRUCT = 16; // A BAG of Structs.
67
68 const NS_RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
69 const NS_XML = 'http://www.w3.org/XML/1998/namespace';
70
71
72 /**
73 * Constructor.
74 *
75 * Primary job is to initialize the XMLParser
76 */
77 function __construct() {
78
79 if ( !function_exists( 'xml_parser_create_ns' ) ) {
80 // this should already be checked by this point
81 throw new MWException( 'XMP support requires XML Parser' );
82 }
83
84 $this->items = XMPInfo::getItems();
85
86 $this->resetXMLParser();
87
88 }
89 /**
90 * Main use is if a single item has multiple xmp documents describing it.
91 * For example in jpeg's with extendedXMP
92 */
93 private function resetXMLParser() {
94
95 if ($this->xmlParser) {
96 //is this needed?
97 xml_parser_free( $this->xmlParser );
98 }
99
100 $this->xmlParser = xml_parser_create_ns( 'UTF-8', ' ' );
101 xml_parser_set_option( $this->xmlParser, XML_OPTION_CASE_FOLDING, 0 );
102 xml_parser_set_option( $this->xmlParser, XML_OPTION_SKIP_WHITE, 1 );
103
104 xml_set_element_handler( $this->xmlParser,
105 array( $this, 'startElement' ),
106 array( $this, 'endElement' ) );
107
108 xml_set_character_data_handler( $this->xmlParser, array( $this, 'char' ) );
109
110
111 }
112
113 /** Destroy the xml parser
114 *
115 * Not sure if this is actually needed.
116 */
117 function __destruct() {
118 // not sure if this is needed.
119 xml_parser_free( $this->xmlParser );
120 }
121
122 /** Get the result array. Do some post-processing before returning
123 * the array, and transform any metadata that is special-cased.
124 *
125 * @return Array array of results as an array of arrays suitable for
126 * FormatMetadata::getFormattedData().
127 */
128 public function getResults() {
129 // xmp-special is for metadata that affects how stuff
130 // is extracted. For example xmpNote:HasExtendedXMP.
131
132 // It is also used to handle photoshop:AuthorsPosition
133 // which is weird and really part of another property,
134 // see 2:85 in IPTC. See also pg 21 of IPTC4XMP standard.
135 // The location fields also use it.
136
137 $data = $this->results;
138
139 wfRunHooks('XMPGetResults', Array(&$data));
140
141 if ( isset( $data['xmp-special']['AuthorsPosition'] )
142 && is_string( $data['xmp-special']['AuthorsPosition'] )
143 && isset( $data['xmp-general']['Artist'][0] )
144 ) {
145 // Note, if there is more than one creator,
146 // this only applies to first. This also will
147 // only apply to the dc:Creator prop, not the
148 // exif:Artist prop.
149
150 $data['xmp-general']['Artist'][0] =
151 $data['xmp-special']['AuthorsPosition'] . ', '
152 . $data['xmp-general']['Artist'][0];
153 }
154
155 // Go through the LocationShown and LocationCreated
156 // changing it to the non-hierarchal form used by
157 // the other location fields.
158
159 if ( isset( $data['xmp-special']['LocationShown'][0] )
160 && is_array( $data['xmp-special']['LocationShown'][0] )
161 ) {
162 // the is_array is just paranoia. It should always
163 // be an array.
164 foreach( $data['xmp-special']['LocationShown'] as $loc ) {
165 if ( !is_array( $loc ) ) {
166 // To avoid copying over the _type meta-fields.
167 continue;
168 }
169 foreach( $loc as $field => $val ) {
170 $data['xmp-general'][$field . 'Dest'][] = $val;
171 }
172 }
173 }
174 if ( isset( $data['xmp-special']['LocationCreated'][0] )
175 && is_array( $data['xmp-special']['LocationCreated'][0] )
176 ) {
177 // the is_array is just paranoia. It should always
178 // be an array.
179 foreach( $data['xmp-special']['LocationCreated'] as $loc ) {
180 if ( !is_array( $loc ) ) {
181 // To avoid copying over the _type meta-fields.
182 continue;
183 }
184 foreach( $loc as $field => $val ) {
185 $data['xmp-general'][$field . 'Created'][] = $val;
186 }
187 }
188 }
189
190
191 // We don't want to return the special values, since they're
192 // special and not info to be stored about the file.
193 unset( $data['xmp-special'] );
194
195 // Convert GPSAltitude to negative if below sea level.
196 if ( isset( $data['xmp-exif']['GPSAltitudeRef'] ) ) {
197 if ( $data['xmp-exif']['GPSAltitudeRef'] == '1'
198 && isset( $data['xmp-exif']['GPSAltitude'] )
199 ) {
200 $data['xmp-exif']['GPSAltitude'] *= -1;
201 }
202 unset( $data['xmp-exif']['GPSAltitudeRef'] );
203 }
204
205 return $data;
206 }
207
208 /**
209 * Main function to call to parse XMP. Use getResults to
210 * get results.
211 *
212 * Also catches any errors during processing, writes them to
213 * debug log, blanks result array and returns false.
214 *
215 * @param String: $content XMP data
216 * @param Boolean: $allOfIt If this is all the data (true) or if its split up (false). Default true
217 * @param Boolean: $reset - does xml parser need to be reset. Default false
218 * @return Boolean success.
219 */
220 public function parse( $content, $allOfIt = true, $reset = false ) {
221 if ( $reset ) {
222 $this->resetXMLParser();
223 }
224 try {
225
226 // detect encoding by looking for BOM which is supposed to be in processing instruction.
227 // see page 12 of http://www.adobe.com/devnet/xmp/pdfs/XMPSpecificationPart3.pdf
228 if ( !$this->charset ) {
229 $bom = array();
230 if ( preg_match( '/\xEF\xBB\xBF|\xFE\xFF|\x00\x00\xFE\xFF|\xFF\xFE\x00\x00|\xFF\xFE/',
231 $content, $bom )
232 ) {
233 switch ( $bom[0] ) {
234 case "\xFE\xFF":
235 $this->charset = 'UTF-16BE';
236 break;
237 case "\xFF\xFE":
238 $this->charset = 'UTF-16LE';
239 break;
240 case "\x00\x00\xFE\xFF":
241 $this->charset = 'UTF-32BE';
242 break;
243 case "\xFF\xFE\x00\x00":
244 $this->charset = 'UTF-32LE';
245 break;
246 case "\xEF\xBB\xBF":
247 $this->charset = 'UTF-8';
248 break;
249 default:
250 //this should be impossible to get to
251 throw new MWException("Invalid BOM");
252 break;
253
254 }
255
256 } else {
257 // standard specifically says, if no bom assume utf-8
258 $this->charset = 'UTF-8';
259 }
260 }
261 if ( $this->charset !== 'UTF-8' ) {
262 //don't convert if already utf-8
263 $content = iconv( $this->charset, 'UTF-8//IGNORE', $content );
264 }
265
266 $ok = xml_parse( $this->xmlParser, $content, $allOfIt );
267 if ( !$ok ) {
268 $error = xml_error_string( xml_get_error_code( $this->xmlParser ) );
269 $where = 'line: ' . xml_get_current_line_number( $this->xmlParser )
270 . ' column: ' . xml_get_current_column_number( $this->xmlParser )
271 . ' byte offset: ' . xml_get_current_byte_index( $this->xmlParser );
272
273 wfDebugLog( 'XMP', "XMPReader::parse : Error reading XMP content: $error ($where)" );
274 $this->results = array(); // blank if error.
275 return false;
276 }
277 } catch ( MWException $e ) {
278 wfDebugLog( 'XMP', 'XMP parse error: ' . $e );
279 $this->results = array();
280 return false;
281 }
282 return true;
283 }
284
285 /** Entry point for XMPExtended blocks in jpeg files
286 *
287 * @todo In serious need of testing
288 * @see http://www.adobe.ge/devnet/xmp/pdfs/XMPSpecificationPart3.pdf XMP spec part 3 page 20
289 * @param String $content XMPExtended block minus the namespace signature
290 * @return Boolean If it succeeded.
291 */
292 public function parseExtended( $content ) {
293 // FIXME: This is untested. Hard to find example files
294 // or programs that make such files..
295 $guid = substr( $content, 0, 32 );
296 if ( !isset( $this->results['xmp-special']['HasExtendedXMP'] )
297 || $this->results['xmp-special']['HasExtendedXMP'] !== $guid )
298 {
299 wfDebugLog('XMP', __METHOD__ . " Ignoring XMPExtended block due to wrong guid (guid= '$guid' )");
300 return;
301 }
302 $len = unpack( 'Nlength/Noffset', substr( $content, 32, 8 ) );
303
304 if (!$len || $len['length'] < 4 || $len['offset'] < 0 || $len['offset'] > $len['length'] ) {
305 wfDebugLog('XMP', __METHOD__ . 'Error reading extended XMP block, invalid length or offset.');
306 return false;
307 }
308
309
310 // we're not very robust here. we should accept it in the wrong order. To quote
311 // the xmp standard:
312 // "A JPEG writer should write the ExtendedXMP marker segments in order, immediately following the
313 // StandardXMP. However, the JPEG standard does not require preservation of marker segment order. A
314 // robust JPEG reader should tolerate the marker segments in any order."
315 //
316 // otoh the probability that an image will have more than 128k of metadata is rather low...
317 // so the probability that it will have > 128k, and be in the wrong order is very low...
318
319 if ( $len['offset'] !== $this->extendedXMPOffset ) {
320 wfDebugLog('XMP', __METHOD__ . 'Ignoring XMPExtended block due to wrong order. (Offset was '
321 . $len['offset'] . ' but expected ' . $this->extendedXMPOffset . ')');
322 return false;
323 }
324
325 if ( $len['offset'] === 0 ) {
326 // if we're starting the extended block, we've probably already
327 // done the XMPStandard block, so reset.
328 $this->resetXMLParser();
329 }
330
331 $this->extendedXMPOffset += $len['length'];
332
333 $actualContent = substr( $content, 40 );
334
335 if ( $this->extendedXMPOffset === strlen( $actualContent ) ) {
336 $atEnd = true;
337 } else {
338 $atEnd = false;
339 }
340
341 wfDebugLog('XMP', __METHOD__ . 'Parsing a XMPExtended block');
342 return $this->parse( $actualContent, $atEnd );
343 }
344
345 /**
346 * Character data handler
347 * Called whenever character data is found in the xmp document.
348 *
349 * does nothing if we're in MODE_IGNORE or if the data is whitespace
350 * throws an error if we're not in MODE_SIMPLE (as we're not allowed to have character
351 * data in the other modes).
352 *
353 * As an example, this happens when we encounter XMP like:
354 * <exif:DigitalZoomRatio>0/10</exif:DigitalZoomRatio>
355 * and are processing the 0/10 bit.
356 *
357 * @param $parser XMLParser reference to the xml parser
358 * @param $data String Character data
359 * @throws MWException on invalid data
360 */
361 function char( $parser, $data ) {
362
363 $data = trim( $data );
364 if ( trim( $data ) === "" ) {
365 return;
366 }
367
368 if ( !isset( $this->mode[0] ) ) {
369 throw new MWException( 'Unexpected character data before first rdf:Description element' );
370 }
371
372 if ( $this->mode[0] === self::MODE_IGNORE ) return;
373
374 if ( $this->mode[0] !== self::MODE_SIMPLE
375 && $this->mode[0] !== self::MODE_QDESC
376 ) {
377 throw new MWException( 'character data where not expected. (mode ' . $this->mode[0] . ')' );
378 }
379
380 // to check, how does this handle w.s.
381 if ( $this->charContent === false ) {
382 $this->charContent = $data;
383 } else {
384 $this->charContent .= $data;
385 }
386
387 }
388 /** When we hit a closing element in MODE_IGNORE
389 * Check to see if this is the element we started to ignore,
390 * in which case we get out of MODE_IGNORE
391 *
392 * @param $elm String Namespace of element followed by a space and then tag name of element.
393 */
394 private function endElementModeIgnore ( $elm ) {
395
396 if ( $this->curItem[0] === $elm ) {
397 array_shift( $this->curItem );
398 array_shift( $this->mode );
399 }
400 return;
401
402 }
403 /**
404 * Hit a closing element when in MODE_SIMPLE.
405 * This generally means that we finished processing a
406 * property value, and now have to save the result to the
407 * results array
408 *
409 * For example, when processing:
410 * <exif:DigitalZoomRatio>0/10</exif:DigitalZoomRatio>
411 * this deals with when we hit </exif:DigitalZoomRatio>.
412 *
413 * Or it could be if we hit the end element of a property
414 * of a compound data structure (like a member of an array).
415 *
416 * @param $elm String namespace, space, and tag name.
417 */
418 private function endElementModeSimple ( $elm ) {
419 if ( $this->charContent !== false ) {
420 if ( $this->processingArray ) {
421 // if we're processing an array, use the original element
422 // name instead of rdf:li.
423 list( $ns, $tag ) = explode( ' ', $this->curItem[0], 2 );
424 } else {
425 list( $ns, $tag ) = explode( ' ', $elm, 2 );
426 }
427 $this->saveValue( $ns, $tag, $this->charContent );
428
429 $this->charContent = false; // reset
430 }
431 array_shift( $this->curItem );
432 array_shift( $this->mode );
433
434 }
435 /**
436 * Hit a closing element in MODE_STRUCT, MODE_SEQ, MODE_BAG
437 * generally means we've finished processing a nested structure.
438 * resets some internal variables to indicate that.
439 *
440 * Note this means we hit the </closing element> not the </rdf:Seq>.
441 *
442 * For example, when processing:
443 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
444 * </rdf:Seq> </exif:ISOSpeedRatings>
445 *
446 * This method is called when we hit the </exif:ISOSpeedRatings> tag.
447 *
448 * @param $elm String namespace . space . tag name.
449 */
450 private function endElementNested( $elm ) {
451
452 /* cur item must be the same as $elm, unless if in MODE_STRUCT
453 in which case it could also be rdf:Description */
454 if ( $this->curItem[0] !== $elm
455 && !( $elm === self::NS_RDF . ' Description'
456 && $this->mode[0] === self::MODE_STRUCT )
457 ) {
458 throw new MWException( "nesting mismatch. got a </$elm> but expected a </" . $this->curItem[0] . '>' );
459 }
460
461 // Validate structures.
462 list( $ns, $tag ) = explode( ' ', $elm, 2 );
463 if ( isset( $this->items[$ns][$tag]['validate'] ) ) {
464
465 $info =& $this->items[$ns][$tag];
466 $finalName = isset( $info['map_name'] )
467 ? $info['map_name'] : $tag;
468
469 $validate = is_array( $info['validate'] ) ? $info['validate']
470 : array( 'XMPValidate', $info['validate'] );
471
472 if ( !isset( $this->results['xmp-' . $info['map_group']][$finalName] ) ) {
473 // This can happen if all the members of the struct failed validation.
474 wfDebugLog( 'XMP', __METHOD__ . " <$ns:$tag> has no valid members." );
475
476 } elseif ( is_callable( $validate ) ) {
477 $val =& $this->results['xmp-' . $info['map_group']][$finalName];
478 call_user_func_array( $validate, array( $info, &$val, false ) );
479 if ( is_null( $val ) ) {
480 // the idea being the validation function will unset the variable if
481 // its invalid.
482 wfDebugLog( 'XMP', __METHOD__ . " <$ns:$tag> failed validation." );
483 unset( $this->results['xmp-' . $info['map_group']][$finalName] );
484 }
485 } else {
486 wfDebugLog( 'XMP', __METHOD__ . " Validation function for $finalName ("
487 . $validate[0] . '::' . $validate[1] . '()) is not callable.' );
488 }
489 }
490
491 array_shift( $this->curItem );
492 array_shift( $this->mode );
493 $this->ancestorStruct = false;
494 $this->processingArray = false;
495 $this->itemLang = false;
496 }
497
498 /**
499 * Hit a closing element in MODE_LI (either rdf:Seq, or rdf:Bag )
500 * Add information about what type of element this is.
501 *
502 * Note we still have to hit the outer </property>
503 *
504 * For example, when processing:
505 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
506 * </rdf:Seq> </exif:ISOSpeedRatings>
507 *
508 * This method is called when we hit the </rdf:Seq>.
509 * (For comparison, we call endElementModeSimple when we
510 * hit the </rdf:li>)
511 *
512 * @param $elm String namespace . ' ' . element name
513 */
514 private function endElementModeLi( $elm ) {
515
516 list( $ns, $tag ) = explode( ' ', $this->curItem[0], 2 );
517 $info = $this->items[$ns][$tag];
518 $finalName = isset( $info['map_name'] )
519 ? $info['map_name'] : $tag;
520
521 array_shift( $this->mode );
522
523 if ( !isset( $this->results['xmp-' . $info['map_group']][$finalName] ) ) {
524 wfDebugLog( 'XMP', __METHOD__ . " Empty compund element $finalName." );
525 return;
526 }
527
528 if ( $elm === self::NS_RDF . ' Seq' ) {
529 $this->results['xmp-' . $info['map_group']][$finalName]['_type'] = 'ol';
530 } elseif ( $elm === self::NS_RDF . ' Bag' ) {
531 $this->results['xmp-' . $info['map_group']][$finalName]['_type'] = 'ul';
532 } elseif ( $elm === self::NS_RDF . ' Alt' ) {
533 // extra if needed as you could theoretically have a non-language alt.
534 if ( $info['mode'] === self::MODE_LANG ) {
535 $this->results['xmp-' . $info['map_group']][$finalName]['_type'] = 'lang';
536 }
537
538 } else {
539 throw new MWException( __METHOD__ . " expected </rdf:seq> or </rdf:bag> but instead got $elm." );
540 }
541 }
542 /**
543 * End element while in MODE_QDESC
544 * mostly when ending an element when we have a simple value
545 * that has qualifiers.
546 *
547 * Qualifiers aren't all that common, and we don't do anything
548 * with them.
549 *
550 * @param $elm String namespace and element
551 */
552 private function endElementModeQDesc( $elm ) {
553
554 if ( $elm === self::NS_RDF . ' value' ) {
555 list( $ns, $tag ) = explode( ' ', $this->curItem[0], 2 );
556 $this->saveValue( $ns, $tag, $this->charContent );
557 return;
558 } else {
559 array_shift( $this->mode );
560 array_shift( $this->curItem );
561 }
562
563
564 }
565 /**
566 * Handler for hitting a closing element.
567 *
568 * generally just calls a helper function depending on what
569 * mode we're in.
570 *
571 * Ignores the outer wrapping elements that are optional in
572 * xmp and have no meaning.
573 *
574 * @param $parser XMLParser
575 * @param $elm String namespace . ' ' . element name
576 */
577 function endElement( $parser, $elm ) {
578 if ( $elm === ( self::NS_RDF . ' RDF' )
579 || $elm === 'adobe:ns:meta/ xmpmeta'
580 || $elm === 'adobe:ns:meta/ xapmeta' )
581 {
582 // ignore these.
583 return;
584 }
585
586 if ( $elm === self::NS_RDF . ' type' ) {
587 // these aren't really supported properly yet.
588 // However, it appears they almost never used.
589 wfDebugLog( 'XMP', __METHOD__ . ' encountered <rdf:type>' );
590 }
591
592 if ( strpos( $elm, ' ' ) === false ) {
593 // This probably shouldn't happen.
594 // However, there is a bug in an adobe product
595 // that forgets the namespace on some things.
596 // (Luckily they are unimportant things).
597 wfDebugLog( 'XMP', __METHOD__ . " Encountered </$elm> which has no namespace. Skipping." );
598 return;
599 }
600
601 if ( count( $this->mode[0] ) === 0 ) {
602 // This should never ever happen and means
603 // there is a pretty major bug in this class.
604 throw new MWException( 'Encountered end element with no mode' );
605 }
606
607 if ( count( $this->curItem ) == 0 && $this->mode[0] !== self::MODE_INITIAL ) {
608 // just to be paranoid. Should always have a curItem, except for initially
609 // (aka during MODE_INITAL).
610 throw new MWException( "Hit end element </$elm> but no curItem" );
611 }
612
613 switch( $this->mode[0] ) {
614 case self::MODE_IGNORE:
615 $this->endElementModeIgnore( $elm );
616 break;
617 case self::MODE_SIMPLE:
618 $this->endElementModeSimple( $elm );
619 break;
620 case self::MODE_STRUCT:
621 case self::MODE_SEQ:
622 case self::MODE_BAG:
623 case self::MODE_LANG:
624 case self::MODE_BAGSTRUCT:
625 $this->endElementNested( $elm );
626 break;
627 case self::MODE_INITIAL:
628 if ( $elm === self::NS_RDF . ' Description' ) {
629 array_shift( $this->mode );
630 } else {
631 throw new MWException( 'Element ended unexpectedly while in MODE_INITIAL' );
632 }
633 break;
634 case self::MODE_LI:
635 case self::MODE_LI_LANG:
636 $this->endElementModeLi( $elm );
637 break;
638 case self::MODE_QDESC:
639 $this->endElementModeQDesc( $elm );
640 break;
641 default:
642 wfDebugLog( 'XMP', __METHOD__ . " no mode (elm = $elm)" );
643 break;
644 }
645 }
646
647
648 /**
649 * Hit an opening element while in MODE_IGNORE
650 *
651 * XMP is extensible, so ignore any tag we don't understand.
652 *
653 * Mostly ignores, unless we encounter the element that we are ignoring.
654 * in which case we add it to the item stack, so we can ignore things
655 * that are nested, correctly.
656 *
657 * @param $elm String namespace . ' ' . tag name
658 */
659 private function startElementModeIgnore( $elm ) {
660 if ( $elm === $this->curItem[0] ) {
661 array_unshift( $this->curItem, $elm );
662 array_unshift( $this->mode, self::MODE_IGNORE );
663 }
664 }
665 /**
666 * Start element in MODE_BAG (unordered array)
667 * this should always be <rdf:Bag>
668 *
669 * @param $elm String namespace . ' ' . tag
670 * @throws MWException if we have an element that's not <rdf:Bag>
671 */
672 private function startElementModeBag( $elm ) {
673 if ( $elm === self::NS_RDF . ' Bag' ) {
674 array_unshift( $this->mode, self::MODE_LI );
675 } else {
676 throw new MWException( "Expected <rdf:Bag> but got $elm." );
677 }
678
679 }
680 /**
681 * Start element in MODE_SEQ (ordered array)
682 * this should always be <rdf:Seq>
683 *
684 * @param $elm String namespace . ' ' . tag
685 * @throws MWException if we have an element that's not <rdf:Seq>
686 */
687 private function startElementModeSeq( $elm ) {
688 if ( $elm === self::NS_RDF . ' Seq' ) {
689 array_unshift( $this->mode, self::MODE_LI );
690 } else if ( $elm === self::NS_RDF . ' Bag' ) {
691 # bug 27105
692 wfDebugLog( 'XMP', __METHOD__ . ' Expected an rdf:Seq, but got an rdf:Bag. Pretending'
693 . ' it is a Seq, since some buggy software is known to screw this up.' );
694 array_unshift( $this->mode, self::MODE_LI );
695 } else {
696 throw new MWException( "Expected <rdf:Seq> but got $elm." );
697 }
698
699 }
700 /**
701 * Start element in MODE_LANG (language alternative)
702 * this should always be <rdf:Alt>
703 *
704 * This tag tends to be used for metadata like describe this
705 * picture, which can be translated into multiple languages.
706 *
707 * XMP supports non-linguistic alternative selections,
708 * which are really only used for thumbnails, which
709 * we don't care about.
710 *
711 * @param $elm String namespace . ' ' . tag
712 * @throws MWException if we have an element that's not <rdf:Alt>
713 */
714 private function startElementModeLang( $elm ) {
715 if ( $elm === self::NS_RDF . ' Alt' ) {
716 array_unshift( $this->mode, self::MODE_LI_LANG );
717 } else {
718 throw new MWException( "Expected <rdf:Seq> but got $elm." );
719 }
720
721 }
722 /**
723 * Handle an opening element when in MODE_SIMPLE
724 *
725 * This should not happen often. This is for if a simple element
726 * already opened has a child element. Could happen for a
727 * qualified element.
728 *
729 * For example:
730 * <exif:DigitalZoomRatio><rdf:Description><rdf:value>0/10</rdf:value>
731 * <foo:someQualifier>Bar</foo:someQualifier> </rdf:Description>
732 * </exif:DigitalZoomRatio>
733 *
734 * This method is called when processing the <rdf:Description> element
735 *
736 * @param $elm String namespace and tag names separated by space.
737 * @param $attribs Array Attributes of the element.
738 */
739 private function startElementModeSimple( $elm, $attribs ) {
740 if ( $elm === self::NS_RDF . ' Description' ) {
741 // If this value has qualifiers
742 array_unshift( $this->mode, self::MODE_QDESC );
743 array_unshift( $this->curItem, $this->curItem[0] );
744
745 if ( isset( $attribs[self::NS_RDF . ' value'] ) ) {
746 list( $ns, $tag ) = explode( ' ', $this->curItem[0], 2 );
747 $this->saveValue( $ns, $tag, $attribs[self::NS_RDF . ' value'] );
748 }
749 } elseif ( $elm === self::NS_RDF . ' value' ) {
750 // This should not be here.
751 throw new MWException( __METHOD__ . ' Encountered <rdf:value> where it was unexpected.' );
752
753 } else {
754 // something else we don't recognize, like a qualifier maybe.
755 wfDebugLog( 'XMP', __METHOD__ . " Encountered element <$elm> where only expecting character data as value of " . $this->curItem[0] );
756 array_unshift( $this->mode, self::MODE_IGNORE );
757 array_unshift( $this->curItem, $elm );
758
759 }
760
761 }
762 /**
763 * Start an element when in MODE_QDESC.
764 * This generally happens when a simple element has an inner
765 * rdf:Description to hold qualifier elements.
766 *
767 * For example in:
768 * <exif:DigitalZoomRatio><rdf:Description><rdf:value>0/10</rdf:value>
769 * <foo:someQualifier>Bar</foo:someQualifier> </rdf:Description>
770 * </exif:DigitalZoomRatio>
771 * Called when processing the <rdf:value> or <foo:someQualifier>.
772 *
773 * @param $elm String namespace and tag name separated by a space.
774 *
775 */
776 private function startElementModeQDesc( $elm ) {
777 if ( $elm === self::NS_RDF . ' value' ) {
778 return; // do nothing
779 } else {
780 // otherwise its a qualifier, which we ignore
781 array_unshift( $this->mode, self::MODE_IGNORE );
782 array_unshift( $this->curItem, $elm );
783 }
784 }
785 /**
786 * Starting an element when in MODE_INITIAL
787 * This usually happens when we hit an element inside
788 * the outer rdf:Description
789 *
790 * This is generally where most properties start.
791 *
792 * @param $ns String Namespace
793 * @param $tag String tag name (without namespace prefix)
794 * @param $attribs Array array of attributes
795 */
796 private function startElementModeInitial( $ns, $tag, $attribs ) {
797 if ( $ns !== self::NS_RDF ) {
798
799 if ( isset( $this->items[$ns][$tag] ) ) {
800 if ( isset( $this->items[$ns][$tag]['structPart'] ) ) {
801 // If this element is supposed to appear only as
802 // a child of a structure, but appears here (not as
803 // a child of a struct), then something weird is
804 // happening, so ignore this element and its children.
805
806 wfDebugLog( 'XMP', "Encountered <$ns:$tag> outside"
807 . " of its expected parent. Ignoring." );
808
809 array_unshift( $this->mode, self::MODE_IGNORE );
810 array_unshift( $this->curItem, $ns . ' ' . $tag );
811 return;
812 }
813 $mode = $this->items[$ns][$tag]['mode'];
814 array_unshift( $this->mode, $mode );
815 array_unshift( $this->curItem, $ns . ' ' . $tag );
816 if ( $mode === self::MODE_STRUCT ) {
817 $this->ancestorStruct = isset( $this->items[$ns][$tag]['map_name'] )
818 ? $this->items[$ns][$tag]['map_name'] : $tag;
819 }
820 if ( $this->charContent !== false ) {
821 // Something weird.
822 // Should not happen in valid XMP.
823 throw new MWException( 'tag nested in non-whitespace characters.' );
824 }
825 } else {
826 // This element is not on our list of allowed elements so ignore.
827 wfDebugLog( 'XMP', __METHOD__ . " Ignoring unrecognized element <$ns:$tag>." );
828 array_unshift( $this->mode, self::MODE_IGNORE );
829 array_unshift( $this->curItem, $ns . ' ' . $tag );
830 return;
831 }
832
833 }
834 // process attributes
835 $this->doAttribs( $attribs );
836 }
837 /**
838 * Hit an opening element when in a Struct (MODE_STRUCT)
839 * This is generally for fields of a compound property.
840 *
841 * Example of a struct (abbreviated; flash has more properties):
842 *
843 * <exif:Flash> <rdf:Description> <exif:Fired>True</exif:Fired>
844 * <exif:Mode>1</exif:Mode></rdf:Description></exif:Flash>
845 *
846 * or:
847 *
848 * <exif:Flash rdf:parseType='Resource'> <exif:Fired>True</exif:Fired>
849 * <exif:Mode>1</exif:Mode></exif:Flash>
850 *
851 * @param $ns String namespace
852 * @param $tag String tag name (no ns)
853 * @param $attribs Array array of attribs w/ values.
854 */
855 private function startElementModeStruct( $ns, $tag, $attribs ) {
856 if ( $ns !== self::NS_RDF ) {
857
858 if ( isset( $this->items[$ns][$tag] ) ) {
859 if ( isset( $this->items[$ns][$this->ancestorStruct]['children'] )
860 && !isset( $this->items[$ns][$this->ancestorStruct]['children'][$tag] ) )
861 {
862 // This assumes that we don't have inter-namespace nesting
863 // which we don't in all the properties we're interested in.
864 throw new MWException( " <$tag> appeared nested in <" . $this->ancestorStruct
865 . "> where it is not allowed." );
866 }
867 array_unshift( $this->mode, $this->items[$ns][$tag]['mode'] );
868 array_unshift( $this->curItem, $ns . ' ' . $tag );
869 if ( $this->charContent !== false ) {
870 // Something weird.
871 // Should not happen in valid XMP.
872 throw new MWException( "tag <$tag> nested in non-whitespace characters (" . $this->charContent . ")." );
873 }
874 } else {
875 array_unshift( $this->mode, self::MODE_IGNORE );
876 array_unshift( $this->curItem, $elm );
877 return;
878 }
879
880 }
881
882 if ( $ns === self::NS_RDF && $tag === 'Description' ) {
883 $this->doAttribs( $attribs );
884 array_unshift( $this->mode, self::MODE_STRUCT );
885 array_unshift( $this->curItem, $this->curItem[0] );
886 }
887 }
888 /**
889 * opening element in MODE_LI
890 * process elements of arrays.
891 *
892 * Example:
893 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
894 * </rdf:Seq> </exif:ISOSpeedRatings>
895 * This method is called when we hit the <rdf:li> element.
896 *
897 * @param $elm String: namespace . ' ' . tagname
898 * @param $attribs Array: Attributes. (needed for BAGSTRUCTS)
899 * @throws MWException if gets a tag other than <rdf:li>
900 */
901 private function startElementModeLi( $elm, $attribs ) {
902 if ( ( $elm ) !== self::NS_RDF . ' li' ) {
903 throw new MWException( "<rdf:li> expected but got $elm." );
904 }
905
906 if ( !isset( $this->mode[1] ) ) {
907 // This should never ever ever happen. Checking for it
908 // to be paranoid.
909 throw new MWException( 'In mode Li, but no 2xPrevious mode!' );
910 }
911
912 if ( $this->mode[1] === self::MODE_BAGSTRUCT ) {
913 // This list item contains a compound (STRUCT) value.
914 array_unshift( $this->mode, self::MODE_STRUCT );
915 array_unshift( $this->curItem, $elm );
916 $this->processingArray = true;
917
918 if ( !isset( $this->curItem[1] ) ) {
919 // be paranoid.
920 throw new MWException( 'Can not find parent of BAGSTRUCT.' );
921 }
922 list( $curNS, $curTag ) = explode( ' ', $this->curItem[1] );
923 $this->ancestorStruct = isset( $this->items[$curNS][$curTag]['map_name'] )
924 ? $this->items[$curNS][$curTag]['map_name'] : $curTag;
925
926 $this->doAttribs( $attribs );
927
928 } else {
929 // Normal BAG or SEQ containing simple values.
930 array_unshift( $this->mode, self::MODE_SIMPLE );
931 // need to add curItem[0] on again since one is for the specific item
932 // and one is for the entire group.
933 array_unshift( $this->curItem, $this->curItem[0] );
934 $this->processingArray = true;
935 }
936
937 }
938 /**
939 * Opening element in MODE_LI_LANG.
940 * process elements of language alternatives
941 *
942 * Example:
943 * <dc:title> <rdf:Alt> <rdf:li xml:lang="x-default">My house
944 * </rdf:li> </rdf:Alt> </dc:title>
945 *
946 * This method is called when we hit the <rdf:li> element.
947 *
948 * @param $elm String namespace . ' ' . tag
949 * @param $attribs array array of elements (most importantly xml:lang)
950 * @throws MWException if gets a tag other than <rdf:li> or if no xml:lang
951 */
952 private function startElementModeLiLang( $elm, $attribs ) {
953 if ( $elm !== self::NS_RDF . ' li' ) {
954 throw new MWException( __METHOD__ . " <rdf:li> expected but got $elm." );
955 }
956 if ( !isset( $attribs[ self::NS_XML . ' lang'] )
957 || !preg_match( '/^[-A-Za-z0-9]{2,}$/D', $attribs[ self::NS_XML . ' lang' ] ) )
958 {
959 throw new MWException( __METHOD__
960 . " <rdf:li> did not contain, or has invalid xml:lang attribute in lang alternative" );
961 }
962
963 // Lang is case-insensitive.
964 $this->itemLang = strtolower( $attribs[ self::NS_XML . ' lang' ] );
965
966 // need to add curItem[0] on again since one is for the specific item
967 // and one is for the entire group.
968 array_unshift( $this->curItem, $this->curItem[0] );
969 array_unshift( $this->mode, self::MODE_SIMPLE );
970 $this->processingArray = true;
971 }
972
973 /**
974 * Hits an opening element.
975 * Generally just calls a helper based on what MODE we're in.
976 * Also does some initial set up for the wrapper element
977 *
978 * @param $parser XMLParser
979 * @param $elm String namespace <space> element
980 * @param $attribs Array attribute name => value
981 */
982 function startElement( $parser, $elm, $attribs ) {
983
984 if ( $elm === self::NS_RDF . ' RDF'
985 || $elm === 'adobe:ns:meta/ xmpmeta'
986 || $elm === 'adobe:ns:meta/ xapmeta')
987 {
988 /* ignore. */
989 return;
990 } elseif ( $elm === self::NS_RDF . ' Description' ) {
991 if ( count( $this->mode ) === 0 ) {
992 // outer rdf:desc
993 array_unshift( $this->mode, self::MODE_INITIAL );
994 }
995 } elseif ( $elm === self::NS_RDF . ' type' ) {
996 // This doesn't support rdf:type properly.
997 // In practise I have yet to see a file that
998 // uses this element, however it is mentioned
999 // on page 25 of part 1 of the xmp standard.
1000 //
1001 // also it seems as if exiv2 and exiftool do not support
1002 // this either (That or I misunderstand the standard)
1003 wfDebugLog( 'XMP', __METHOD__ . ' Encountered <rdf:type> which isn\'t currently supported' );
1004 }
1005
1006 if ( strpos( $elm, ' ' ) === false ) {
1007 // This probably shouldn't happen.
1008 wfDebugLog( 'XMP', __METHOD__ . " Encountered <$elm> which has no namespace. Skipping." );
1009 return;
1010 }
1011
1012 list( $ns, $tag ) = explode( ' ', $elm, 2 );
1013
1014 if ( count( $this->mode ) === 0 ) {
1015 // This should not happen.
1016 throw new MWException('Error extracting XMP, '
1017 . "encountered <$elm> with no mode" );
1018 }
1019
1020 switch( $this->mode[0] ) {
1021 case self::MODE_IGNORE:
1022 $this->startElementModeIgnore( $elm );
1023 break;
1024 case self::MODE_SIMPLE:
1025 $this->startElementModeSimple( $elm, $attribs );
1026 break;
1027 case self::MODE_INITIAL:
1028 $this->startElementModeInitial( $ns, $tag, $attribs );
1029 break;
1030 case self::MODE_STRUCT:
1031 $this->startElementModeStruct( $ns, $tag, $attribs );
1032 break;
1033 case self::MODE_BAG:
1034 case self::MODE_BAGSTRUCT:
1035 $this->startElementModeBag( $elm );
1036 break;
1037 case self::MODE_SEQ:
1038 $this->startElementModeSeq( $elm );
1039 break;
1040 case self::MODE_LANG:
1041 $this->startElementModeLang( $elm );
1042 break;
1043 case self::MODE_LI_LANG:
1044 $this->startElementModeLiLang( $elm, $attribs );
1045 break;
1046 case self::MODE_LI:
1047 $this->startElementModeLi( $elm, $attribs );
1048 break;
1049 case self::MODE_QDESC:
1050 $this->startElementModeQDesc( $elm );
1051 break;
1052 default:
1053 throw new MWException( 'StartElement in unknown mode: ' . $this->mode[0] );
1054 break;
1055 }
1056
1057
1058
1059 }
1060 /**
1061 * Process attributes.
1062 * Simple values can be stored as either a tag or attribute
1063 *
1064 * Often the initial <rdf:Description> tag just has all the simple
1065 * properties as attributes.
1066 *
1067 * Example:
1068 * <rdf:Description rdf:about="" xmlns:exif="http://ns.adobe.com/exif/1.0/" exif:DigitalZoomRatio="0/10">
1069 *
1070 * @param $attribs Array attribute=>value array.
1071 */
1072 private function doAttribs( $attribs ) {
1073
1074 // first check for rdf:parseType attribute, as that can change
1075 // how the attributes are interperted.
1076
1077 if ( isset( $attribs[self::NS_RDF . ' parseType'] )
1078 && $attribs[self::NS_RDF . ' parseType'] === 'Resource'
1079 && $this->mode[0] === self::MODE_SIMPLE )
1080 {
1081 // this is equivalent to having an inner rdf:Description
1082 $this->mode[0] = self::MODE_QDESC;
1083 }
1084 foreach ( $attribs as $name => $val ) {
1085
1086
1087 if ( strpos( $name, ' ' ) === false ) {
1088 // This shouldn't happen, but so far some old software forgets namespace
1089 // on rdf:about.
1090 wfDebugLog( 'XMP', __METHOD__ . ' Encountered non-namespaced attribute: '
1091 . " $name=\"$val\". Skipping. " );
1092 continue;
1093 }
1094 list( $ns, $tag ) = explode( ' ', $name, 2 );
1095 if ( $ns === self::NS_RDF ) {
1096 if ( $tag === 'value' || $tag === 'resource' ) {
1097 // resource is for url.
1098 // value attribute is a weird way of just putting the contents.
1099 $this->char( $this->xmlParser, $val );
1100 }
1101 } elseif ( isset( $this->items[$ns][$tag] ) ) {
1102 if ( $this->mode[0] === self::MODE_SIMPLE ) {
1103 throw new MWException( __METHOD__
1104 . " $ns:$tag found as attribute where not allowed" );
1105 }
1106 $this->saveValue( $ns, $tag, $val );
1107 } else {
1108 wfDebugLog( 'XMP', __METHOD__ . " Ignoring unrecognized element <$ns:$tag>." );
1109 }
1110 }
1111 }
1112 /**
1113 * Given an extracted value, save it to results array
1114 *
1115 * note also uses $this->ancestorStruct and
1116 * $this->processingArray to determine what name to
1117 * save the value under. (in addition to $tag).
1118 *
1119 * @param $ns String namespace of tag this is for
1120 * @param $tag String tag name
1121 * @param $val String value to save
1122 */
1123 private function saveValue( $ns, $tag, $val ) {
1124
1125 $info =& $this->items[$ns][$tag];
1126 $finalName = isset( $info['map_name'] )
1127 ? $info['map_name'] : $tag;
1128 if ( isset( $info['validate'] ) ) {
1129 $validate = is_array( $info['validate'] ) ? $info['validate']
1130 : array( 'XMPValidate', $info['validate'] );
1131
1132 if ( is_callable( $validate ) ) {
1133 call_user_func_array( $validate, array( $info, &$val, true ) );
1134 // the reasoning behind using &$val instead of using the return value
1135 // is to be consistent between here and validating structures.
1136 if ( is_null( $val ) ) {
1137 wfDebugLog( 'XMP', __METHOD__ . " <$ns:$tag> failed validation." );
1138 return;
1139 }
1140 } else {
1141 wfDebugLog( 'XMP', __METHOD__ . " Validation function for $finalName ("
1142 . $validate[0] . '::' . $validate[1] . '()) is not callable.' );
1143 }
1144 }
1145
1146 if ( $this->ancestorStruct && $this->processingArray ) {
1147 // Aka both an array and a struct. ( self::MODE_BAGSTRUCT )
1148 $this->results['xmp-' . $info['map_group']][$this->ancestorStruct][][$finalName] = $val;
1149 } elseif ( $this->ancestorStruct ) {
1150 $this->results['xmp-' . $info['map_group']][$this->ancestorStruct][$finalName] = $val;
1151 } elseif ( $this->processingArray ) {
1152 if ( $this->itemLang === false ) {
1153 // normal array
1154 $this->results['xmp-' . $info['map_group']][$finalName][] = $val;
1155 } else {
1156 // lang array.
1157 $this->results['xmp-' . $info['map_group']][$finalName][$this->itemLang] = $val;
1158 }
1159 } else {
1160 $this->results['xmp-' . $info['map_group']][$finalName] = $val;
1161 }
1162 }
1163
1164
1165 }