Fix separated login link so that create account and login are always next to each...
[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 * @par For example, when processing:
467 * @code{,xml}
468 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
469 * </rdf:Seq> </exif:ISOSpeedRatings>
470 * @endcode
471 *
472 * This method is called when we hit the "</exif:ISOSpeedRatings>" tag.
473 *
474 * @param $elm String namespace . space . tag name.
475 */
476 private function endElementNested( $elm ) {
477
478 /* cur item must be the same as $elm, unless if in MODE_STRUCT
479 in which case it could also be rdf:Description */
480 if ( $this->curItem[0] !== $elm
481 && !( $elm === self::NS_RDF . ' Description'
482 && $this->mode[0] === self::MODE_STRUCT )
483 ) {
484 throw new MWException( "nesting mismatch. got a </$elm> but expected a </" . $this->curItem[0] . '>' );
485 }
486
487 // Validate structures.
488 list( $ns, $tag ) = explode( ' ', $elm, 2 );
489 if ( isset( $this->items[$ns][$tag]['validate'] ) ) {
490
491 $info =& $this->items[$ns][$tag];
492 $finalName = isset( $info['map_name'] )
493 ? $info['map_name'] : $tag;
494
495 $validate = is_array( $info['validate'] ) ? $info['validate']
496 : array( 'XMPValidate', $info['validate'] );
497
498 if ( !isset( $this->results['xmp-' . $info['map_group']][$finalName] ) ) {
499 // This can happen if all the members of the struct failed validation.
500 wfDebugLog( 'XMP', __METHOD__ . " <$ns:$tag> has no valid members." );
501
502 } elseif ( is_callable( $validate ) ) {
503 $val =& $this->results['xmp-' . $info['map_group']][$finalName];
504 call_user_func_array( $validate, array( $info, &$val, false ) );
505 if ( is_null( $val ) ) {
506 // the idea being the validation function will unset the variable if
507 // its invalid.
508 wfDebugLog( 'XMP', __METHOD__ . " <$ns:$tag> failed validation." );
509 unset( $this->results['xmp-' . $info['map_group']][$finalName] );
510 }
511 } else {
512 wfDebugLog( 'XMP', __METHOD__ . " Validation function for $finalName ("
513 . $validate[0] . '::' . $validate[1] . '()) is not callable.' );
514 }
515 }
516
517 array_shift( $this->curItem );
518 array_shift( $this->mode );
519 $this->ancestorStruct = false;
520 $this->processingArray = false;
521 $this->itemLang = false;
522 }
523
524 /**
525 * Hit a closing element in MODE_LI (either rdf:Seq, or rdf:Bag )
526 * Add information about what type of element this is.
527 *
528 * Note we still have to hit the outer "</property>"
529 *
530 * @par For example, when processing:
531 * @code{,xml}
532 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
533 * </rdf:Seq> </exif:ISOSpeedRatings>
534 * @endcode
535 *
536 * This method is called when we hit the "</rdf:Seq>".
537 * (For comparison, we call endElementModeSimple when we
538 * hit the "</rdf:li>")
539 *
540 * @param $elm String namespace . ' ' . element name
541 */
542 private function endElementModeLi( $elm ) {
543
544 list( $ns, $tag ) = explode( ' ', $this->curItem[0], 2 );
545 $info = $this->items[$ns][$tag];
546 $finalName = isset( $info['map_name'] )
547 ? $info['map_name'] : $tag;
548
549 array_shift( $this->mode );
550
551 if ( !isset( $this->results['xmp-' . $info['map_group']][$finalName] ) ) {
552 wfDebugLog( 'XMP', __METHOD__ . " Empty compund element $finalName." );
553 return;
554 }
555
556 if ( $elm === self::NS_RDF . ' Seq' ) {
557 $this->results['xmp-' . $info['map_group']][$finalName]['_type'] = 'ol';
558 } elseif ( $elm === self::NS_RDF . ' Bag' ) {
559 $this->results['xmp-' . $info['map_group']][$finalName]['_type'] = 'ul';
560 } elseif ( $elm === self::NS_RDF . ' Alt' ) {
561 // extra if needed as you could theoretically have a non-language alt.
562 if ( $info['mode'] === self::MODE_LANG ) {
563 $this->results['xmp-' . $info['map_group']][$finalName]['_type'] = 'lang';
564 }
565
566 } else {
567 throw new MWException( __METHOD__ . " expected </rdf:seq> or </rdf:bag> but instead got $elm." );
568 }
569 }
570
571 /**
572 * End element while in MODE_QDESC
573 * mostly when ending an element when we have a simple value
574 * that has qualifiers.
575 *
576 * Qualifiers aren't all that common, and we don't do anything
577 * with them.
578 *
579 * @param $elm String namespace and element
580 */
581 private function endElementModeQDesc( $elm ) {
582
583 if ( $elm === self::NS_RDF . ' value' ) {
584 list( $ns, $tag ) = explode( ' ', $this->curItem[0], 2 );
585 $this->saveValue( $ns, $tag, $this->charContent );
586 return;
587 } else {
588 array_shift( $this->mode );
589 array_shift( $this->curItem );
590 }
591
592
593 }
594
595 /**
596 * Handler for hitting a closing element.
597 *
598 * generally just calls a helper function depending on what
599 * mode we're in.
600 *
601 * Ignores the outer wrapping elements that are optional in
602 * xmp and have no meaning.
603 *
604 * @param $parser XMLParser
605 * @param $elm String namespace . ' ' . element name
606 */
607 function endElement( $parser, $elm ) {
608 if ( $elm === ( self::NS_RDF . ' RDF' )
609 || $elm === 'adobe:ns:meta/ xmpmeta'
610 || $elm === 'adobe:ns:meta/ xapmeta' )
611 {
612 // ignore these.
613 return;
614 }
615
616 if ( $elm === self::NS_RDF . ' type' ) {
617 // these aren't really supported properly yet.
618 // However, it appears they almost never used.
619 wfDebugLog( 'XMP', __METHOD__ . ' encountered <rdf:type>' );
620 }
621
622 if ( strpos( $elm, ' ' ) === false ) {
623 // This probably shouldn't happen.
624 // However, there is a bug in an adobe product
625 // that forgets the namespace on some things.
626 // (Luckily they are unimportant things).
627 wfDebugLog( 'XMP', __METHOD__ . " Encountered </$elm> which has no namespace. Skipping." );
628 return;
629 }
630
631 if ( count( $this->mode[0] ) === 0 ) {
632 // This should never ever happen and means
633 // there is a pretty major bug in this class.
634 throw new MWException( 'Encountered end element with no mode' );
635 }
636
637 if ( count( $this->curItem ) == 0 && $this->mode[0] !== self::MODE_INITIAL ) {
638 // just to be paranoid. Should always have a curItem, except for initially
639 // (aka during MODE_INITAL).
640 throw new MWException( "Hit end element </$elm> but no curItem" );
641 }
642
643 switch( $this->mode[0] ) {
644 case self::MODE_IGNORE:
645 $this->endElementModeIgnore( $elm );
646 break;
647 case self::MODE_SIMPLE:
648 $this->endElementModeSimple( $elm );
649 break;
650 case self::MODE_STRUCT:
651 case self::MODE_SEQ:
652 case self::MODE_BAG:
653 case self::MODE_LANG:
654 case self::MODE_BAGSTRUCT:
655 $this->endElementNested( $elm );
656 break;
657 case self::MODE_INITIAL:
658 if ( $elm === self::NS_RDF . ' Description' ) {
659 array_shift( $this->mode );
660 } else {
661 throw new MWException( 'Element ended unexpectedly while in MODE_INITIAL' );
662 }
663 break;
664 case self::MODE_LI:
665 case self::MODE_LI_LANG:
666 $this->endElementModeLi( $elm );
667 break;
668 case self::MODE_QDESC:
669 $this->endElementModeQDesc( $elm );
670 break;
671 default:
672 wfDebugLog( 'XMP', __METHOD__ . " no mode (elm = $elm)" );
673 break;
674 }
675 }
676
677 /**
678 * Hit an opening element while in MODE_IGNORE
679 *
680 * XMP is extensible, so ignore any tag we don't understand.
681 *
682 * Mostly ignores, unless we encounter the element that we are ignoring.
683 * in which case we add it to the item stack, so we can ignore things
684 * that are nested, correctly.
685 *
686 * @param $elm String namespace . ' ' . tag name
687 */
688 private function startElementModeIgnore( $elm ) {
689 if ( $elm === $this->curItem[0] ) {
690 array_unshift( $this->curItem, $elm );
691 array_unshift( $this->mode, self::MODE_IGNORE );
692 }
693 }
694
695 /**
696 * Start element in MODE_BAG (unordered array)
697 * this should always be <rdf:Bag>
698 *
699 * @param $elm String namespace . ' ' . tag
700 * @throws MWException if we have an element that's not <rdf:Bag>
701 */
702 private function startElementModeBag( $elm ) {
703 if ( $elm === self::NS_RDF . ' Bag' ) {
704 array_unshift( $this->mode, self::MODE_LI );
705 } else {
706 throw new MWException( "Expected <rdf:Bag> but got $elm." );
707 }
708
709 }
710
711 /**
712 * Start element in MODE_SEQ (ordered array)
713 * this should always be <rdf:Seq>
714 *
715 * @param $elm String namespace . ' ' . tag
716 * @throws MWException if we have an element that's not <rdf:Seq>
717 */
718 private function startElementModeSeq( $elm ) {
719 if ( $elm === self::NS_RDF . ' Seq' ) {
720 array_unshift( $this->mode, self::MODE_LI );
721 } elseif ( $elm === self::NS_RDF . ' Bag' ) {
722 # bug 27105
723 wfDebugLog( 'XMP', __METHOD__ . ' Expected an rdf:Seq, but got an rdf:Bag. Pretending'
724 . ' it is a Seq, since some buggy software is known to screw this up.' );
725 array_unshift( $this->mode, self::MODE_LI );
726 } else {
727 throw new MWException( "Expected <rdf:Seq> but got $elm." );
728 }
729
730 }
731
732 /**
733 * Start element in MODE_LANG (language alternative)
734 * this should always be <rdf:Alt>
735 *
736 * This tag tends to be used for metadata like describe this
737 * picture, which can be translated into multiple languages.
738 *
739 * XMP supports non-linguistic alternative selections,
740 * which are really only used for thumbnails, which
741 * we don't care about.
742 *
743 * @param $elm String namespace . ' ' . tag
744 * @throws MWException if we have an element that's not <rdf:Alt>
745 */
746 private function startElementModeLang( $elm ) {
747 if ( $elm === self::NS_RDF . ' Alt' ) {
748 array_unshift( $this->mode, self::MODE_LI_LANG );
749 } else {
750 throw new MWException( "Expected <rdf:Seq> but got $elm." );
751 }
752
753 }
754
755 /**
756 * Handle an opening element when in MODE_SIMPLE
757 *
758 * This should not happen often. This is for if a simple element
759 * already opened has a child element. Could happen for a
760 * qualified element.
761 *
762 * For example:
763 * <exif:DigitalZoomRatio><rdf:Description><rdf:value>0/10</rdf:value>
764 * <foo:someQualifier>Bar</foo:someQualifier> </rdf:Description>
765 * </exif:DigitalZoomRatio>
766 *
767 * This method is called when processing the <rdf:Description> element
768 *
769 * @param $elm String namespace and tag names separated by space.
770 * @param $attribs Array Attributes of the element.
771 */
772 private function startElementModeSimple( $elm, $attribs ) {
773 if ( $elm === self::NS_RDF . ' Description' ) {
774 // If this value has qualifiers
775 array_unshift( $this->mode, self::MODE_QDESC );
776 array_unshift( $this->curItem, $this->curItem[0] );
777
778 if ( isset( $attribs[self::NS_RDF . ' value'] ) ) {
779 list( $ns, $tag ) = explode( ' ', $this->curItem[0], 2 );
780 $this->saveValue( $ns, $tag, $attribs[self::NS_RDF . ' value'] );
781 }
782 } elseif ( $elm === self::NS_RDF . ' value' ) {
783 // This should not be here.
784 throw new MWException( __METHOD__ . ' Encountered <rdf:value> where it was unexpected.' );
785
786 } else {
787 // something else we don't recognize, like a qualifier maybe.
788 wfDebugLog( 'XMP', __METHOD__ . " Encountered element <$elm> where only expecting character data as value of " . $this->curItem[0] );
789 array_unshift( $this->mode, self::MODE_IGNORE );
790 array_unshift( $this->curItem, $elm );
791
792 }
793
794 }
795
796 /**
797 * Start an element when in MODE_QDESC.
798 * This generally happens when a simple element has an inner
799 * rdf:Description to hold qualifier elements.
800 *
801 * For example in:
802 * <exif:DigitalZoomRatio><rdf:Description><rdf:value>0/10</rdf:value>
803 * <foo:someQualifier>Bar</foo:someQualifier> </rdf:Description>
804 * </exif:DigitalZoomRatio>
805 * Called when processing the <rdf:value> or <foo:someQualifier>.
806 *
807 * @param $elm String namespace and tag name separated by a space.
808 *
809 */
810 private function startElementModeQDesc( $elm ) {
811 if ( $elm === self::NS_RDF . ' value' ) {
812 return; // do nothing
813 } else {
814 // otherwise its a qualifier, which we ignore
815 array_unshift( $this->mode, self::MODE_IGNORE );
816 array_unshift( $this->curItem, $elm );
817 }
818 }
819
820 /**
821 * Starting an element when in MODE_INITIAL
822 * This usually happens when we hit an element inside
823 * the outer rdf:Description
824 *
825 * This is generally where most properties start.
826 *
827 * @param $ns String Namespace
828 * @param $tag String tag name (without namespace prefix)
829 * @param $attribs Array array of attributes
830 */
831 private function startElementModeInitial( $ns, $tag, $attribs ) {
832 if ( $ns !== self::NS_RDF ) {
833
834 if ( isset( $this->items[$ns][$tag] ) ) {
835 if ( isset( $this->items[$ns][$tag]['structPart'] ) ) {
836 // If this element is supposed to appear only as
837 // a child of a structure, but appears here (not as
838 // a child of a struct), then something weird is
839 // happening, so ignore this element and its children.
840
841 wfDebugLog( 'XMP', "Encountered <$ns:$tag> outside"
842 . " of its expected parent. Ignoring." );
843
844 array_unshift( $this->mode, self::MODE_IGNORE );
845 array_unshift( $this->curItem, $ns . ' ' . $tag );
846 return;
847 }
848 $mode = $this->items[$ns][$tag]['mode'];
849 array_unshift( $this->mode, $mode );
850 array_unshift( $this->curItem, $ns . ' ' . $tag );
851 if ( $mode === self::MODE_STRUCT ) {
852 $this->ancestorStruct = isset( $this->items[$ns][$tag]['map_name'] )
853 ? $this->items[$ns][$tag]['map_name'] : $tag;
854 }
855 if ( $this->charContent !== false ) {
856 // Something weird.
857 // Should not happen in valid XMP.
858 throw new MWException( 'tag nested in non-whitespace characters.' );
859 }
860 } else {
861 // This element is not on our list of allowed elements so ignore.
862 wfDebugLog( 'XMP', __METHOD__ . " Ignoring unrecognized element <$ns:$tag>." );
863 array_unshift( $this->mode, self::MODE_IGNORE );
864 array_unshift( $this->curItem, $ns . ' ' . $tag );
865 return;
866 }
867
868 }
869 // process attributes
870 $this->doAttribs( $attribs );
871 }
872
873 /**
874 * Hit an opening element when in a Struct (MODE_STRUCT)
875 * This is generally for fields of a compound property.
876 *
877 * Example of a struct (abbreviated; flash has more properties):
878 *
879 * <exif:Flash> <rdf:Description> <exif:Fired>True</exif:Fired>
880 * <exif:Mode>1</exif:Mode></rdf:Description></exif:Flash>
881 *
882 * or:
883 *
884 * <exif:Flash rdf:parseType='Resource'> <exif:Fired>True</exif:Fired>
885 * <exif:Mode>1</exif:Mode></exif:Flash>
886 *
887 * @param $ns String namespace
888 * @param $tag String tag name (no ns)
889 * @param $attribs Array array of attribs w/ values.
890 */
891 private function startElementModeStruct( $ns, $tag, $attribs ) {
892 if ( $ns !== self::NS_RDF ) {
893
894 if ( isset( $this->items[$ns][$tag] ) ) {
895 if ( isset( $this->items[$ns][$this->ancestorStruct]['children'] )
896 && !isset( $this->items[$ns][$this->ancestorStruct]['children'][$tag] ) )
897 {
898 // This assumes that we don't have inter-namespace nesting
899 // which we don't in all the properties we're interested in.
900 throw new MWException( " <$tag> appeared nested in <" . $this->ancestorStruct
901 . "> where it is not allowed." );
902 }
903 array_unshift( $this->mode, $this->items[$ns][$tag]['mode'] );
904 array_unshift( $this->curItem, $ns . ' ' . $tag );
905 if ( $this->charContent !== false ) {
906 // Something weird.
907 // Should not happen in valid XMP.
908 throw new MWException( "tag <$tag> nested in non-whitespace characters (" . $this->charContent . ")." );
909 }
910 } else {
911 array_unshift( $this->mode, self::MODE_IGNORE );
912 array_unshift( $this->curItem, $elm );
913 return;
914 }
915
916 }
917
918 if ( $ns === self::NS_RDF && $tag === 'Description' ) {
919 $this->doAttribs( $attribs );
920 array_unshift( $this->mode, self::MODE_STRUCT );
921 array_unshift( $this->curItem, $this->curItem[0] );
922 }
923 }
924
925 /**
926 * opening element in MODE_LI
927 * process elements of arrays.
928 *
929 * Example:
930 * <exif:ISOSpeedRatings> <rdf:Seq> <rdf:li>64</rdf:li>
931 * </rdf:Seq> </exif:ISOSpeedRatings>
932 * This method is called when we hit the <rdf:li> element.
933 *
934 * @param $elm String: namespace . ' ' . tagname
935 * @param $attribs Array: Attributes. (needed for BAGSTRUCTS)
936 * @throws MWException if gets a tag other than <rdf:li>
937 */
938 private function startElementModeLi( $elm, $attribs ) {
939 if ( ( $elm ) !== self::NS_RDF . ' li' ) {
940 throw new MWException( "<rdf:li> expected but got $elm." );
941 }
942
943 if ( !isset( $this->mode[1] ) ) {
944 // This should never ever ever happen. Checking for it
945 // to be paranoid.
946 throw new MWException( 'In mode Li, but no 2xPrevious mode!' );
947 }
948
949 if ( $this->mode[1] === self::MODE_BAGSTRUCT ) {
950 // This list item contains a compound (STRUCT) value.
951 array_unshift( $this->mode, self::MODE_STRUCT );
952 array_unshift( $this->curItem, $elm );
953 $this->processingArray = true;
954
955 if ( !isset( $this->curItem[1] ) ) {
956 // be paranoid.
957 throw new MWException( 'Can not find parent of BAGSTRUCT.' );
958 }
959 list( $curNS, $curTag ) = explode( ' ', $this->curItem[1] );
960 $this->ancestorStruct = isset( $this->items[$curNS][$curTag]['map_name'] )
961 ? $this->items[$curNS][$curTag]['map_name'] : $curTag;
962
963 $this->doAttribs( $attribs );
964
965 } else {
966 // Normal BAG or SEQ containing simple values.
967 array_unshift( $this->mode, self::MODE_SIMPLE );
968 // need to add curItem[0] on again since one is for the specific item
969 // and one is for the entire group.
970 array_unshift( $this->curItem, $this->curItem[0] );
971 $this->processingArray = true;
972 }
973
974 }
975
976 /**
977 * Opening element in MODE_LI_LANG.
978 * process elements of language alternatives
979 *
980 * Example:
981 * <dc:title> <rdf:Alt> <rdf:li xml:lang="x-default">My house
982 * </rdf:li> </rdf:Alt> </dc:title>
983 *
984 * This method is called when we hit the <rdf:li> element.
985 *
986 * @param $elm String namespace . ' ' . tag
987 * @param $attribs array array of elements (most importantly xml:lang)
988 * @throws MWException if gets a tag other than <rdf:li> or if no xml:lang
989 */
990 private function startElementModeLiLang( $elm, $attribs ) {
991 if ( $elm !== self::NS_RDF . ' li' ) {
992 throw new MWException( __METHOD__ . " <rdf:li> expected but got $elm." );
993 }
994 if ( !isset( $attribs[ self::NS_XML . ' lang'] )
995 || !preg_match( '/^[-A-Za-z0-9]{2,}$/D', $attribs[ self::NS_XML . ' lang' ] ) )
996 {
997 throw new MWException( __METHOD__
998 . " <rdf:li> did not contain, or has invalid xml:lang attribute in lang alternative" );
999 }
1000
1001 // Lang is case-insensitive.
1002 $this->itemLang = strtolower( $attribs[ self::NS_XML . ' lang' ] );
1003
1004 // need to add curItem[0] on again since one is for the specific item
1005 // and one is for the entire group.
1006 array_unshift( $this->curItem, $this->curItem[0] );
1007 array_unshift( $this->mode, self::MODE_SIMPLE );
1008 $this->processingArray = true;
1009 }
1010
1011 /**
1012 * Hits an opening element.
1013 * Generally just calls a helper based on what MODE we're in.
1014 * Also does some initial set up for the wrapper element
1015 *
1016 * @param $parser XMLParser
1017 * @param $elm String namespace "<space>" element
1018 * @param $attribs Array attribute name => value
1019 */
1020 function startElement( $parser, $elm, $attribs ) {
1021
1022 if ( $elm === self::NS_RDF . ' RDF'
1023 || $elm === 'adobe:ns:meta/ xmpmeta'
1024 || $elm === 'adobe:ns:meta/ xapmeta')
1025 {
1026 /* ignore. */
1027 return;
1028 } elseif ( $elm === self::NS_RDF . ' Description' ) {
1029 if ( count( $this->mode ) === 0 ) {
1030 // outer rdf:desc
1031 array_unshift( $this->mode, self::MODE_INITIAL );
1032 }
1033 } elseif ( $elm === self::NS_RDF . ' type' ) {
1034 // This doesn't support rdf:type properly.
1035 // In practise I have yet to see a file that
1036 // uses this element, however it is mentioned
1037 // on page 25 of part 1 of the xmp standard.
1038 //
1039 // also it seems as if exiv2 and exiftool do not support
1040 // this either (That or I misunderstand the standard)
1041 wfDebugLog( 'XMP', __METHOD__ . ' Encountered <rdf:type> which isn\'t currently supported' );
1042 }
1043
1044 if ( strpos( $elm, ' ' ) === false ) {
1045 // This probably shouldn't happen.
1046 wfDebugLog( 'XMP', __METHOD__ . " Encountered <$elm> which has no namespace. Skipping." );
1047 return;
1048 }
1049
1050 list( $ns, $tag ) = explode( ' ', $elm, 2 );
1051
1052 if ( count( $this->mode ) === 0 ) {
1053 // This should not happen.
1054 throw new MWException('Error extracting XMP, '
1055 . "encountered <$elm> with no mode" );
1056 }
1057
1058 switch( $this->mode[0] ) {
1059 case self::MODE_IGNORE:
1060 $this->startElementModeIgnore( $elm );
1061 break;
1062 case self::MODE_SIMPLE:
1063 $this->startElementModeSimple( $elm, $attribs );
1064 break;
1065 case self::MODE_INITIAL:
1066 $this->startElementModeInitial( $ns, $tag, $attribs );
1067 break;
1068 case self::MODE_STRUCT:
1069 $this->startElementModeStruct( $ns, $tag, $attribs );
1070 break;
1071 case self::MODE_BAG:
1072 case self::MODE_BAGSTRUCT:
1073 $this->startElementModeBag( $elm );
1074 break;
1075 case self::MODE_SEQ:
1076 $this->startElementModeSeq( $elm );
1077 break;
1078 case self::MODE_LANG:
1079 $this->startElementModeLang( $elm );
1080 break;
1081 case self::MODE_LI_LANG:
1082 $this->startElementModeLiLang( $elm, $attribs );
1083 break;
1084 case self::MODE_LI:
1085 $this->startElementModeLi( $elm, $attribs );
1086 break;
1087 case self::MODE_QDESC:
1088 $this->startElementModeQDesc( $elm );
1089 break;
1090 default:
1091 throw new MWException( 'StartElement in unknown mode: ' . $this->mode[0] );
1092 break;
1093 }
1094 }
1095
1096 /**
1097 * Process attributes.
1098 * Simple values can be stored as either a tag or attribute
1099 *
1100 * Often the initial "<rdf:Description>" tag just has all the simple
1101 * properties as attributes.
1102 *
1103 * @par Example:
1104 * @code
1105 * <rdf:Description rdf:about="" xmlns:exif="http://ns.adobe.com/exif/1.0/" exif:DigitalZoomRatio="0/10">
1106 * @endcode
1107 *
1108 * @param $attribs Array attribute=>value array.
1109 */
1110 private function doAttribs( $attribs ) {
1111
1112 // first check for rdf:parseType attribute, as that can change
1113 // how the attributes are interperted.
1114
1115 if ( isset( $attribs[self::NS_RDF . ' parseType'] )
1116 && $attribs[self::NS_RDF . ' parseType'] === 'Resource'
1117 && $this->mode[0] === self::MODE_SIMPLE )
1118 {
1119 // this is equivalent to having an inner rdf:Description
1120 $this->mode[0] = self::MODE_QDESC;
1121 }
1122 foreach ( $attribs as $name => $val ) {
1123
1124
1125 if ( strpos( $name, ' ' ) === false ) {
1126 // This shouldn't happen, but so far some old software forgets namespace
1127 // on rdf:about.
1128 wfDebugLog( 'XMP', __METHOD__ . ' Encountered non-namespaced attribute: '
1129 . " $name=\"$val\". Skipping. " );
1130 continue;
1131 }
1132 list( $ns, $tag ) = explode( ' ', $name, 2 );
1133 if ( $ns === self::NS_RDF ) {
1134 if ( $tag === 'value' || $tag === 'resource' ) {
1135 // resource is for url.
1136 // value attribute is a weird way of just putting the contents.
1137 $this->char( $this->xmlParser, $val );
1138 }
1139 } elseif ( isset( $this->items[$ns][$tag] ) ) {
1140 if ( $this->mode[0] === self::MODE_SIMPLE ) {
1141 throw new MWException( __METHOD__
1142 . " $ns:$tag found as attribute where not allowed" );
1143 }
1144 $this->saveValue( $ns, $tag, $val );
1145 } else {
1146 wfDebugLog( 'XMP', __METHOD__ . " Ignoring unrecognized element <$ns:$tag>." );
1147 }
1148 }
1149 }
1150
1151 /**
1152 * Given an extracted value, save it to results array
1153 *
1154 * note also uses $this->ancestorStruct and
1155 * $this->processingArray to determine what name to
1156 * save the value under. (in addition to $tag).
1157 *
1158 * @param $ns String namespace of tag this is for
1159 * @param $tag String tag name
1160 * @param $val String value to save
1161 */
1162 private function saveValue( $ns, $tag, $val ) {
1163
1164 $info =& $this->items[$ns][$tag];
1165 $finalName = isset( $info['map_name'] )
1166 ? $info['map_name'] : $tag;
1167 if ( isset( $info['validate'] ) ) {
1168 $validate = is_array( $info['validate'] ) ? $info['validate']
1169 : array( 'XMPValidate', $info['validate'] );
1170
1171 if ( is_callable( $validate ) ) {
1172 call_user_func_array( $validate, array( $info, &$val, true ) );
1173 // the reasoning behind using &$val instead of using the return value
1174 // is to be consistent between here and validating structures.
1175 if ( is_null( $val ) ) {
1176 wfDebugLog( 'XMP', __METHOD__ . " <$ns:$tag> failed validation." );
1177 return;
1178 }
1179 } else {
1180 wfDebugLog( 'XMP', __METHOD__ . " Validation function for $finalName ("
1181 . $validate[0] . '::' . $validate[1] . '()) is not callable.' );
1182 }
1183 }
1184
1185 if ( $this->ancestorStruct && $this->processingArray ) {
1186 // Aka both an array and a struct. ( self::MODE_BAGSTRUCT )
1187 $this->results['xmp-' . $info['map_group']][$this->ancestorStruct][][$finalName] = $val;
1188 } elseif ( $this->ancestorStruct ) {
1189 $this->results['xmp-' . $info['map_group']][$this->ancestorStruct][$finalName] = $val;
1190 } elseif ( $this->processingArray ) {
1191 if ( $this->itemLang === false ) {
1192 // normal array
1193 $this->results['xmp-' . $info['map_group']][$finalName][] = $val;
1194 } else {
1195 // lang array.
1196 $this->results['xmp-' . $info['map_group']][$finalName][$this->itemLang] = $val;
1197 }
1198 } else {
1199 $this->results['xmp-' . $info['map_group']][$finalName] = $val;
1200 }
1201 }
1202 }