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