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