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