Merge "Add recentChangesLine to ChangesList"
[lhc/web/wiklou.git] / includes / media / FormatMetadata.php
1 <?php
2 /**
3 * Formatting of image metadata values into human readable form.
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 * @ingroup Media
21 * @author Ævar Arnfjörð Bjarmason <avarab@gmail.com>
22 * @copyright Copyright © 2005, Ævar Arnfjörð Bjarmason, 2009 Brent Garber, 2010 Brian Wolff
23 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
24 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 specification
25 * @file
26 */
27
28 /**
29 * Format Image metadata values into a human readable form.
30 *
31 * Note lots of these messages use the prefix 'exif' even though
32 * they may not be exif properties. For example 'exif-ImageDescription'
33 * can be the Exif ImageDescription, or it could be the iptc-iim caption
34 * property, or it could be the xmp dc:description property. This
35 * is because these messages should be independent of how the data is
36 * stored, sine the user doesn't care if the description is stored in xmp,
37 * exif, etc only that its a description. (Additionally many of these properties
38 * are merged together following the MWG standard, such that for example,
39 * exif properties override XMP properties that mean the same thing if
40 * there is a conflict).
41 *
42 * It should perhaps use a prefix like 'metadata' instead, but there
43 * is already a large number of messages using the 'exif' prefix.
44 *
45 * @ingroup Media
46 * @since 1.23 the class extends ContextSource and various formerly-public
47 * internal methods are private
48 */
49 class FormatMetadata extends ContextSource {
50 /**
51 * Only output a single language for multi-language fields
52 * @var bool
53 * @since 1.23
54 */
55 protected $singleLang = false;
56
57 /**
58 * Trigger only outputting single language for multilanguage fields
59 *
60 * @param bool $val
61 * @since 1.23
62 */
63 public function setSingleLanguage( $val ) {
64 $this->singleLang = $val;
65 }
66
67 /**
68 * Numbers given by Exif user agents are often magical, that is they
69 * should be replaced by a detailed explanation depending on their
70 * value which most of the time are plain integers. This function
71 * formats Exif (and other metadata) values into human readable form.
72 *
73 * This is the usual entry point for this class.
74 *
75 * @param array $tags The Exif data to format ( as returned by
76 * Exif::getFilteredData() or BitmapMetadataHandler )
77 * @param bool|IContextSource $context Context to use (optional)
78 * @return array
79 */
80 public static function getFormattedData( $tags, $context = false ) {
81 $obj = new FormatMetadata;
82 if ( $context ) {
83 $obj->setContext( $context );
84 }
85
86 return $obj->makeFormattedData( $tags );
87 }
88
89 /**
90 * Numbers given by Exif user agents are often magical, that is they
91 * should be replaced by a detailed explanation depending on their
92 * value which most of the time are plain integers. This function
93 * formats Exif (and other metadata) values into human readable form.
94 *
95 * @param array $tags The Exif data to format ( as returned by
96 * Exif::getFilteredData() or BitmapMetadataHandler )
97 * @return array
98 * @since 1.23
99 */
100 public function makeFormattedData( $tags ) {
101 $resolutionunit = !isset( $tags['ResolutionUnit'] ) || $tags['ResolutionUnit'] == 2 ? 2 : 3;
102 unset( $tags['ResolutionUnit'] );
103
104 foreach ( $tags as $tag => &$vals ) {
105
106 // This seems ugly to wrap non-array's in an array just to unwrap again,
107 // especially when most of the time it is not an array
108 if ( !is_array( $tags[$tag] ) ) {
109 $vals = array( $vals );
110 }
111
112 // _type is a special value to say what array type
113 if ( isset( $tags[$tag]['_type'] ) ) {
114 $type = $tags[$tag]['_type'];
115 unset( $vals['_type'] );
116 } else {
117 $type = 'ul'; // default unordered list.
118 }
119
120 // This is done differently as the tag is an array.
121 if ( $tag == 'GPSTimeStamp' && count( $vals ) === 3 ) {
122 // hour min sec array
123
124 $h = explode( '/', $vals[0] );
125 $m = explode( '/', $vals[1] );
126 $s = explode( '/', $vals[2] );
127
128 // this should already be validated
129 // when loaded from file, but it could
130 // come from a foreign repo, so be
131 // paranoid.
132 if ( !isset( $h[1] )
133 || !isset( $m[1] )
134 || !isset( $s[1] )
135 || $h[1] == 0
136 || $m[1] == 0
137 || $s[1] == 0
138 ) {
139 continue;
140 }
141 $tags[$tag] = str_pad( intval( $h[0] / $h[1] ), 2, '0', STR_PAD_LEFT )
142 . ':' . str_pad( intval( $m[0] / $m[1] ), 2, '0', STR_PAD_LEFT )
143 . ':' . str_pad( intval( $s[0] / $s[1] ), 2, '0', STR_PAD_LEFT );
144
145 try {
146 $time = wfTimestamp( TS_MW, '1971:01:01 ' . $tags[$tag] );
147 // the 1971:01:01 is just a placeholder, and not shown to user.
148 if ( $time && intval( $time ) > 0 ) {
149 $tags[$tag] = $this->getLanguage()->time( $time );
150 }
151 } catch ( TimestampException $e ) {
152 // This shouldn't happen, but we've seen bad formats
153 // such as 4-digit seconds in the wild.
154 // leave $tags[$tag] as-is
155 }
156 continue;
157 }
158
159 // The contact info is a multi-valued field
160 // instead of the other props which are single
161 // valued (mostly) so handle as a special case.
162 if ( $tag === 'Contact' ) {
163 $vals = $this->collapseContactInfo( $vals );
164 continue;
165 }
166
167 foreach ( $vals as &$val ) {
168
169 switch ( $tag ) {
170 case 'Compression':
171 switch ( $val ) {
172 case 1:
173 case 2:
174 case 3:
175 case 4:
176 case 5:
177 case 6:
178 case 7:
179 case 8:
180 case 32773:
181 case 32946:
182 case 34712:
183 $val = $this->exifMsg( $tag, $val );
184 break;
185 default:
186 /* If not recognized, display as is. */
187 break;
188 }
189 break;
190
191 case 'PhotometricInterpretation':
192 switch ( $val ) {
193 case 2:
194 case 6:
195 $val = $this->exifMsg( $tag, $val );
196 break;
197 default:
198 /* If not recognized, display as is. */
199 break;
200 }
201 break;
202
203 case 'Orientation':
204 switch ( $val ) {
205 case 1:
206 case 2:
207 case 3:
208 case 4:
209 case 5:
210 case 6:
211 case 7:
212 case 8:
213 $val = $this->exifMsg( $tag, $val );
214 break;
215 default:
216 /* If not recognized, display as is. */
217 break;
218 }
219 break;
220
221 case 'PlanarConfiguration':
222 switch ( $val ) {
223 case 1:
224 case 2:
225 $val = $this->exifMsg( $tag, $val );
226 break;
227 default:
228 /* If not recognized, display as is. */
229 break;
230 }
231 break;
232
233 // TODO: YCbCrSubSampling
234 case 'YCbCrPositioning':
235 switch ( $val ) {
236 case 1:
237 case 2:
238 $val = $this->exifMsg( $tag, $val );
239 break;
240 default:
241 /* If not recognized, display as is. */
242 break;
243 }
244 break;
245
246 case 'XResolution':
247 case 'YResolution':
248 switch ( $resolutionunit ) {
249 case 2:
250 $val = $this->exifMsg( 'XYResolution', 'i', $this->formatNum( $val ) );
251 break;
252 case 3:
253 $val = $this->exifMsg( 'XYResolution', 'c', $this->formatNum( $val ) );
254 break;
255 default:
256 /* If not recognized, display as is. */
257 break;
258 }
259 break;
260
261 // TODO: YCbCrCoefficients #p27 (see annex E)
262 case 'ExifVersion':
263 case 'FlashpixVersion':
264 $val = "$val" / 100;
265 break;
266
267 case 'ColorSpace':
268 switch ( $val ) {
269 case 1:
270 case 65535:
271 $val = $this->exifMsg( $tag, $val );
272 break;
273 default:
274 /* If not recognized, display as is. */
275 break;
276 }
277 break;
278
279 case 'ComponentsConfiguration':
280 switch ( $val ) {
281 case 0:
282 case 1:
283 case 2:
284 case 3:
285 case 4:
286 case 5:
287 case 6:
288 $val = $this->exifMsg( $tag, $val );
289 break;
290 default:
291 /* If not recognized, display as is. */
292 break;
293 }
294 break;
295
296 case 'DateTime':
297 case 'DateTimeOriginal':
298 case 'DateTimeDigitized':
299 case 'DateTimeReleased':
300 case 'DateTimeExpires':
301 case 'GPSDateStamp':
302 case 'dc-date':
303 case 'DateTimeMetadata':
304 if ( $val == '0000:00:00 00:00:00' || $val == ' : : : : ' ) {
305 $val = $this->msg( 'exif-unknowndate' )->text();
306 } elseif ( preg_match(
307 '/^(?:\d{4}):(?:\d\d):(?:\d\d) (?:\d\d):(?:\d\d):(?:\d\d)$/D',
308 $val
309 ) ) {
310 // Full date.
311 $time = wfTimestamp( TS_MW, $val );
312 if ( $time && intval( $time ) > 0 ) {
313 $val = $this->getLanguage()->timeanddate( $time );
314 }
315 } elseif ( preg_match( '/^(?:\d{4}):(?:\d\d):(?:\d\d) (?:\d\d):(?:\d\d)$/D', $val ) ) {
316 // No second field. Still format the same
317 // since timeanddate doesn't include seconds anyways,
318 // but second still available in api
319 $time = wfTimestamp( TS_MW, $val . ':00' );
320 if ( $time && intval( $time ) > 0 ) {
321 $val = $this->getLanguage()->timeanddate( $time );
322 }
323 } elseif ( preg_match( '/^(?:\d{4}):(?:\d\d):(?:\d\d)$/D', $val ) ) {
324 // If only the date but not the time is filled in.
325 $time = wfTimestamp( TS_MW, substr( $val, 0, 4 )
326 . substr( $val, 5, 2 )
327 . substr( $val, 8, 2 )
328 . '000000' );
329 if ( $time && intval( $time ) > 0 ) {
330 $val = $this->getLanguage()->date( $time );
331 }
332 }
333 // else it will just output $val without formatting it.
334 break;
335
336 case 'ExposureProgram':
337 switch ( $val ) {
338 case 0:
339 case 1:
340 case 2:
341 case 3:
342 case 4:
343 case 5:
344 case 6:
345 case 7:
346 case 8:
347 $val = $this->exifMsg( $tag, $val );
348 break;
349 default:
350 /* If not recognized, display as is. */
351 break;
352 }
353 break;
354
355 case 'SubjectDistance':
356 $val = $this->exifMsg( $tag, '', $this->formatNum( $val ) );
357 break;
358
359 case 'MeteringMode':
360 switch ( $val ) {
361 case 0:
362 case 1:
363 case 2:
364 case 3:
365 case 4:
366 case 5:
367 case 6:
368 case 7:
369 case 255:
370 $val = $this->exifMsg( $tag, $val );
371 break;
372 default:
373 /* If not recognized, display as is. */
374 break;
375 }
376 break;
377
378 case 'LightSource':
379 switch ( $val ) {
380 case 0:
381 case 1:
382 case 2:
383 case 3:
384 case 4:
385 case 9:
386 case 10:
387 case 11:
388 case 12:
389 case 13:
390 case 14:
391 case 15:
392 case 17:
393 case 18:
394 case 19:
395 case 20:
396 case 21:
397 case 22:
398 case 23:
399 case 24:
400 case 255:
401 $val = $this->exifMsg( $tag, $val );
402 break;
403 default:
404 /* If not recognized, display as is. */
405 break;
406 }
407 break;
408
409 case 'Flash':
410 $flashDecode = array(
411 'fired' => $val & bindec( '00000001' ),
412 'return' => ( $val & bindec( '00000110' ) ) >> 1,
413 'mode' => ( $val & bindec( '00011000' ) ) >> 3,
414 'function' => ( $val & bindec( '00100000' ) ) >> 5,
415 'redeye' => ( $val & bindec( '01000000' ) ) >> 6,
416 // 'reserved' => ($val & bindec( '10000000' )) >> 7,
417 );
418 $flashMsgs = array();
419 # We do not need to handle unknown values since all are used.
420 foreach ( $flashDecode as $subTag => $subValue ) {
421 # We do not need any message for zeroed values.
422 if ( $subTag != 'fired' && $subValue == 0 ) {
423 continue;
424 }
425 $fullTag = $tag . '-' . $subTag;
426 $flashMsgs[] = $this->exifMsg( $fullTag, $subValue );
427 }
428 $val = $this->getLanguage()->commaList( $flashMsgs );
429 break;
430
431 case 'FocalPlaneResolutionUnit':
432 switch ( $val ) {
433 case 2:
434 $val = $this->exifMsg( $tag, $val );
435 break;
436 default:
437 /* If not recognized, display as is. */
438 break;
439 }
440 break;
441
442 case 'SensingMethod':
443 switch ( $val ) {
444 case 1:
445 case 2:
446 case 3:
447 case 4:
448 case 5:
449 case 7:
450 case 8:
451 $val = $this->exifMsg( $tag, $val );
452 break;
453 default:
454 /* If not recognized, display as is. */
455 break;
456 }
457 break;
458
459 case 'FileSource':
460 switch ( $val ) {
461 case 3:
462 $val = $this->exifMsg( $tag, $val );
463 break;
464 default:
465 /* If not recognized, display as is. */
466 break;
467 }
468 break;
469
470 case 'SceneType':
471 switch ( $val ) {
472 case 1:
473 $val = $this->exifMsg( $tag, $val );
474 break;
475 default:
476 /* If not recognized, display as is. */
477 break;
478 }
479 break;
480
481 case 'CustomRendered':
482 switch ( $val ) {
483 case 0:
484 case 1:
485 $val = $this->exifMsg( $tag, $val );
486 break;
487 default:
488 /* If not recognized, display as is. */
489 break;
490 }
491 break;
492
493 case 'ExposureMode':
494 switch ( $val ) {
495 case 0:
496 case 1:
497 case 2:
498 $val = $this->exifMsg( $tag, $val );
499 break;
500 default:
501 /* If not recognized, display as is. */
502 break;
503 }
504 break;
505
506 case 'WhiteBalance':
507 switch ( $val ) {
508 case 0:
509 case 1:
510 $val = $this->exifMsg( $tag, $val );
511 break;
512 default:
513 /* If not recognized, display as is. */
514 break;
515 }
516 break;
517
518 case 'SceneCaptureType':
519 switch ( $val ) {
520 case 0:
521 case 1:
522 case 2:
523 case 3:
524 $val = $this->exifMsg( $tag, $val );
525 break;
526 default:
527 /* If not recognized, display as is. */
528 break;
529 }
530 break;
531
532 case 'GainControl':
533 switch ( $val ) {
534 case 0:
535 case 1:
536 case 2:
537 case 3:
538 case 4:
539 $val = $this->exifMsg( $tag, $val );
540 break;
541 default:
542 /* If not recognized, display as is. */
543 break;
544 }
545 break;
546
547 case 'Contrast':
548 switch ( $val ) {
549 case 0:
550 case 1:
551 case 2:
552 $val = $this->exifMsg( $tag, $val );
553 break;
554 default:
555 /* If not recognized, display as is. */
556 break;
557 }
558 break;
559
560 case 'Saturation':
561 switch ( $val ) {
562 case 0:
563 case 1:
564 case 2:
565 $val = $this->exifMsg( $tag, $val );
566 break;
567 default:
568 /* If not recognized, display as is. */
569 break;
570 }
571 break;
572
573 case 'Sharpness':
574 switch ( $val ) {
575 case 0:
576 case 1:
577 case 2:
578 $val = $this->exifMsg( $tag, $val );
579 break;
580 default:
581 /* If not recognized, display as is. */
582 break;
583 }
584 break;
585
586 case 'SubjectDistanceRange':
587 switch ( $val ) {
588 case 0:
589 case 1:
590 case 2:
591 case 3:
592 $val = $this->exifMsg( $tag, $val );
593 break;
594 default:
595 /* If not recognized, display as is. */
596 break;
597 }
598 break;
599
600 // The GPS...Ref values are kept for compatibility, probably won't be reached.
601 case 'GPSLatitudeRef':
602 case 'GPSDestLatitudeRef':
603 switch ( $val ) {
604 case 'N':
605 case 'S':
606 $val = $this->exifMsg( 'GPSLatitude', $val );
607 break;
608 default:
609 /* If not recognized, display as is. */
610 break;
611 }
612 break;
613
614 case 'GPSLongitudeRef':
615 case 'GPSDestLongitudeRef':
616 switch ( $val ) {
617 case 'E':
618 case 'W':
619 $val = $this->exifMsg( 'GPSLongitude', $val );
620 break;
621 default:
622 /* If not recognized, display as is. */
623 break;
624 }
625 break;
626
627 case 'GPSAltitude':
628 if ( $val < 0 ) {
629 $val = $this->exifMsg( 'GPSAltitude', 'below-sealevel', $this->formatNum( -$val, 3 ) );
630 } else {
631 $val = $this->exifMsg( 'GPSAltitude', 'above-sealevel', $this->formatNum( $val, 3 ) );
632 }
633 break;
634
635 case 'GPSStatus':
636 switch ( $val ) {
637 case 'A':
638 case 'V':
639 $val = $this->exifMsg( $tag, $val );
640 break;
641 default:
642 /* If not recognized, display as is. */
643 break;
644 }
645 break;
646
647 case 'GPSMeasureMode':
648 switch ( $val ) {
649 case 2:
650 case 3:
651 $val = $this->exifMsg( $tag, $val );
652 break;
653 default:
654 /* If not recognized, display as is. */
655 break;
656 }
657 break;
658
659 case 'GPSTrackRef':
660 case 'GPSImgDirectionRef':
661 case 'GPSDestBearingRef':
662 switch ( $val ) {
663 case 'T':
664 case 'M':
665 $val = $this->exifMsg( 'GPSDirection', $val );
666 break;
667 default:
668 /* If not recognized, display as is. */
669 break;
670 }
671 break;
672
673 case 'GPSLatitude':
674 case 'GPSDestLatitude':
675 $val = $this->formatCoords( $val, 'latitude' );
676 break;
677 case 'GPSLongitude':
678 case 'GPSDestLongitude':
679 $val = $this->formatCoords( $val, 'longitude' );
680 break;
681
682 case 'GPSSpeedRef':
683 switch ( $val ) {
684 case 'K':
685 case 'M':
686 case 'N':
687 $val = $this->exifMsg( 'GPSSpeed', $val );
688 break;
689 default:
690 /* If not recognized, display as is. */
691 break;
692 }
693 break;
694
695 case 'GPSDestDistanceRef':
696 switch ( $val ) {
697 case 'K':
698 case 'M':
699 case 'N':
700 $val = $this->exifMsg( 'GPSDestDistance', $val );
701 break;
702 default:
703 /* If not recognized, display as is. */
704 break;
705 }
706 break;
707
708 case 'GPSDOP':
709 // See https://en.wikipedia.org/wiki/Dilution_of_precision_(GPS)
710 if ( $val <= 2 ) {
711 $val = $this->exifMsg( $tag, 'excellent', $this->formatNum( $val ) );
712 } elseif ( $val <= 5 ) {
713 $val = $this->exifMsg( $tag, 'good', $this->formatNum( $val ) );
714 } elseif ( $val <= 10 ) {
715 $val = $this->exifMsg( $tag, 'moderate', $this->formatNum( $val ) );
716 } elseif ( $val <= 20 ) {
717 $val = $this->exifMsg( $tag, 'fair', $this->formatNum( $val ) );
718 } else {
719 $val = $this->exifMsg( $tag, 'poor', $this->formatNum( $val ) );
720 }
721 break;
722
723 // This is not in the Exif standard, just a special
724 // case for our purposes which enables wikis to wikify
725 // the make, model and software name to link to their articles.
726 case 'Make':
727 case 'Model':
728 $val = $this->exifMsg( $tag, '', $val );
729 break;
730
731 case 'Software':
732 if ( is_array( $val ) ) {
733 // if its a software, version array.
734 $val = $this->msg( 'exif-software-version-value', $val[0], $val[1] )->text();
735 } else {
736 $val = $this->exifMsg( $tag, '', $val );
737 }
738 break;
739
740 case 'ExposureTime':
741 // Show the pretty fraction as well as decimal version
742 $val = $this->msg( 'exif-exposuretime-format',
743 $this->formatFraction( $val ), $this->formatNum( $val ) )->text();
744 break;
745 case 'ISOSpeedRatings':
746 // If its = 65535 that means its at the
747 // limit of the size of Exif::short and
748 // is really higher.
749 if ( $val == '65535' ) {
750 $val = $this->exifMsg( $tag, 'overflow' );
751 } else {
752 $val = $this->formatNum( $val );
753 }
754 break;
755 case 'FNumber':
756 $val = $this->msg( 'exif-fnumber-format',
757 $this->formatNum( $val ) )->text();
758 break;
759
760 case 'FocalLength':
761 case 'FocalLengthIn35mmFilm':
762 $val = $this->msg( 'exif-focallength-format',
763 $this->formatNum( $val ) )->text();
764 break;
765
766 case 'MaxApertureValue':
767 if ( strpos( $val, '/' ) !== false ) {
768 // need to expand this earlier to calculate fNumber
769 list( $n, $d ) = explode( '/', $val );
770 if ( is_numeric( $n ) && is_numeric( $d ) ) {
771 $val = $n / $d;
772 }
773 }
774 if ( is_numeric( $val ) ) {
775 $fNumber = pow( 2, $val / 2 );
776 if ( $fNumber !== false ) {
777 $val = $this->msg( 'exif-maxaperturevalue-value',
778 $this->formatNum( $val ),
779 $this->formatNum( $fNumber, 2 )
780 )->text();
781 }
782 }
783 break;
784
785 case 'iimCategory':
786 switch ( strtolower( $val ) ) {
787 // See pg 29 of IPTC photo
788 // metadata standard.
789 case 'ace':
790 case 'clj':
791 case 'dis':
792 case 'fin':
793 case 'edu':
794 case 'evn':
795 case 'hth':
796 case 'hum':
797 case 'lab':
798 case 'lif':
799 case 'pol':
800 case 'rel':
801 case 'sci':
802 case 'soi':
803 case 'spo':
804 case 'war':
805 case 'wea':
806 $val = $this->exifMsg(
807 'iimcategory',
808 $val
809 );
810 }
811 break;
812 case 'SubjectNewsCode':
813 // Essentially like iimCategory.
814 // 8 (numeric) digit hierarchical
815 // classification. We decode the
816 // first 2 digits, which provide
817 // a broad category.
818 $val = $this->convertNewsCode( $val );
819 break;
820 case 'Urgency':
821 // 1-8 with 1 being highest, 5 normal
822 // 0 is reserved, and 9 is 'user-defined'.
823 $urgency = '';
824 if ( $val == 0 || $val == 9 ) {
825 $urgency = 'other';
826 } elseif ( $val < 5 && $val > 1 ) {
827 $urgency = 'high';
828 } elseif ( $val == 5 ) {
829 $urgency = 'normal';
830 } elseif ( $val <= 8 && $val > 5 ) {
831 $urgency = 'low';
832 }
833
834 if ( $urgency !== '' ) {
835 $val = $this->exifMsg( 'urgency',
836 $urgency, $val
837 );
838 }
839 break;
840
841 // Things that have a unit of pixels.
842 case 'OriginalImageHeight':
843 case 'OriginalImageWidth':
844 case 'PixelXDimension':
845 case 'PixelYDimension':
846 case 'ImageWidth':
847 case 'ImageLength':
848 $val = $this->formatNum( $val ) . ' ' . $this->msg( 'unit-pixel' )->text();
849 break;
850
851 // Do not transform fields with pure text.
852 // For some languages the formatNum()
853 // conversion results to wrong output like
854 // foo,bar@example,com or foo٫bar@example٫com.
855 // Also some 'numeric' things like Scene codes
856 // are included here as we really don't want
857 // commas inserted.
858 case 'ImageDescription':
859 case 'Artist':
860 case 'Copyright':
861 case 'RelatedSoundFile':
862 case 'ImageUniqueID':
863 case 'SpectralSensitivity':
864 case 'GPSSatellites':
865 case 'GPSVersionID':
866 case 'GPSMapDatum':
867 case 'Keywords':
868 case 'WorldRegionDest':
869 case 'CountryDest':
870 case 'CountryCodeDest':
871 case 'ProvinceOrStateDest':
872 case 'CityDest':
873 case 'SublocationDest':
874 case 'WorldRegionCreated':
875 case 'CountryCreated':
876 case 'CountryCodeCreated':
877 case 'ProvinceOrStateCreated':
878 case 'CityCreated':
879 case 'SublocationCreated':
880 case 'ObjectName':
881 case 'SpecialInstructions':
882 case 'Headline':
883 case 'Credit':
884 case 'Source':
885 case 'EditStatus':
886 case 'FixtureIdentifier':
887 case 'LocationDest':
888 case 'LocationDestCode':
889 case 'Writer':
890 case 'JPEGFileComment':
891 case 'iimSupplementalCategory':
892 case 'OriginalTransmissionRef':
893 case 'Identifier':
894 case 'dc-contributor':
895 case 'dc-coverage':
896 case 'dc-publisher':
897 case 'dc-relation':
898 case 'dc-rights':
899 case 'dc-source':
900 case 'dc-type':
901 case 'Lens':
902 case 'SerialNumber':
903 case 'CameraOwnerName':
904 case 'Label':
905 case 'Nickname':
906 case 'RightsCertificate':
907 case 'CopyrightOwner':
908 case 'UsageTerms':
909 case 'WebStatement':
910 case 'OriginalDocumentID':
911 case 'LicenseUrl':
912 case 'MorePermissionsUrl':
913 case 'AttributionUrl':
914 case 'PreferredAttributionName':
915 case 'PNGFileComment':
916 case 'Disclaimer':
917 case 'ContentWarning':
918 case 'GIFFileComment':
919 case 'SceneCode':
920 case 'IntellectualGenre':
921 case 'Event':
922 case 'OrginisationInImage':
923 case 'PersonInImage':
924
925 $val = htmlspecialchars( $val );
926 break;
927
928 case 'ObjectCycle':
929 switch ( $val ) {
930 case 'a':
931 case 'p':
932 case 'b':
933 $val = $this->exifMsg( $tag, $val );
934 break;
935 default:
936 $val = htmlspecialchars( $val );
937 break;
938 }
939 break;
940 case 'Copyrighted':
941 switch ( $val ) {
942 case 'True':
943 case 'False':
944 $val = $this->exifMsg( $tag, $val );
945 break;
946 }
947 break;
948 case 'Rating':
949 if ( $val == '-1' ) {
950 $val = $this->exifMsg( $tag, 'rejected' );
951 } else {
952 $val = $this->formatNum( $val );
953 }
954 break;
955
956 case 'LanguageCode':
957 $lang = Language::fetchLanguageName( strtolower( $val ), $this->getLanguage()->getCode() );
958 if ( $lang ) {
959 $val = htmlspecialchars( $lang );
960 } else {
961 $val = htmlspecialchars( $val );
962 }
963 break;
964
965 default:
966 $val = $this->formatNum( $val );
967 break;
968 }
969 }
970 // End formatting values, start flattening arrays.
971 $vals = $this->flattenArrayReal( $vals, $type );
972 }
973
974 return $tags;
975 }
976
977 /**
978 * Flatten an array, using the content language for any messages.
979 *
980 * @param array $vals Array of values
981 * @param string $type Type of array (either lang, ul, ol).
982 * lang = language assoc array with keys being the lang code
983 * ul = unordered list, ol = ordered list
984 * type can also come from the '_type' member of $vals.
985 * @param bool $noHtml If to avoid returning anything resembling HTML.
986 * (Ugly hack for backwards compatibility with old MediaWiki).
987 * @param bool|IContextSource $context
988 * @return string Single value (in wiki-syntax).
989 * @since 1.23
990 */
991 public static function flattenArrayContentLang( $vals, $type = 'ul',
992 $noHtml = false, $context = false
993 ) {
994 global $wgContLang;
995 $obj = new FormatMetadata;
996 if ( $context ) {
997 $obj->setContext( $context );
998 }
999 $context = new DerivativeContext( $obj->getContext() );
1000 $context->setLanguage( $wgContLang );
1001 $obj->setContext( $context );
1002
1003 return $obj->flattenArrayReal( $vals, $type, $noHtml );
1004 }
1005
1006 /**
1007 * A function to collapse multivalued tags into a single value.
1008 * This turns an array of (for example) authors into a bulleted list.
1009 *
1010 * This is public on the basis it might be useful outside of this class.
1011 *
1012 * @param array $vals Array of values
1013 * @param string $type Type of array (either lang, ul, ol).
1014 * lang = language assoc array with keys being the lang code
1015 * ul = unordered list, ol = ordered list
1016 * type can also come from the '_type' member of $vals.
1017 * @param bool $noHtml If to avoid returning anything resembling HTML.
1018 * (Ugly hack for backwards compatibility with old mediawiki).
1019 * @return string Single value (in wiki-syntax).
1020 * @since 1.23
1021 */
1022 public function flattenArrayReal( $vals, $type = 'ul', $noHtml = false ) {
1023 if ( !is_array( $vals ) ) {
1024 return $vals; // do nothing if not an array;
1025 }
1026
1027 if ( isset( $vals['_type'] ) ) {
1028 $type = $vals['_type'];
1029 unset( $vals['_type'] );
1030 }
1031
1032 if ( !is_array( $vals ) ) {
1033 return $vals; // do nothing if not an array;
1034 } elseif ( count( $vals ) === 1 && $type !== 'lang' ) {
1035 return $vals[0];
1036 } elseif ( count( $vals ) === 0 ) {
1037 wfDebug( __METHOD__ . " metadata array with 0 elements!\n" );
1038
1039 return ""; // paranoia. This should never happen
1040 } else {
1041 /* @todo FIXME: This should hide some of the list entries if there are
1042 * say more than four. Especially if a field is translated into 20
1043 * languages, we don't want to show them all by default
1044 */
1045 switch ( $type ) {
1046 case 'lang':
1047 // Display default, followed by ContLang,
1048 // followed by the rest in no particular
1049 // order.
1050
1051 // Todo: hide some items if really long list.
1052
1053 $content = '';
1054
1055 $priorityLanguages = $this->getPriorityLanguages();
1056 $defaultItem = false;
1057 $defaultLang = false;
1058
1059 // If default is set, save it for later,
1060 // as we don't know if it's equal to
1061 // one of the lang codes. (In xmp
1062 // you specify the language for a
1063 // default property by having both
1064 // a default prop, and one in the language
1065 // that are identical)
1066 if ( isset( $vals['x-default'] ) ) {
1067 $defaultItem = $vals['x-default'];
1068 unset( $vals['x-default'] );
1069 }
1070 foreach ( $priorityLanguages as $pLang ) {
1071 if ( isset( $vals[$pLang] ) ) {
1072 $isDefault = false;
1073 if ( $vals[$pLang] === $defaultItem ) {
1074 $defaultItem = false;
1075 $isDefault = true;
1076 }
1077 $content .= $this->langItem(
1078 $vals[$pLang], $pLang,
1079 $isDefault, $noHtml );
1080
1081 unset( $vals[$pLang] );
1082
1083 if ( $this->singleLang ) {
1084 return Html::rawElement( 'span',
1085 array( 'lang' => $pLang ), $vals[$pLang] );
1086 }
1087 }
1088 }
1089
1090 // Now do the rest.
1091 foreach ( $vals as $lang => $item ) {
1092 if ( $item === $defaultItem ) {
1093 $defaultLang = $lang;
1094 continue;
1095 }
1096 $content .= $this->langItem( $item,
1097 $lang, false, $noHtml );
1098 if ( $this->singleLang ) {
1099 return Html::rawElement( 'span',
1100 array( 'lang' => $lang ), $item );
1101 }
1102 }
1103 if ( $defaultItem !== false ) {
1104 $content = $this->langItem( $defaultItem,
1105 $defaultLang, true, $noHtml ) .
1106 $content;
1107 if ( $this->singleLang ) {
1108 return $defaultItem;
1109 }
1110 }
1111 if ( $noHtml ) {
1112 return $content;
1113 }
1114
1115 return '<ul class="metadata-langlist">' .
1116 $content .
1117 '</ul>';
1118 case 'ol':
1119 if ( $noHtml ) {
1120 return "\n#" . implode( "\n#", $vals );
1121 }
1122
1123 return "<ol><li>" . implode( "</li>\n<li>", $vals ) . '</li></ol>';
1124 case 'ul':
1125 default:
1126 if ( $noHtml ) {
1127 return "\n*" . implode( "\n*", $vals );
1128 }
1129
1130 return "<ul><li>" . implode( "</li>\n<li>", $vals ) . '</li></ul>';
1131 }
1132 }
1133 }
1134
1135 /** Helper function for creating lists of translations.
1136 *
1137 * @param string $value Value (this is not escaped)
1138 * @param string $lang Lang code of item or false
1139 * @param bool $default If it is default value.
1140 * @param bool $noHtml If to avoid html (for back-compat)
1141 * @throws MWException
1142 * @return string Language item (Note: despite how this looks, this is
1143 * treated as wikitext, not as HTML).
1144 */
1145 private function langItem( $value, $lang, $default = false, $noHtml = false ) {
1146 if ( $lang === false && $default === false ) {
1147 throw new MWException( '$lang and $default cannot both '
1148 . 'be false.' );
1149 }
1150
1151 if ( $noHtml ) {
1152 $wrappedValue = $value;
1153 } else {
1154 $wrappedValue = '<span class="mw-metadata-lang-value">'
1155 . $value . '</span>';
1156 }
1157
1158 if ( $lang === false ) {
1159 $msg = $this->msg( 'metadata-langitem-default', $wrappedValue );
1160 if ( $noHtml ) {
1161 return $msg->text() . "\n\n";
1162 } /* else */
1163
1164 return '<li class="mw-metadata-lang-default">'
1165 . $msg->text()
1166 . "</li>\n";
1167 }
1168
1169 $lowLang = strtolower( $lang );
1170 $langName = Language::fetchLanguageName( $lowLang );
1171 if ( $langName === '' ) {
1172 // try just the base language name. (aka en-US -> en ).
1173 list( $langPrefix ) = explode( '-', $lowLang, 2 );
1174 $langName = Language::fetchLanguageName( $langPrefix );
1175 if ( $langName === '' ) {
1176 // give up.
1177 $langName = $lang;
1178 }
1179 }
1180 // else we have a language specified
1181
1182 $msg = $this->msg( 'metadata-langitem', $wrappedValue, $langName, $lang );
1183 if ( $noHtml ) {
1184 return '*' . $msg->text();
1185 } /* else: */
1186
1187 $item = '<li class="mw-metadata-lang-code-'
1188 . $lang;
1189 if ( $default ) {
1190 $item .= ' mw-metadata-lang-default';
1191 }
1192 $item .= '" lang="' . $lang . '">';
1193 $item .= $msg->text();
1194 $item .= "</li>\n";
1195
1196 return $item;
1197 }
1198
1199 /**
1200 * Convenience function for getFormattedData()
1201 *
1202 * @param string $tag The tag name to pass on
1203 * @param string $val The value of the tag
1204 * @param string $arg An argument to pass ($1)
1205 * @param string $arg2 A 2nd argument to pass ($2)
1206 * @return string The text content of "exif-$tag-$val" message in lower case
1207 */
1208 private function exifMsg( $tag, $val, $arg = null, $arg2 = null ) {
1209 global $wgContLang;
1210
1211 if ( $val === '' ) {
1212 $val = 'value';
1213 }
1214
1215 return $this->msg( $wgContLang->lc( "exif-$tag-$val" ), $arg, $arg2 )->text();
1216 }
1217
1218 /**
1219 * Format a number, convert numbers from fractions into floating point
1220 * numbers, joins arrays of numbers with commas.
1221 *
1222 * @param mixed $num The value to format
1223 * @param float|int|bool $round Digits to round to or false.
1224 * @return mixed A floating point number or whatever we were fed
1225 */
1226 private function formatNum( $num, $round = false ) {
1227 $m = array();
1228 if ( is_array( $num ) ) {
1229 $out = array();
1230 foreach ( $num as $number ) {
1231 $out[] = $this->formatNum( $number );
1232 }
1233
1234 return $this->getLanguage()->commaList( $out );
1235 }
1236 if ( preg_match( '/^(-?\d+)\/(\d+)$/', $num, $m ) ) {
1237 if ( $m[2] != 0 ) {
1238 $newNum = $m[1] / $m[2];
1239 if ( $round !== false ) {
1240 $newNum = round( $newNum, $round );
1241 }
1242 } else {
1243 $newNum = $num;
1244 }
1245
1246 return $this->getLanguage()->formatNum( $newNum );
1247 } else {
1248 if ( is_numeric( $num ) && $round !== false ) {
1249 $num = round( $num, $round );
1250 }
1251
1252 return $this->getLanguage()->formatNum( $num );
1253 }
1254 }
1255
1256 /**
1257 * Format a rational number, reducing fractions
1258 *
1259 * @param mixed $num The value to format
1260 * @return mixed A floating point number or whatever we were fed
1261 */
1262 private function formatFraction( $num ) {
1263 $m = array();
1264 if ( preg_match( '/^(-?\d+)\/(\d+)$/', $num, $m ) ) {
1265 $numerator = intval( $m[1] );
1266 $denominator = intval( $m[2] );
1267 $gcd = $this->gcd( abs( $numerator ), $denominator );
1268 if ( $gcd != 0 ) {
1269 // 0 shouldn't happen! ;)
1270 return $this->formatNum( $numerator / $gcd ) . '/' . $this->formatNum( $denominator / $gcd );
1271 }
1272 }
1273
1274 return $this->formatNum( $num );
1275 }
1276
1277 /**
1278 * Calculate the greatest common divisor of two integers.
1279 *
1280 * @param int $a Numerator
1281 * @param int $b Denominator
1282 * @return int
1283 */
1284 private function gcd( $a, $b ) {
1285 /*
1286 // https://en.wikipedia.org/wiki/Euclidean_algorithm
1287 // Recursive form would be:
1288 if( $b == 0 )
1289 return $a;
1290 else
1291 return gcd( $b, $a % $b );
1292 */
1293 while ( $b != 0 ) {
1294 $remainder = $a % $b;
1295
1296 // tail recursion...
1297 $a = $b;
1298 $b = $remainder;
1299 }
1300
1301 return $a;
1302 }
1303
1304 /**
1305 * Fetch the human readable version of a news code.
1306 * A news code is an 8 digit code. The first two
1307 * digits are a general classification, so we just
1308 * translate that.
1309 *
1310 * Note, leading 0's are significant, so this is
1311 * a string, not an int.
1312 *
1313 * @param string $val The 8 digit news code.
1314 * @return string The human readable form
1315 */
1316 private function convertNewsCode( $val ) {
1317 if ( !preg_match( '/^\d{8}$/D', $val ) ) {
1318 // Not a valid news code.
1319 return $val;
1320 }
1321 $cat = '';
1322 switch ( substr( $val, 0, 2 ) ) {
1323 case '01':
1324 $cat = 'ace';
1325 break;
1326 case '02':
1327 $cat = 'clj';
1328 break;
1329 case '03':
1330 $cat = 'dis';
1331 break;
1332 case '04':
1333 $cat = 'fin';
1334 break;
1335 case '05':
1336 $cat = 'edu';
1337 break;
1338 case '06':
1339 $cat = 'evn';
1340 break;
1341 case '07':
1342 $cat = 'hth';
1343 break;
1344 case '08':
1345 $cat = 'hum';
1346 break;
1347 case '09':
1348 $cat = 'lab';
1349 break;
1350 case '10':
1351 $cat = 'lif';
1352 break;
1353 case '11':
1354 $cat = 'pol';
1355 break;
1356 case '12':
1357 $cat = 'rel';
1358 break;
1359 case '13':
1360 $cat = 'sci';
1361 break;
1362 case '14':
1363 $cat = 'soi';
1364 break;
1365 case '15':
1366 $cat = 'spo';
1367 break;
1368 case '16':
1369 $cat = 'war';
1370 break;
1371 case '17':
1372 $cat = 'wea';
1373 break;
1374 }
1375 if ( $cat !== '' ) {
1376 $catMsg = $this->exifMsg( 'iimcategory', $cat );
1377 $val = $this->exifMsg( 'subjectnewscode', '', $val, $catMsg );
1378 }
1379
1380 return $val;
1381 }
1382
1383 /**
1384 * Format a coordinate value, convert numbers from floating point
1385 * into degree minute second representation.
1386 *
1387 * @param int $coord Degrees, minutes and seconds
1388 * @param string $type Latitude or longitude (for if its a NWS or E)
1389 * @return mixed A floating point number or whatever we were fed
1390 */
1391 private function formatCoords( $coord, $type ) {
1392 $ref = '';
1393 if ( $coord < 0 ) {
1394 $nCoord = -$coord;
1395 if ( $type === 'latitude' ) {
1396 $ref = 'S';
1397 } elseif ( $type === 'longitude' ) {
1398 $ref = 'W';
1399 }
1400 } else {
1401 $nCoord = $coord;
1402 if ( $type === 'latitude' ) {
1403 $ref = 'N';
1404 } elseif ( $type === 'longitude' ) {
1405 $ref = 'E';
1406 }
1407 }
1408
1409 $deg = floor( $nCoord );
1410 $min = floor( ( $nCoord - $deg ) * 60.0 );
1411 $sec = round( ( ( $nCoord - $deg ) - $min / 60 ) * 3600, 2 );
1412
1413 $deg = $this->formatNum( $deg );
1414 $min = $this->formatNum( $min );
1415 $sec = $this->formatNum( $sec );
1416
1417 return $this->msg( 'exif-coordinate-format', $deg, $min, $sec, $ref, $coord )->text();
1418 }
1419
1420 /**
1421 * Format the contact info field into a single value.
1422 *
1423 * This function might be called from
1424 * JpegHandler::convertMetadataVersion which is why it is
1425 * public.
1426 *
1427 * @param array $vals Array with fields of the ContactInfo
1428 * struct defined in the IPTC4XMP spec. Or potentially
1429 * an array with one element that is a free form text
1430 * value from the older iptc iim 1:118 prop.
1431 * @return string HTML-ish looking wikitext
1432 * @since 1.23 no longer static
1433 */
1434 public function collapseContactInfo( $vals ) {
1435 if ( !( isset( $vals['CiAdrExtadr'] )
1436 || isset( $vals['CiAdrCity'] )
1437 || isset( $vals['CiAdrCtry'] )
1438 || isset( $vals['CiEmailWork'] )
1439 || isset( $vals['CiTelWork'] )
1440 || isset( $vals['CiAdrPcode'] )
1441 || isset( $vals['CiAdrRegion'] )
1442 || isset( $vals['CiUrlWork'] )
1443 ) ) {
1444 // We don't have any sub-properties
1445 // This could happen if its using old
1446 // iptc that just had this as a free-form
1447 // text value.
1448 // Note: We run this through htmlspecialchars
1449 // partially to be consistent, and partially
1450 // because people often insert >, etc into
1451 // the metadata which should not be interpreted
1452 // but we still want to auto-link urls.
1453 foreach ( $vals as &$val ) {
1454 $val = htmlspecialchars( $val );
1455 }
1456
1457 return $this->flattenArrayReal( $vals );
1458 } else {
1459 // We have a real ContactInfo field.
1460 // Its unclear if all these fields have to be
1461 // set, so assume they do not.
1462 $url = $tel = $street = $city = $country = '';
1463 $email = $postal = $region = '';
1464
1465 // Also note, some of the class names this uses
1466 // are similar to those used by hCard. This is
1467 // mostly because they're sensible names. This
1468 // does not (and does not attempt to) output
1469 // stuff in the hCard microformat. However it
1470 // might output in the adr microformat.
1471
1472 if ( isset( $vals['CiAdrExtadr'] ) ) {
1473 // Todo: This can potentially be multi-line.
1474 // Need to check how that works in XMP.
1475 $street = '<span class="extended-address">'
1476 . htmlspecialchars(
1477 $vals['CiAdrExtadr'] )
1478 . '</span>';
1479 }
1480 if ( isset( $vals['CiAdrCity'] ) ) {
1481 $city = '<span class="locality">'
1482 . htmlspecialchars( $vals['CiAdrCity'] )
1483 . '</span>';
1484 }
1485 if ( isset( $vals['CiAdrCtry'] ) ) {
1486 $country = '<span class="country-name">'
1487 . htmlspecialchars( $vals['CiAdrCtry'] )
1488 . '</span>';
1489 }
1490 if ( isset( $vals['CiEmailWork'] ) ) {
1491 $emails = array();
1492 // Have to split multiple emails at commas/new lines.
1493 $splitEmails = explode( "\n", $vals['CiEmailWork'] );
1494 foreach ( $splitEmails as $e1 ) {
1495 // Also split on comma
1496 foreach ( explode( ',', $e1 ) as $e2 ) {
1497 $finalEmail = trim( $e2 );
1498 if ( $finalEmail == ',' || $finalEmail == '' ) {
1499 continue;
1500 }
1501 if ( strpos( $finalEmail, '<' ) !== false ) {
1502 // Don't do fancy formatting to
1503 // "My name" <foo@bar.com> style stuff
1504 $emails[] = $finalEmail;
1505 } else {
1506 $emails[] = '[mailto:'
1507 . $finalEmail
1508 . ' <span class="email">'
1509 . $finalEmail
1510 . '</span>]';
1511 }
1512 }
1513 }
1514 $email = implode( ', ', $emails );
1515 }
1516 if ( isset( $vals['CiTelWork'] ) ) {
1517 $tel = '<span class="tel">'
1518 . htmlspecialchars( $vals['CiTelWork'] )
1519 . '</span>';
1520 }
1521 if ( isset( $vals['CiAdrPcode'] ) ) {
1522 $postal = '<span class="postal-code">'
1523 . htmlspecialchars(
1524 $vals['CiAdrPcode'] )
1525 . '</span>';
1526 }
1527 if ( isset( $vals['CiAdrRegion'] ) ) {
1528 // Note this is province/state.
1529 $region = '<span class="region">'
1530 . htmlspecialchars(
1531 $vals['CiAdrRegion'] )
1532 . '</span>';
1533 }
1534 if ( isset( $vals['CiUrlWork'] ) ) {
1535 $url = '<span class="url">'
1536 . htmlspecialchars( $vals['CiUrlWork'] )
1537 . '</span>';
1538 }
1539
1540 return $this->msg( 'exif-contact-value', $email, $url,
1541 $street, $city, $region, $postal, $country,
1542 $tel )->text();
1543 }
1544 }
1545
1546 /**
1547 * Get a list of fields that are visible by default.
1548 *
1549 * @return array
1550 * @since 1.23
1551 */
1552 public static function getVisibleFields() {
1553 $fields = array();
1554 $lines = explode( "\n", wfMessage( 'metadata-fields' )->inContentLanguage()->text() );
1555 foreach ( $lines as $line ) {
1556 $matches = array();
1557 if ( preg_match( '/^\\*\s*(.*?)\s*$/', $line, $matches ) ) {
1558 $fields[] = $matches[1];
1559 }
1560 }
1561 $fields = array_map( 'strtolower', $fields );
1562
1563 return $fields;
1564 }
1565
1566 /**
1567 * Get an array of extended metadata. (See the imageinfo API for format.)
1568 *
1569 * @param File $file File to use
1570 * @return array [<property name> => ['value' => <value>]], or [] on error
1571 * @since 1.23
1572 */
1573 public function fetchExtendedMetadata( File $file ) {
1574 global $wgMemc;
1575
1576 // If revision deleted, exit immediately
1577 if ( $file->isDeleted( File::DELETED_FILE ) ) {
1578 return array();
1579 }
1580
1581 $cacheKey = wfMemcKey(
1582 'getExtendedMetadata',
1583 $this->getLanguage()->getCode(),
1584 (int)$this->singleLang,
1585 $file->getSha1()
1586 );
1587
1588 $cachedValue = $wgMemc->get( $cacheKey );
1589 if (
1590 $cachedValue
1591 && Hooks::run( 'ValidateExtendedMetadataCache', array( $cachedValue['timestamp'], $file ) )
1592 ) {
1593 $extendedMetadata = $cachedValue['data'];
1594 } else {
1595 $maxCacheTime = ( $file instanceof ForeignAPIFile ) ? 60 * 60 * 12 : 60 * 60 * 24 * 30;
1596 $fileMetadata = $this->getExtendedMetadataFromFile( $file );
1597 $extendedMetadata = $this->getExtendedMetadataFromHook( $file, $fileMetadata, $maxCacheTime );
1598 if ( $this->singleLang ) {
1599 $this->resolveMultilangMetadata( $extendedMetadata );
1600 }
1601 $this->discardMultipleValues( $extendedMetadata );
1602 // Make sure the metadata won't break the API when an XML format is used.
1603 // This is an API-specific function so it would be cleaner to call it from
1604 // outside fetchExtendedMetadata, but this way we don't need to redo the
1605 // computation on a cache hit.
1606 $this->sanitizeArrayForAPI( $extendedMetadata );
1607 $valueToCache = array( 'data' => $extendedMetadata, 'timestamp' => wfTimestampNow() );
1608 $wgMemc->set( $cacheKey, $valueToCache, $maxCacheTime );
1609 }
1610
1611 return $extendedMetadata;
1612 }
1613
1614 /**
1615 * Get file-based metadata in standardized format.
1616 *
1617 * Note that for a remote file, this might return metadata supplied by extensions.
1618 *
1619 * @param File $file File to use
1620 * @return array [<property name> => ['value' => <value>]], or [] on error
1621 * @since 1.23
1622 */
1623 protected function getExtendedMetadataFromFile( File $file ) {
1624 // If this is a remote file accessed via an API request, we already
1625 // have remote metadata so we just ignore any local one
1626 if ( $file instanceof ForeignAPIFile ) {
1627 // In case of error we pretend no metadata - this will get cached.
1628 // Might or might not be a good idea.
1629 return $file->getExtendedMetadata() ?: array();
1630 }
1631
1632 $uploadDate = wfTimestamp( TS_ISO_8601, $file->getTimestamp() );
1633
1634 $fileMetadata = array(
1635 // This is modification time, which is close to "upload" time.
1636 'DateTime' => array(
1637 'value' => $uploadDate,
1638 'source' => 'mediawiki-metadata',
1639 ),
1640 );
1641
1642 $title = $file->getTitle();
1643 if ( $title ) {
1644 $text = $title->getText();
1645 $pos = strrpos( $text, '.' );
1646
1647 if ( $pos ) {
1648 $name = substr( $text, 0, $pos );
1649 } else {
1650 $name = $text;
1651 }
1652
1653 $fileMetadata['ObjectName'] = array(
1654 'value' => $name,
1655 'source' => 'mediawiki-metadata',
1656 );
1657 }
1658
1659 return $fileMetadata;
1660 }
1661
1662 /**
1663 * Get additional metadata from hooks in standardized format.
1664 *
1665 * @param File $file File to use
1666 * @param array $extendedMetadata
1667 * @param int $maxCacheTime Hook handlers might use this parameter to override cache time
1668 *
1669 * @return array [<property name> => ['value' => <value>]], or [] on error
1670 * @since 1.23
1671 */
1672 protected function getExtendedMetadataFromHook( File $file, array $extendedMetadata,
1673 &$maxCacheTime
1674 ) {
1675
1676 Hooks::run( 'GetExtendedMetadata', array(
1677 &$extendedMetadata,
1678 $file,
1679 $this->getContext(),
1680 $this->singleLang,
1681 &$maxCacheTime
1682 ) );
1683
1684 $visible = array_flip( self::getVisibleFields() );
1685 foreach ( $extendedMetadata as $key => $value ) {
1686 if ( !isset( $visible[strtolower( $key )] ) ) {
1687 $extendedMetadata[$key]['hidden'] = '';
1688 }
1689 }
1690
1691 return $extendedMetadata;
1692 }
1693
1694 /**
1695 * Turns an XMP-style multilang array into a single value.
1696 * If the value is not a multilang array, it is returned unchanged.
1697 * See mediawiki.org/wiki/Manual:File_metadata_handling#Multi-language_array_format
1698 * @param mixed $value
1699 * @return mixed Value in best language, null if there were no languages at all
1700 * @since 1.23
1701 */
1702 protected function resolveMultilangValue( $value ) {
1703 if (
1704 !is_array( $value )
1705 || !isset( $value['_type'] )
1706 || $value['_type'] != 'lang'
1707 ) {
1708 return $value; // do nothing if not a multilang array
1709 }
1710
1711 // choose the language best matching user or site settings
1712 $priorityLanguages = $this->getPriorityLanguages();
1713 foreach ( $priorityLanguages as $lang ) {
1714 if ( isset( $value[$lang] ) ) {
1715 return $value[$lang];
1716 }
1717 }
1718
1719 // otherwise go with the default language, if set
1720 if ( isset( $value['x-default'] ) ) {
1721 return $value['x-default'];
1722 }
1723
1724 // otherwise just return any one language
1725 unset( $value['_type'] );
1726 if ( !empty( $value ) ) {
1727 return reset( $value );
1728 }
1729
1730 // this should not happen; signal error
1731 return null;
1732 }
1733
1734 /**
1735 * Turns an XMP-style multivalue array into a single value by dropping all but the first
1736 * value. If the value is not a multivalue array (or a multivalue array inside a multilang
1737 * array), it is returned unchanged.
1738 * See mediawiki.org/wiki/Manual:File_metadata_handling#Multi-language_array_format
1739 * @param mixed $value
1740 * @return mixed The value, or the first value if there were multiple ones
1741 * @since 1.25
1742 */
1743 protected function resolveMultivalueValue( $value ) {
1744 if ( !is_array( $value ) ) {
1745 return $value;
1746 } elseif ( isset( $value['_type'] ) && $value['_type'] === 'lang' ) {
1747 // if this is a multilang array, process fields separately
1748 $newValue = array();
1749 foreach ( $value as $k => $v ) {
1750 $newValue[$k] = $this->resolveMultivalueValue( $v );
1751 }
1752 return $newValue;
1753 } else { // _type is 'ul' or 'ol' or missing in which case it defaults to 'ul'
1754 list( $k, $v ) = each( $value );
1755 if ( $k === '_type' ) {
1756 $v = current( $value );
1757 }
1758 return $v;
1759 }
1760 }
1761
1762 /**
1763 * Takes an array returned by the getExtendedMetadata* functions,
1764 * and resolves multi-language values in it.
1765 * @param array $metadata
1766 * @since 1.23
1767 */
1768 protected function resolveMultilangMetadata( &$metadata ) {
1769 if ( !is_array( $metadata ) ) {
1770 return;
1771 }
1772 foreach ( $metadata as &$field ) {
1773 if ( isset( $field['value'] ) ) {
1774 $field['value'] = $this->resolveMultilangValue( $field['value'] );
1775 }
1776 }
1777 }
1778
1779 /**
1780 * Takes an array returned by the getExtendedMetadata* functions,
1781 * and turns all fields into single-valued ones by dropping extra values.
1782 * @param array $metadata
1783 * @since 1.25
1784 */
1785 protected function discardMultipleValues( &$metadata ) {
1786 if ( !is_array( $metadata ) ) {
1787 return;
1788 }
1789 foreach ( $metadata as $key => &$field ) {
1790 if ( $key === 'Software' || $key === 'Contact' ) {
1791 // we skip some fields which have composite values. They are not particularly interesting
1792 // and you can get them via the metadata / commonmetadata APIs anyway.
1793 continue;
1794 }
1795 if ( isset( $field['value'] ) ) {
1796 $field['value'] = $this->resolveMultivalueValue( $field['value'] );
1797 }
1798 }
1799
1800 }
1801
1802 /**
1803 * Makes sure the given array is a valid API response fragment
1804 * @param array $arr
1805 */
1806 protected function sanitizeArrayForAPI( &$arr ) {
1807 if ( !is_array( $arr ) ) {
1808 return;
1809 }
1810
1811 $counter = 1;
1812 foreach ( $arr as $key => &$value ) {
1813 $sanitizedKey = $this->sanitizeKeyForAPI( $key );
1814 if ( $sanitizedKey !== $key ) {
1815 if ( isset( $arr[$sanitizedKey] ) ) {
1816 // Make the sanitized keys hopefully unique.
1817 // To make it definitely unique would be too much effort, given that
1818 // sanitizing is only needed for misformatted metadata anyway, but
1819 // this at least covers the case when $arr is numeric.
1820 $sanitizedKey .= $counter;
1821 ++$counter;
1822 }
1823 $arr[$sanitizedKey] = $arr[$key];
1824 unset( $arr[$key] );
1825 }
1826 if ( is_array( $value ) ) {
1827 $this->sanitizeArrayForAPI( $value );
1828 }
1829 }
1830
1831 // Handle API metadata keys (particularly "_type")
1832 $keys = array_filter( array_keys( $arr ), 'ApiResult::isMetadataKey' );
1833 if ( $keys ) {
1834 ApiResult::setPreserveKeysList( $arr, $keys );
1835 }
1836 }
1837
1838 /**
1839 * Turns a string into a valid API identifier.
1840 * @param string $key
1841 * @return string
1842 * @since 1.23
1843 */
1844 protected function sanitizeKeyForAPI( $key ) {
1845 // drop all characters which are not valid in an XML tag name
1846 // a bunch of non-ASCII letters would be valid but probably won't
1847 // be used so we take the easy way
1848 $key = preg_replace( '/[^a-zA-z0-9_:.-]/', '', $key );
1849 // drop characters which are invalid at the first position
1850 $key = preg_replace( '/^[\d-.]+/', '', $key );
1851
1852 if ( $key == '' ) {
1853 $key = '_';
1854 }
1855
1856 // special case for an internal keyword
1857 if ( $key == '_element' ) {
1858 $key = 'element';
1859 }
1860
1861 return $key;
1862 }
1863
1864 /**
1865 * Returns a list of languages (first is best) to use when formatting multilang fields,
1866 * based on user and site preferences.
1867 * @return array
1868 * @since 1.23
1869 */
1870 protected function getPriorityLanguages() {
1871 $priorityLanguages =
1872 Language::getFallbacksIncludingSiteLanguage( $this->getLanguage()->getCode() );
1873 $priorityLanguages = array_merge(
1874 (array)$this->getLanguage()->getCode(),
1875 $priorityLanguages[0],
1876 $priorityLanguages[1]
1877 );
1878
1879 return $priorityLanguages;
1880 }
1881 }