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