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