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