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