PHPSessionHandler: Implement SessionHandlerInterface
[mediawiki.git] / includes / media / FormatMetadata.php
blob73eeba667ae49b75f55fda5029dea64e03b4873a
1 <?php
2 /**
3 * Formatting of image metadata values into human readable form.
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.
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.
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
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
28 /**
29 * Format Image metadata values into a human readable form.
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).
42 * It should perhaps use a prefix like 'metadata' instead, but there
43 * is already a large number of messages using the 'exif' prefix.
45 * @ingroup Media
46 * @since 1.23 the class extends ContextSource and various formerly-public
47 * internal methods are private
49 class FormatMetadata extends ContextSource {
50 /**
51 * Only output a single language for multi-language fields
52 * @var bool
53 * @since 1.23
55 protected $singleLang = false;
57 /**
58 * Trigger only outputting single language for multilanguage fields
60 * @param bool $val
61 * @since 1.23
63 public function setSingleLanguage( $val ) {
64 $this->singleLang = $val;
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.
73 * This is the usual entry point for this class.
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
80 public static function getFormattedData( $tags, $context = false ) {
81 $obj = new FormatMetadata;
82 if ( $context ) {
83 $obj->setContext( $context );
86 return $obj->makeFormattedData( $tags );
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.
95 * @param array $tags The Exif data to format ( as returned by
96 * Exif::getFilteredData() or BitmapMetadataHandler )
97 * @return array
98 * @since 1.23
100 public function makeFormattedData( $tags ) {
101 $resolutionunit = !isset( $tags['ResolutionUnit'] ) || $tags['ResolutionUnit'] == 2 ? 2 : 3;
102 unset( $tags['ResolutionUnit'] );
104 foreach ( $tags as $tag => &$vals ) {
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 );
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.
120 // This is done differently as the tag is an array.
121 if ( $tag == 'GPSTimeStamp' && count( $vals ) === 3 ) {
122 // hour min sec array
124 $h = explode( '/', $vals[0] );
125 $m = explode( '/', $vals[1] );
126 $s = explode( '/', $vals[2] );
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
139 continue;
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 );
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 );
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
156 continue;
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;
167 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;
189 break;
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;
211 break;
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;
229 break;
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;
241 break;
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;
254 break;
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;
269 break;
271 // TODO: YCbCrCoefficients #p27 (see annex E)
272 case 'ExifVersion':
273 case 'FlashpixVersion':
274 $val = "$val" / 100;
275 break;
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;
287 break;
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;
304 break;
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 );
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 );
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 );
343 // else it will just output $val without formatting it.
344 break;
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;
363 break;
365 case 'SubjectDistance':
366 $val = $this->exifMsg( $tag, '', $this->formatNum( $val ) );
367 break;
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;
386 break;
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;
417 break;
419 case 'Flash':
420 $flashDecode = array(
421 'fired' => $val & bindec( '00000001' ),
422 'return' => ( $val & bindec( '00000110' ) ) >> 1,
423 'mode' => ( $val & bindec( '00011000' ) ) >> 3,
424 'function' => ( $val & bindec( '00100000' ) ) >> 5,
425 'redeye' => ( $val & bindec( '01000000' ) ) >> 6,
426 // 'reserved' => ($val & bindec( '10000000' )) >> 7,
428 $flashMsgs = array();
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;
435 $fullTag = $tag . '-' . $subTag;
436 $flashMsgs[] = $this->exifMsg( $fullTag, $subValue );
438 $val = $this->getLanguage()->commaList( $flashMsgs );
439 break;
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;
450 break;
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;
467 break;
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;
478 break;
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;
489 break;
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;
501 break;
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;
514 break;
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;
526 break;
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;
540 break;
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;
555 break;
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;
568 break;
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;
581 break;
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;
594 break;
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;
608 break;
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;
622 break;
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;
635 break;
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 ) );
643 break;
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;
655 break;
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;
667 break;
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;
681 break;
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;
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;
703 break;
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;
716 break;
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 ) );
731 break;
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;
741 case 'Software':
742 if ( is_array( $val ) ) {
743 // if its a software, version array.
744 $val = $this->msg( 'exif-software-version-value', $val[0], $val[1] )->text();
745 } else {
746 $val = $this->exifMsg( $tag, '', $val );
748 break;
750 case 'ExposureTime':
751 // Show the pretty fraction as well as decimal version
752 $val = $this->msg( 'exif-exposuretime-format',
753 $this->formatFraction( $val ), $this->formatNum( $val ) )->text();
754 break;
755 case 'ISOSpeedRatings':
756 // If its = 65535 that means its at the
757 // limit of the size of Exif::short and
758 // is really higher.
759 if ( $val == '65535' ) {
760 $val = $this->exifMsg( $tag, 'overflow' );
761 } else {
762 $val = $this->formatNum( $val );
764 break;
765 case 'FNumber':
766 $val = $this->msg( 'exif-fnumber-format',
767 $this->formatNum( $val ) )->text();
768 break;
770 case 'FocalLength':
771 case 'FocalLengthIn35mmFilm':
772 $val = $this->msg( 'exif-focallength-format',
773 $this->formatNum( $val ) )->text();
774 break;
776 case 'MaxApertureValue':
777 if ( strpos( $val, '/' ) !== false ) {
778 // need to expand this earlier to calculate fNumber
779 list( $n, $d ) = explode( '/', $val );
780 if ( is_numeric( $n ) && is_numeric( $d ) ) {
781 $val = $n / $d;
784 if ( is_numeric( $val ) ) {
785 $fNumber = pow( 2, $val / 2 );
786 if ( $fNumber !== false ) {
787 $val = $this->msg( 'exif-maxaperturevalue-value',
788 $this->formatNum( $val ),
789 $this->formatNum( $fNumber, 2 )
790 )->text();
793 break;
795 case 'iimCategory':
796 switch ( strtolower( $val ) ) {
797 // See pg 29 of IPTC photo
798 // metadata standard.
799 case 'ace':
800 case 'clj':
801 case 'dis':
802 case 'fin':
803 case 'edu':
804 case 'evn':
805 case 'hth':
806 case 'hum':
807 case 'lab':
808 case 'lif':
809 case 'pol':
810 case 'rel':
811 case 'sci':
812 case 'soi':
813 case 'spo':
814 case 'war':
815 case 'wea':
816 $val = $this->exifMsg(
817 'iimcategory',
818 $val
821 break;
822 case 'SubjectNewsCode':
823 // Essentially like iimCategory.
824 // 8 (numeric) digit hierarchical
825 // classification. We decode the
826 // first 2 digits, which provide
827 // a broad category.
828 $val = $this->convertNewsCode( $val );
829 break;
830 case 'Urgency':
831 // 1-8 with 1 being highest, 5 normal
832 // 0 is reserved, and 9 is 'user-defined'.
833 $urgency = '';
834 if ( $val == 0 || $val == 9 ) {
835 $urgency = 'other';
836 } elseif ( $val < 5 && $val > 1 ) {
837 $urgency = 'high';
838 } elseif ( $val == 5 ) {
839 $urgency = 'normal';
840 } elseif ( $val <= 8 && $val > 5 ) {
841 $urgency = 'low';
844 if ( $urgency !== '' ) {
845 $val = $this->exifMsg( 'urgency',
846 $urgency, $val
849 break;
851 // Things that have a unit of pixels.
852 case 'OriginalImageHeight':
853 case 'OriginalImageWidth':
854 case 'PixelXDimension':
855 case 'PixelYDimension':
856 case 'ImageWidth':
857 case 'ImageLength':
858 $val = $this->formatNum( $val ) . ' ' . $this->msg( 'unit-pixel' )->text();
859 break;
861 // Do not transform fields with pure text.
862 // For some languages the formatNum()
863 // conversion results to wrong output like
864 // foo,bar@example,com or foo٫bar@example٫com.
865 // Also some 'numeric' things like Scene codes
866 // are included here as we really don't want
867 // commas inserted.
868 case 'ImageDescription':
869 case 'Artist':
870 case 'Copyright':
871 case 'RelatedSoundFile':
872 case 'ImageUniqueID':
873 case 'SpectralSensitivity':
874 case 'GPSSatellites':
875 case 'GPSVersionID':
876 case 'GPSMapDatum':
877 case 'Keywords':
878 case 'WorldRegionDest':
879 case 'CountryDest':
880 case 'CountryCodeDest':
881 case 'ProvinceOrStateDest':
882 case 'CityDest':
883 case 'SublocationDest':
884 case 'WorldRegionCreated':
885 case 'CountryCreated':
886 case 'CountryCodeCreated':
887 case 'ProvinceOrStateCreated':
888 case 'CityCreated':
889 case 'SublocationCreated':
890 case 'ObjectName':
891 case 'SpecialInstructions':
892 case 'Headline':
893 case 'Credit':
894 case 'Source':
895 case 'EditStatus':
896 case 'FixtureIdentifier':
897 case 'LocationDest':
898 case 'LocationDestCode':
899 case 'Writer':
900 case 'JPEGFileComment':
901 case 'iimSupplementalCategory':
902 case 'OriginalTransmissionRef':
903 case 'Identifier':
904 case 'dc-contributor':
905 case 'dc-coverage':
906 case 'dc-publisher':
907 case 'dc-relation':
908 case 'dc-rights':
909 case 'dc-source':
910 case 'dc-type':
911 case 'Lens':
912 case 'SerialNumber':
913 case 'CameraOwnerName':
914 case 'Label':
915 case 'Nickname':
916 case 'RightsCertificate':
917 case 'CopyrightOwner':
918 case 'UsageTerms':
919 case 'WebStatement':
920 case 'OriginalDocumentID':
921 case 'LicenseUrl':
922 case 'MorePermissionsUrl':
923 case 'AttributionUrl':
924 case 'PreferredAttributionName':
925 case 'PNGFileComment':
926 case 'Disclaimer':
927 case 'ContentWarning':
928 case 'GIFFileComment':
929 case 'SceneCode':
930 case 'IntellectualGenre':
931 case 'Event':
932 case 'OrginisationInImage':
933 case 'PersonInImage':
935 $val = htmlspecialchars( $val );
936 break;
938 case 'ObjectCycle':
939 switch ( $val ) {
940 case 'a':
941 case 'p':
942 case 'b':
943 $val = $this->exifMsg( $tag, $val );
944 break;
945 default:
946 $val = htmlspecialchars( $val );
947 break;
949 break;
950 case 'Copyrighted':
951 switch ( $val ) {
952 case 'True':
953 case 'False':
954 $val = $this->exifMsg( $tag, $val );
955 break;
957 break;
958 case 'Rating':
959 if ( $val == '-1' ) {
960 $val = $this->exifMsg( $tag, 'rejected' );
961 } else {
962 $val = $this->formatNum( $val );
964 break;
966 case 'LanguageCode':
967 $lang = Language::fetchLanguageName( strtolower( $val ), $this->getLanguage()->getCode() );
968 if ( $lang ) {
969 $val = htmlspecialchars( $lang );
970 } else {
971 $val = htmlspecialchars( $val );
973 break;
975 default:
976 $val = $this->formatNum( $val );
977 break;
980 // End formatting values, start flattening arrays.
981 $vals = $this->flattenArrayReal( $vals, $type );
984 return $tags;
988 * Flatten an array, using the content language for any messages.
990 * @param array $vals Array of values
991 * @param string $type Type of array (either lang, ul, ol).
992 * lang = language assoc array with keys being the lang code
993 * ul = unordered list, ol = ordered list
994 * type can also come from the '_type' member of $vals.
995 * @param bool $noHtml If to avoid returning anything resembling HTML.
996 * (Ugly hack for backwards compatibility with old MediaWiki).
997 * @param bool|IContextSource $context
998 * @return string Single value (in wiki-syntax).
999 * @since 1.23
1001 public static function flattenArrayContentLang( $vals, $type = 'ul',
1002 $noHtml = false, $context = false
1004 global $wgContLang;
1005 $obj = new FormatMetadata;
1006 if ( $context ) {
1007 $obj->setContext( $context );
1009 $context = new DerivativeContext( $obj->getContext() );
1010 $context->setLanguage( $wgContLang );
1011 $obj->setContext( $context );
1013 return $obj->flattenArrayReal( $vals, $type, $noHtml );
1017 * A function to collapse multivalued tags into a single value.
1018 * This turns an array of (for example) authors into a bulleted list.
1020 * This is public on the basis it might be useful outside of this class.
1022 * @param array $vals Array of values
1023 * @param string $type Type of array (either lang, ul, ol).
1024 * lang = language assoc array with keys being the lang code
1025 * ul = unordered list, ol = ordered list
1026 * type can also come from the '_type' member of $vals.
1027 * @param bool $noHtml If to avoid returning anything resembling HTML.
1028 * (Ugly hack for backwards compatibility with old mediawiki).
1029 * @return string Single value (in wiki-syntax).
1030 * @since 1.23
1032 public function flattenArrayReal( $vals, $type = 'ul', $noHtml = false ) {
1033 if ( !is_array( $vals ) ) {
1034 return $vals; // do nothing if not an array;
1037 if ( isset( $vals['_type'] ) ) {
1038 $type = $vals['_type'];
1039 unset( $vals['_type'] );
1042 if ( !is_array( $vals ) ) {
1043 return $vals; // do nothing if not an array;
1044 } elseif ( count( $vals ) === 1 && $type !== 'lang' ) {
1045 return $vals[0];
1046 } elseif ( count( $vals ) === 0 ) {
1047 wfDebug( __METHOD__ . " metadata array with 0 elements!\n" );
1049 return ""; // paranoia. This should never happen
1050 } else {
1051 /* @todo FIXME: This should hide some of the list entries if there are
1052 * say more than four. Especially if a field is translated into 20
1053 * languages, we don't want to show them all by default
1055 switch ( $type ) {
1056 case 'lang':
1057 // Display default, followed by ContLang,
1058 // followed by the rest in no particular
1059 // order.
1061 // Todo: hide some items if really long list.
1063 $content = '';
1065 $priorityLanguages = $this->getPriorityLanguages();
1066 $defaultItem = false;
1067 $defaultLang = false;
1069 // If default is set, save it for later,
1070 // as we don't know if it's equal to
1071 // one of the lang codes. (In xmp
1072 // you specify the language for a
1073 // default property by having both
1074 // a default prop, and one in the language
1075 // that are identical)
1076 if ( isset( $vals['x-default'] ) ) {
1077 $defaultItem = $vals['x-default'];
1078 unset( $vals['x-default'] );
1080 foreach ( $priorityLanguages as $pLang ) {
1081 if ( isset( $vals[$pLang] ) ) {
1082 $isDefault = false;
1083 if ( $vals[$pLang] === $defaultItem ) {
1084 $defaultItem = false;
1085 $isDefault = true;
1087 $content .= $this->langItem(
1088 $vals[$pLang], $pLang,
1089 $isDefault, $noHtml );
1091 unset( $vals[$pLang] );
1093 if ( $this->singleLang ) {
1094 return Html::rawElement( 'span',
1095 array( 'lang' => $pLang ), $vals[$pLang] );
1100 // Now do the rest.
1101 foreach ( $vals as $lang => $item ) {
1102 if ( $item === $defaultItem ) {
1103 $defaultLang = $lang;
1104 continue;
1106 $content .= $this->langItem( $item,
1107 $lang, false, $noHtml );
1108 if ( $this->singleLang ) {
1109 return Html::rawElement( 'span',
1110 array( 'lang' => $lang ), $item );
1113 if ( $defaultItem !== false ) {
1114 $content = $this->langItem( $defaultItem,
1115 $defaultLang, true, $noHtml ) .
1116 $content;
1117 if ( $this->singleLang ) {
1118 return $defaultItem;
1121 if ( $noHtml ) {
1122 return $content;
1125 return '<ul class="metadata-langlist">' .
1126 $content .
1127 '</ul>';
1128 case 'ol':
1129 if ( $noHtml ) {
1130 return "\n#" . implode( "\n#", $vals );
1133 return "<ol><li>" . implode( "</li>\n<li>", $vals ) . '</li></ol>';
1134 case 'ul':
1135 default:
1136 if ( $noHtml ) {
1137 return "\n*" . implode( "\n*", $vals );
1140 return "<ul><li>" . implode( "</li>\n<li>", $vals ) . '</li></ul>';
1145 /** Helper function for creating lists of translations.
1147 * @param string $value Value (this is not escaped)
1148 * @param string $lang Lang code of item or false
1149 * @param bool $default If it is default value.
1150 * @param bool $noHtml If to avoid html (for back-compat)
1151 * @throws MWException
1152 * @return string Language item (Note: despite how this looks, this is
1153 * treated as wikitext, not as HTML).
1155 private function langItem( $value, $lang, $default = false, $noHtml = false ) {
1156 if ( $lang === false && $default === false ) {
1157 throw new MWException( '$lang and $default cannot both '
1158 . 'be false.' );
1161 if ( $noHtml ) {
1162 $wrappedValue = $value;
1163 } else {
1164 $wrappedValue = '<span class="mw-metadata-lang-value">'
1165 . $value . '</span>';
1168 if ( $lang === false ) {
1169 $msg = $this->msg( 'metadata-langitem-default', $wrappedValue );
1170 if ( $noHtml ) {
1171 return $msg->text() . "\n\n";
1172 } /* else */
1174 return '<li class="mw-metadata-lang-default">'
1175 . $msg->text()
1176 . "</li>\n";
1179 $lowLang = strtolower( $lang );
1180 $langName = Language::fetchLanguageName( $lowLang );
1181 if ( $langName === '' ) {
1182 // try just the base language name. (aka en-US -> en ).
1183 list( $langPrefix ) = explode( '-', $lowLang, 2 );
1184 $langName = Language::fetchLanguageName( $langPrefix );
1185 if ( $langName === '' ) {
1186 // give up.
1187 $langName = $lang;
1190 // else we have a language specified
1192 $msg = $this->msg( 'metadata-langitem', $wrappedValue, $langName, $lang );
1193 if ( $noHtml ) {
1194 return '*' . $msg->text();
1195 } /* else: */
1197 $item = '<li class="mw-metadata-lang-code-'
1198 . $lang;
1199 if ( $default ) {
1200 $item .= ' mw-metadata-lang-default';
1202 $item .= '" lang="' . $lang . '">';
1203 $item .= $msg->text();
1204 $item .= "</li>\n";
1206 return $item;
1210 * Convenience function for getFormattedData()
1212 * @param string $tag The tag name to pass on
1213 * @param string $val The value of the tag
1214 * @param string $arg An argument to pass ($1)
1215 * @param string $arg2 A 2nd argument to pass ($2)
1216 * @return string The text content of "exif-$tag-$val" message in lower case
1218 private function exifMsg( $tag, $val, $arg = null, $arg2 = null ) {
1219 global $wgContLang;
1221 if ( $val === '' ) {
1222 $val = 'value';
1225 return $this->msg( $wgContLang->lc( "exif-$tag-$val" ), $arg, $arg2 )->text();
1229 * Format a number, convert numbers from fractions into floating point
1230 * numbers, joins arrays of numbers with commas.
1232 * @param mixed $num The value to format
1233 * @param float|int|bool $round Digits to round to or false.
1234 * @return mixed A floating point number or whatever we were fed
1236 private function formatNum( $num, $round = false ) {
1237 $m = array();
1238 if ( is_array( $num ) ) {
1239 $out = array();
1240 foreach ( $num as $number ) {
1241 $out[] = $this->formatNum( $number );
1244 return $this->getLanguage()->commaList( $out );
1246 if ( preg_match( '/^(-?\d+)\/(\d+)$/', $num, $m ) ) {
1247 if ( $m[2] != 0 ) {
1248 $newNum = $m[1] / $m[2];
1249 if ( $round !== false ) {
1250 $newNum = round( $newNum, $round );
1252 } else {
1253 $newNum = $num;
1256 return $this->getLanguage()->formatNum( $newNum );
1257 } else {
1258 if ( is_numeric( $num ) && $round !== false ) {
1259 $num = round( $num, $round );
1262 return $this->getLanguage()->formatNum( $num );
1267 * Format a rational number, reducing fractions
1269 * @param mixed $num The value to format
1270 * @return mixed A floating point number or whatever we were fed
1272 private function formatFraction( $num ) {
1273 $m = array();
1274 if ( preg_match( '/^(-?\d+)\/(\d+)$/', $num, $m ) ) {
1275 $numerator = intval( $m[1] );
1276 $denominator = intval( $m[2] );
1277 $gcd = $this->gcd( abs( $numerator ), $denominator );
1278 if ( $gcd != 0 ) {
1279 // 0 shouldn't happen! ;)
1280 return $this->formatNum( $numerator / $gcd ) . '/' . $this->formatNum( $denominator / $gcd );
1284 return $this->formatNum( $num );
1288 * Calculate the greatest common divisor of two integers.
1290 * @param int $a Numerator
1291 * @param int $b Denominator
1292 * @return int
1294 private function gcd( $a, $b ) {
1296 // https://en.wikipedia.org/wiki/Euclidean_algorithm
1297 // Recursive form would be:
1298 if( $b == 0 )
1299 return $a;
1300 else
1301 return gcd( $b, $a % $b );
1303 while ( $b != 0 ) {
1304 $remainder = $a % $b;
1306 // tail recursion...
1307 $a = $b;
1308 $b = $remainder;
1311 return $a;
1315 * Fetch the human readable version of a news code.
1316 * A news code is an 8 digit code. The first two
1317 * digits are a general classification, so we just
1318 * translate that.
1320 * Note, leading 0's are significant, so this is
1321 * a string, not an int.
1323 * @param string $val The 8 digit news code.
1324 * @return string The human readable form
1326 private function convertNewsCode( $val ) {
1327 if ( !preg_match( '/^\d{8}$/D', $val ) ) {
1328 // Not a valid news code.
1329 return $val;
1331 $cat = '';
1332 switch ( substr( $val, 0, 2 ) ) {
1333 case '01':
1334 $cat = 'ace';
1335 break;
1336 case '02':
1337 $cat = 'clj';
1338 break;
1339 case '03':
1340 $cat = 'dis';
1341 break;
1342 case '04':
1343 $cat = 'fin';
1344 break;
1345 case '05':
1346 $cat = 'edu';
1347 break;
1348 case '06':
1349 $cat = 'evn';
1350 break;
1351 case '07':
1352 $cat = 'hth';
1353 break;
1354 case '08':
1355 $cat = 'hum';
1356 break;
1357 case '09':
1358 $cat = 'lab';
1359 break;
1360 case '10':
1361 $cat = 'lif';
1362 break;
1363 case '11':
1364 $cat = 'pol';
1365 break;
1366 case '12':
1367 $cat = 'rel';
1368 break;
1369 case '13':
1370 $cat = 'sci';
1371 break;
1372 case '14':
1373 $cat = 'soi';
1374 break;
1375 case '15':
1376 $cat = 'spo';
1377 break;
1378 case '16':
1379 $cat = 'war';
1380 break;
1381 case '17':
1382 $cat = 'wea';
1383 break;
1385 if ( $cat !== '' ) {
1386 $catMsg = $this->exifMsg( 'iimcategory', $cat );
1387 $val = $this->exifMsg( 'subjectnewscode', '', $val, $catMsg );
1390 return $val;
1394 * Format a coordinate value, convert numbers from floating point
1395 * into degree minute second representation.
1397 * @param int $coord Degrees, minutes and seconds
1398 * @param string $type Latitude or longitude (for if its a NWS or E)
1399 * @return mixed A floating point number or whatever we were fed
1401 private function formatCoords( $coord, $type ) {
1402 $ref = '';
1403 if ( $coord < 0 ) {
1404 $nCoord = -$coord;
1405 if ( $type === 'latitude' ) {
1406 $ref = 'S';
1407 } elseif ( $type === 'longitude' ) {
1408 $ref = 'W';
1410 } else {
1411 $nCoord = $coord;
1412 if ( $type === 'latitude' ) {
1413 $ref = 'N';
1414 } elseif ( $type === 'longitude' ) {
1415 $ref = 'E';
1419 $deg = floor( $nCoord );
1420 $min = floor( ( $nCoord - $deg ) * 60.0 );
1421 $sec = round( ( ( $nCoord - $deg ) - $min / 60 ) * 3600, 2 );
1423 $deg = $this->formatNum( $deg );
1424 $min = $this->formatNum( $min );
1425 $sec = $this->formatNum( $sec );
1427 return $this->msg( 'exif-coordinate-format', $deg, $min, $sec, $ref, $coord )->text();
1431 * Format the contact info field into a single value.
1433 * This function might be called from
1434 * JpegHandler::convertMetadataVersion which is why it is
1435 * public.
1437 * @param array $vals Array with fields of the ContactInfo
1438 * struct defined in the IPTC4XMP spec. Or potentially
1439 * an array with one element that is a free form text
1440 * value from the older iptc iim 1:118 prop.
1441 * @return string HTML-ish looking wikitext
1442 * @since 1.23 no longer static
1444 public function collapseContactInfo( $vals ) {
1445 if ( !( isset( $vals['CiAdrExtadr'] )
1446 || isset( $vals['CiAdrCity'] )
1447 || isset( $vals['CiAdrCtry'] )
1448 || isset( $vals['CiEmailWork'] )
1449 || isset( $vals['CiTelWork'] )
1450 || isset( $vals['CiAdrPcode'] )
1451 || isset( $vals['CiAdrRegion'] )
1452 || isset( $vals['CiUrlWork'] )
1453 ) ) {
1454 // We don't have any sub-properties
1455 // This could happen if its using old
1456 // iptc that just had this as a free-form
1457 // text value.
1458 // Note: We run this through htmlspecialchars
1459 // partially to be consistent, and partially
1460 // because people often insert >, etc into
1461 // the metadata which should not be interpreted
1462 // but we still want to auto-link urls.
1463 foreach ( $vals as &$val ) {
1464 $val = htmlspecialchars( $val );
1467 return $this->flattenArrayReal( $vals );
1468 } else {
1469 // We have a real ContactInfo field.
1470 // Its unclear if all these fields have to be
1471 // set, so assume they do not.
1472 $url = $tel = $street = $city = $country = '';
1473 $email = $postal = $region = '';
1475 // Also note, some of the class names this uses
1476 // are similar to those used by hCard. This is
1477 // mostly because they're sensible names. This
1478 // does not (and does not attempt to) output
1479 // stuff in the hCard microformat. However it
1480 // might output in the adr microformat.
1482 if ( isset( $vals['CiAdrExtadr'] ) ) {
1483 // Todo: This can potentially be multi-line.
1484 // Need to check how that works in XMP.
1485 $street = '<span class="extended-address">'
1486 . htmlspecialchars(
1487 $vals['CiAdrExtadr'] )
1488 . '</span>';
1490 if ( isset( $vals['CiAdrCity'] ) ) {
1491 $city = '<span class="locality">'
1492 . htmlspecialchars( $vals['CiAdrCity'] )
1493 . '</span>';
1495 if ( isset( $vals['CiAdrCtry'] ) ) {
1496 $country = '<span class="country-name">'
1497 . htmlspecialchars( $vals['CiAdrCtry'] )
1498 . '</span>';
1500 if ( isset( $vals['CiEmailWork'] ) ) {
1501 $emails = array();
1502 // Have to split multiple emails at commas/new lines.
1503 $splitEmails = explode( "\n", $vals['CiEmailWork'] );
1504 foreach ( $splitEmails as $e1 ) {
1505 // Also split on comma
1506 foreach ( explode( ',', $e1 ) as $e2 ) {
1507 $finalEmail = trim( $e2 );
1508 if ( $finalEmail == ',' || $finalEmail == '' ) {
1509 continue;
1511 if ( strpos( $finalEmail, '<' ) !== false ) {
1512 // Don't do fancy formatting to
1513 // "My name" <foo@bar.com> style stuff
1514 $emails[] = $finalEmail;
1515 } else {
1516 $emails[] = '[mailto:'
1517 . $finalEmail
1518 . ' <span class="email">'
1519 . $finalEmail
1520 . '</span>]';
1524 $email = implode( ', ', $emails );
1526 if ( isset( $vals['CiTelWork'] ) ) {
1527 $tel = '<span class="tel">'
1528 . htmlspecialchars( $vals['CiTelWork'] )
1529 . '</span>';
1531 if ( isset( $vals['CiAdrPcode'] ) ) {
1532 $postal = '<span class="postal-code">'
1533 . htmlspecialchars(
1534 $vals['CiAdrPcode'] )
1535 . '</span>';
1537 if ( isset( $vals['CiAdrRegion'] ) ) {
1538 // Note this is province/state.
1539 $region = '<span class="region">'
1540 . htmlspecialchars(
1541 $vals['CiAdrRegion'] )
1542 . '</span>';
1544 if ( isset( $vals['CiUrlWork'] ) ) {
1545 $url = '<span class="url">'
1546 . htmlspecialchars( $vals['CiUrlWork'] )
1547 . '</span>';
1550 return $this->msg( 'exif-contact-value', $email, $url,
1551 $street, $city, $region, $postal, $country,
1552 $tel )->text();
1557 * Get a list of fields that are visible by default.
1559 * @return array
1560 * @since 1.23
1562 public static function getVisibleFields() {
1563 $fields = array();
1564 $lines = explode( "\n", wfMessage( 'metadata-fields' )->inContentLanguage()->text() );
1565 foreach ( $lines as $line ) {
1566 $matches = array();
1567 if ( preg_match( '/^\\*\s*(.*?)\s*$/', $line, $matches ) ) {
1568 $fields[] = $matches[1];
1571 $fields = array_map( 'strtolower', $fields );
1573 return $fields;
1577 * Get an array of extended metadata. (See the imageinfo API for format.)
1579 * @param File $file File to use
1580 * @return array [<property name> => ['value' => <value>]], or [] on error
1581 * @since 1.23
1583 public function fetchExtendedMetadata( File $file ) {
1584 $cache = ObjectCache::getMainWANInstance();
1586 // If revision deleted, exit immediately
1587 if ( $file->isDeleted( File::DELETED_FILE ) ) {
1588 return array();
1591 $cacheKey = wfMemcKey(
1592 'getExtendedMetadata',
1593 $this->getLanguage()->getCode(),
1594 (int)$this->singleLang,
1595 $file->getSha1()
1598 $cachedValue = $cache->get( $cacheKey );
1599 if (
1600 $cachedValue
1601 && Hooks::run( 'ValidateExtendedMetadataCache', array( $cachedValue['timestamp'], $file ) )
1603 $extendedMetadata = $cachedValue['data'];
1604 } else {
1605 $maxCacheTime = ( $file instanceof ForeignAPIFile ) ? 60 * 60 * 12 : 60 * 60 * 24 * 30;
1606 $fileMetadata = $this->getExtendedMetadataFromFile( $file );
1607 $extendedMetadata = $this->getExtendedMetadataFromHook( $file, $fileMetadata, $maxCacheTime );
1608 if ( $this->singleLang ) {
1609 $this->resolveMultilangMetadata( $extendedMetadata );
1611 $this->discardMultipleValues( $extendedMetadata );
1612 // Make sure the metadata won't break the API when an XML format is used.
1613 // This is an API-specific function so it would be cleaner to call it from
1614 // outside fetchExtendedMetadata, but this way we don't need to redo the
1615 // computation on a cache hit.
1616 $this->sanitizeArrayForAPI( $extendedMetadata );
1617 $valueToCache = array( 'data' => $extendedMetadata, 'timestamp' => wfTimestampNow() );
1618 $cache->set( $cacheKey, $valueToCache, $maxCacheTime );
1621 return $extendedMetadata;
1625 * Get file-based metadata in standardized format.
1627 * Note that for a remote file, this might return metadata supplied by extensions.
1629 * @param File $file File to use
1630 * @return array [<property name> => ['value' => <value>]], or [] on error
1631 * @since 1.23
1633 protected function getExtendedMetadataFromFile( File $file ) {
1634 // If this is a remote file accessed via an API request, we already
1635 // have remote metadata so we just ignore any local one
1636 if ( $file instanceof ForeignAPIFile ) {
1637 // In case of error we pretend no metadata - this will get cached.
1638 // Might or might not be a good idea.
1639 return $file->getExtendedMetadata() ?: array();
1642 $uploadDate = wfTimestamp( TS_ISO_8601, $file->getTimestamp() );
1644 $fileMetadata = array(
1645 // This is modification time, which is close to "upload" time.
1646 'DateTime' => array(
1647 'value' => $uploadDate,
1648 'source' => 'mediawiki-metadata',
1652 $title = $file->getTitle();
1653 if ( $title ) {
1654 $text = $title->getText();
1655 $pos = strrpos( $text, '.' );
1657 if ( $pos ) {
1658 $name = substr( $text, 0, $pos );
1659 } else {
1660 $name = $text;
1663 $fileMetadata['ObjectName'] = array(
1664 'value' => $name,
1665 'source' => 'mediawiki-metadata',
1669 return $fileMetadata;
1673 * Get additional metadata from hooks in standardized format.
1675 * @param File $file File to use
1676 * @param array $extendedMetadata
1677 * @param int $maxCacheTime Hook handlers might use this parameter to override cache time
1679 * @return array [<property name> => ['value' => <value>]], or [] on error
1680 * @since 1.23
1682 protected function getExtendedMetadataFromHook( File $file, array $extendedMetadata,
1683 &$maxCacheTime
1686 Hooks::run( 'GetExtendedMetadata', array(
1687 &$extendedMetadata,
1688 $file,
1689 $this->getContext(),
1690 $this->singleLang,
1691 &$maxCacheTime
1692 ) );
1694 $visible = array_flip( self::getVisibleFields() );
1695 foreach ( $extendedMetadata as $key => $value ) {
1696 if ( !isset( $visible[strtolower( $key )] ) ) {
1697 $extendedMetadata[$key]['hidden'] = '';
1701 return $extendedMetadata;
1705 * Turns an XMP-style multilang array into a single value.
1706 * If the value is not a multilang array, it is returned unchanged.
1707 * See mediawiki.org/wiki/Manual:File_metadata_handling#Multi-language_array_format
1708 * @param mixed $value
1709 * @return mixed Value in best language, null if there were no languages at all
1710 * @since 1.23
1712 protected function resolveMultilangValue( $value ) {
1713 if (
1714 !is_array( $value )
1715 || !isset( $value['_type'] )
1716 || $value['_type'] != 'lang'
1718 return $value; // do nothing if not a multilang array
1721 // choose the language best matching user or site settings
1722 $priorityLanguages = $this->getPriorityLanguages();
1723 foreach ( $priorityLanguages as $lang ) {
1724 if ( isset( $value[$lang] ) ) {
1725 return $value[$lang];
1729 // otherwise go with the default language, if set
1730 if ( isset( $value['x-default'] ) ) {
1731 return $value['x-default'];
1734 // otherwise just return any one language
1735 unset( $value['_type'] );
1736 if ( !empty( $value ) ) {
1737 return reset( $value );
1740 // this should not happen; signal error
1741 return null;
1745 * Turns an XMP-style multivalue array into a single value by dropping all but the first
1746 * value. If the value is not a multivalue array (or a multivalue array inside a multilang
1747 * array), it is returned unchanged.
1748 * See mediawiki.org/wiki/Manual:File_metadata_handling#Multi-language_array_format
1749 * @param mixed $value
1750 * @return mixed The value, or the first value if there were multiple ones
1751 * @since 1.25
1753 protected function resolveMultivalueValue( $value ) {
1754 if ( !is_array( $value ) ) {
1755 return $value;
1756 } elseif ( isset( $value['_type'] ) && $value['_type'] === 'lang' ) {
1757 // if this is a multilang array, process fields separately
1758 $newValue = array();
1759 foreach ( $value as $k => $v ) {
1760 $newValue[$k] = $this->resolveMultivalueValue( $v );
1762 return $newValue;
1763 } else { // _type is 'ul' or 'ol' or missing in which case it defaults to 'ul'
1764 list( $k, $v ) = each( $value );
1765 if ( $k === '_type' ) {
1766 $v = current( $value );
1768 return $v;
1773 * Takes an array returned by the getExtendedMetadata* functions,
1774 * and resolves multi-language values in it.
1775 * @param array $metadata
1776 * @since 1.23
1778 protected function resolveMultilangMetadata( &$metadata ) {
1779 if ( !is_array( $metadata ) ) {
1780 return;
1782 foreach ( $metadata as &$field ) {
1783 if ( isset( $field['value'] ) ) {
1784 $field['value'] = $this->resolveMultilangValue( $field['value'] );
1790 * Takes an array returned by the getExtendedMetadata* functions,
1791 * and turns all fields into single-valued ones by dropping extra values.
1792 * @param array $metadata
1793 * @since 1.25
1795 protected function discardMultipleValues( &$metadata ) {
1796 if ( !is_array( $metadata ) ) {
1797 return;
1799 foreach ( $metadata as $key => &$field ) {
1800 if ( $key === 'Software' || $key === 'Contact' ) {
1801 // we skip some fields which have composite values. They are not particularly interesting
1802 // and you can get them via the metadata / commonmetadata APIs anyway.
1803 continue;
1805 if ( isset( $field['value'] ) ) {
1806 $field['value'] = $this->resolveMultivalueValue( $field['value'] );
1813 * Makes sure the given array is a valid API response fragment
1814 * @param array $arr
1816 protected function sanitizeArrayForAPI( &$arr ) {
1817 if ( !is_array( $arr ) ) {
1818 return;
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;
1833 $arr[$sanitizedKey] = $arr[$key];
1834 unset( $arr[$key] );
1836 if ( is_array( $value ) ) {
1837 $this->sanitizeArrayForAPI( $value );
1841 // Handle API metadata keys (particularly "_type")
1842 $keys = array_filter( array_keys( $arr ), 'ApiResult::isMetadataKey' );
1843 if ( $keys ) {
1844 ApiResult::setPreserveKeysList( $arr, $keys );
1849 * Turns a string into a valid API identifier.
1850 * @param string $key
1851 * @return string
1852 * @since 1.23
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 );
1862 if ( $key == '' ) {
1863 $key = '_';
1866 // special case for an internal keyword
1867 if ( $key == '_element' ) {
1868 $key = 'element';
1871 return $key;
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
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]
1889 return $priorityLanguages;