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