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