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