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
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
27 use MediaWiki\MediaWikiServices
;
28 use Wikimedia\Timestamp\TimestampException
;
31 * Format Image metadata values into a human readable form.
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).
44 * It should perhaps use a prefix like 'metadata' instead, but there
45 * is already a large number of messages using the 'exif' prefix.
48 * @since 1.23 the class extends ContextSource and various formerly-public
49 * internal methods are private
51 class FormatMetadata
extends ContextSource
{
53 * Only output a single language for multi-language fields
57 protected $singleLang = false;
60 * Trigger only outputting single language for multilanguage fields
65 public function setSingleLanguage( $val ) {
66 $this->singleLang
= $val;
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.
75 * This is the usual entry point for this class.
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)
82 public static function getFormattedData( $tags, $context = false ) {
83 $obj = new FormatMetadata
;
85 $obj->setContext( $context );
88 return $obj->makeFormattedData( $tags );
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.
97 * @param array $tags The Exif data to format ( as returned by
98 * Exif::getFilteredData() or BitmapMetadataHandler )
101 * @suppress PhanTypeArraySuspiciousNullable
103 public function makeFormattedData( $tags ) {
104 $resolutionunit = !isset( $tags['ResolutionUnit'] ) ||
$tags['ResolutionUnit'] == 2 ?
2 : 3;
105 unset( $tags['ResolutionUnit'] );
107 foreach ( $tags as $tag => &$vals ) {
108 // This seems ugly to wrap non-array's in an array just to unwrap again,
109 // especially when most of the time it is not an array
110 if ( !is_array( $tags[$tag] ) ) {
114 // _type is a special value to say what array type
115 if ( isset( $tags[$tag]['_type'] ) ) {
116 $type = $tags[$tag]['_type'];
117 unset( $vals['_type'] );
119 $type = 'ul'; // default unordered list.
122 // This is done differently as the tag is an array.
123 if ( $tag == 'GPSTimeStamp' && count( $vals ) === 3 ) {
124 // hour min sec array
126 $h = explode( '/', $vals[0] );
127 $m = explode( '/', $vals[1] );
128 $s = explode( '/', $vals[2] );
130 // this should already be validated
131 // when loaded from file, but it could
132 // come from a foreign repo, so be
143 $tags[$tag] = str_pad( intval( $h[0] / $h[1] ), 2, '0', STR_PAD_LEFT
)
144 . ':' . str_pad( intval( $m[0] / $m[1] ), 2, '0', STR_PAD_LEFT
)
145 . ':' . str_pad( intval( $s[0] / $s[1] ), 2, '0', STR_PAD_LEFT
);
148 $time = wfTimestamp( TS_MW
, '1971:01:01 ' . $tags[$tag] );
149 // the 1971:01:01 is just a placeholder, and not shown to user.
150 if ( $time && intval( $time ) > 0 ) {
151 $tags[$tag] = $this->getLanguage()->time( $time );
153 } catch ( TimestampException
$e ) {
154 // This shouldn't happen, but we've seen bad formats
155 // such as 4-digit seconds in the wild.
156 // leave $tags[$tag] as-is
161 // The contact info is a multi-valued field
162 // instead of the other props which are single
163 // valued (mostly) so handle as a special case.
164 if ( $tag === 'Contact' ) {
165 $vals = $this->collapseContactInfo( $vals );
169 foreach ( $vals as &$val ) {
184 $val = $this->exifMsg( $tag, $val );
187 /* If not recognized, display as is. */
192 case 'PhotometricInterpretation':
206 $val = $this->exifMsg( $tag, $val );
209 /* If not recognized, display as is. */
224 $val = $this->exifMsg( $tag, $val );
227 /* If not recognized, display as is. */
232 case 'PlanarConfiguration':
236 $val = $this->exifMsg( $tag, $val );
239 /* If not recognized, display as is. */
244 // TODO: YCbCrSubSampling
245 case 'YCbCrPositioning':
249 $val = $this->exifMsg( $tag, $val );
252 /* If not recognized, display as is. */
259 switch ( $resolutionunit ) {
261 $val = $this->exifMsg( 'XYResolution', 'i', $this->formatNum( $val ) );
264 $val = $this->exifMsg( 'XYResolution', 'c', $this->formatNum( $val ) );
267 /* If not recognized, display as is. */
272 // TODO: YCbCrCoefficients #p27 (see annex E)
274 case 'FlashpixVersion':
275 $val = (int)$val / 100;
282 $val = $this->exifMsg( $tag, $val );
285 /* If not recognized, display as is. */
290 case 'ComponentsConfiguration':
299 $val = $this->exifMsg( $tag, $val );
302 /* If not recognized, display as is. */
308 case 'DateTimeOriginal':
309 case 'DateTimeDigitized':
310 case 'DateTimeReleased':
311 case 'DateTimeExpires':
314 case 'DateTimeMetadata':
315 if ( $val == '0000:00:00 00:00:00' ||
$val == ' : : : : ' ) {
316 $val = $this->msg( 'exif-unknowndate' )->text();
317 } elseif ( preg_match(
318 '/^(?:\d{4}):(?:\d\d):(?:\d\d) (?:\d\d):(?:\d\d):(?:\d\d)$/D',
322 $time = wfTimestamp( TS_MW
, $val );
323 if ( $time && intval( $time ) > 0 ) {
324 $val = $this->getLanguage()->timeanddate( $time );
326 } elseif ( preg_match( '/^(?:\d{4}):(?:\d\d):(?:\d\d) (?:\d\d):(?:\d\d)$/D', $val ) ) {
327 // No second field. Still format the same
328 // since timeanddate doesn't include seconds anyways,
329 // but second still available in api
330 $time = wfTimestamp( TS_MW
, $val . ':00' );
331 if ( $time && intval( $time ) > 0 ) {
332 $val = $this->getLanguage()->timeanddate( $time );
334 } elseif ( preg_match( '/^(?:\d{4}):(?:\d\d):(?:\d\d)$/D', $val ) ) {
335 // If only the date but not the time is filled in.
336 $time = wfTimestamp( TS_MW
, substr( $val, 0, 4 )
337 . substr( $val, 5, 2 )
338 . substr( $val, 8, 2 )
340 if ( $time && intval( $time ) > 0 ) {
341 $val = $this->getLanguage()->date( $time );
344 // else it will just output $val without formatting it.
347 case 'ExposureProgram':
358 $val = $this->exifMsg( $tag, $val );
361 /* If not recognized, display as is. */
366 case 'SubjectDistance':
367 $val = $this->exifMsg( $tag, '', $this->formatNum( $val ) );
381 $val = $this->exifMsg( $tag, $val );
384 /* If not recognized, display as is. */
412 $val = $this->exifMsg( $tag, $val );
415 /* If not recognized, display as is. */
422 'fired' => $val & 0b00000001
,
423 'return' => ( $val & 0b00000110
) >> 1,
424 'mode' => ( $val & 0b00011000
) >> 3,
425 'function' => ( $val & 0b00100000
) >> 5,
426 'redeye' => ( $val & 0b01000000
) >> 6,
427 // 'reserved' => ( $val & 0b10000000 ) >> 7,
430 # We do not need to handle unknown values since all are used.
431 foreach ( $flashDecode as $subTag => $subValue ) {
432 # We do not need any message for zeroed values.
433 if ( $subTag != 'fired' && $subValue == 0 ) {
436 $fullTag = $tag . '-' . $subTag;
437 $flashMsgs[] = $this->exifMsg( $fullTag, $subValue );
439 $val = $this->getLanguage()->commaList( $flashMsgs );
442 case 'FocalPlaneResolutionUnit':
445 $val = $this->exifMsg( $tag, $val );
448 /* If not recognized, display as is. */
453 case 'SensingMethod':
462 $val = $this->exifMsg( $tag, $val );
465 /* If not recognized, display as is. */
473 $val = $this->exifMsg( $tag, $val );
476 /* If not recognized, display as is. */
484 $val = $this->exifMsg( $tag, $val );
487 /* If not recognized, display as is. */
492 case 'CustomRendered':
496 /* The following are unofficial Apple additions */
497 case 2: /* HDR (no original saved) */
498 case 3: /* HDR (original saved) */
499 case 4: /* Original (for HDR) */
500 /* Yes 5 is not present ;) */
501 case 6: /* Panorama */
502 case 7: /* Portrait HDR */
503 case 8: /* Portrait */
504 $val = $this->exifMsg( $tag, $val );
507 /* If not recognized, display as is. */
517 $val = $this->exifMsg( $tag, $val );
520 /* If not recognized, display as is. */
529 $val = $this->exifMsg( $tag, $val );
532 /* If not recognized, display as is. */
537 case 'SceneCaptureType':
543 $val = $this->exifMsg( $tag, $val );
546 /* If not recognized, display as is. */
558 $val = $this->exifMsg( $tag, $val );
561 /* If not recognized, display as is. */
571 $val = $this->exifMsg( $tag, $val );
574 /* If not recognized, display as is. */
584 $val = $this->exifMsg( $tag, $val );
587 /* If not recognized, display as is. */
597 $val = $this->exifMsg( $tag, $val );
600 /* If not recognized, display as is. */
605 case 'SubjectDistanceRange':
611 $val = $this->exifMsg( $tag, $val );
614 /* If not recognized, display as is. */
619 // The GPS...Ref values are kept for compatibility, probably won't be reached.
620 case 'GPSLatitudeRef':
621 case 'GPSDestLatitudeRef':
625 $val = $this->exifMsg( 'GPSLatitude', $val );
628 /* If not recognized, display as is. */
633 case 'GPSLongitudeRef':
634 case 'GPSDestLongitudeRef':
638 $val = $this->exifMsg( 'GPSLongitude', $val );
641 /* If not recognized, display as is. */
648 $val = $this->exifMsg( 'GPSAltitude', 'below-sealevel', $this->formatNum( -$val, 3 ) );
650 $val = $this->exifMsg( 'GPSAltitude', 'above-sealevel', $this->formatNum( $val, 3 ) );
658 $val = $this->exifMsg( $tag, $val );
661 /* If not recognized, display as is. */
666 case 'GPSMeasureMode':
670 $val = $this->exifMsg( $tag, $val );
673 /* If not recognized, display as is. */
679 case 'GPSImgDirectionRef':
680 case 'GPSDestBearingRef':
684 $val = $this->exifMsg( 'GPSDirection', $val );
687 /* If not recognized, display as is. */
693 case 'GPSDestLatitude':
694 $val = $this->formatCoords( $val, 'latitude' );
697 case 'GPSDestLongitude':
698 $val = $this->formatCoords( $val, 'longitude' );
706 $val = $this->exifMsg( 'GPSSpeed', $val );
709 /* If not recognized, display as is. */
714 case 'GPSDestDistanceRef':
719 $val = $this->exifMsg( 'GPSDestDistance', $val );
722 /* If not recognized, display as is. */
728 // See https://en.wikipedia.org/wiki/Dilution_of_precision_(GPS)
730 $val = $this->exifMsg( $tag, 'excellent', $this->formatNum( $val ) );
731 } elseif ( $val <= 5 ) {
732 $val = $this->exifMsg( $tag, 'good', $this->formatNum( $val ) );
733 } elseif ( $val <= 10 ) {
734 $val = $this->exifMsg( $tag, 'moderate', $this->formatNum( $val ) );
735 } elseif ( $val <= 20 ) {
736 $val = $this->exifMsg( $tag, 'fair', $this->formatNum( $val ) );
738 $val = $this->exifMsg( $tag, 'poor', $this->formatNum( $val ) );
742 // This is not in the Exif standard, just a special
743 // case for our purposes which enables wikis to wikify
744 // the make, model and software name to link to their articles.
747 $val = $this->exifMsg( $tag, '', $val );
751 if ( is_array( $val ) ) {
752 if ( count( $val ) > 1 ) {
753 // if its a software, version array.
754 $val = $this->msg( 'exif-software-version-value', $val[0], $val[1] )->text();
756 // https://phabricator.wikimedia.org/T178130
757 $val = $this->exifMsg( $tag, '', $val[0] );
760 $val = $this->exifMsg( $tag, '', $val );
765 // Show the pretty fraction as well as decimal version
766 $val = $this->msg( 'exif-exposuretime-format',
767 $this->formatFraction( $val ), $this->formatNum( $val ) )->text();
769 case 'ISOSpeedRatings':
770 // If its = 65535 that means its at the
771 // limit of the size of Exif::short and
773 if ( $val == '65535' ) {
774 $val = $this->exifMsg( $tag, 'overflow' );
776 $val = $this->formatNum( $val );
780 $val = $this->msg( 'exif-fnumber-format',
781 $this->formatNum( $val ) )->text();
785 case 'FocalLengthIn35mmFilm':
786 $val = $this->msg( 'exif-focallength-format',
787 $this->formatNum( $val ) )->text();
790 case 'MaxApertureValue':
791 if ( strpos( $val, '/' ) !== false ) {
792 // need to expand this earlier to calculate fNumber
793 list( $n, $d ) = explode( '/', $val );
794 if ( is_numeric( $n ) && is_numeric( $d ) ) {
798 if ( is_numeric( $val ) ) {
799 $fNumber = 2 ** ( $val / 2 );
800 if ( $fNumber !== false ) {
801 $val = $this->msg( 'exif-maxaperturevalue-value',
802 $this->formatNum( $val ),
803 $this->formatNum( $fNumber, 2 )
810 switch ( strtolower( $val ) ) {
811 // See pg 29 of IPTC photo
812 // metadata standard.
830 $val = $this->exifMsg(
836 case 'SubjectNewsCode':
837 // Essentially like iimCategory.
838 // 8 (numeric) digit hierarchical
839 // classification. We decode the
840 // first 2 digits, which provide
842 $val = $this->convertNewsCode( $val );
845 // 1-8 with 1 being highest, 5 normal
846 // 0 is reserved, and 9 is 'user-defined'.
848 if ( $val == 0 ||
$val == 9 ) {
850 } elseif ( $val < 5 && $val > 1 ) {
852 } elseif ( $val == 5 ) {
854 } elseif ( $val <= 8 && $val > 5 ) {
858 if ( $urgency !== '' ) {
859 $val = $this->exifMsg( 'urgency',
865 // Things that have a unit of pixels.
866 case 'OriginalImageHeight':
867 case 'OriginalImageWidth':
868 case 'PixelXDimension':
869 case 'PixelYDimension':
872 $val = $this->formatNum( $val ) . ' ' . $this->msg( 'unit-pixel' )->text();
875 // Do not transform fields with pure text.
876 // For some languages the formatNum()
877 // conversion results to wrong output like
878 // foo,bar@example,com or foo٫bar@example٫com.
879 // Also some 'numeric' things like Scene codes
880 // are included here as we really don't want
882 case 'ImageDescription':
886 case 'RelatedSoundFile':
887 case 'ImageUniqueID':
888 case 'SpectralSensitivity':
889 case 'GPSSatellites':
893 case 'WorldRegionDest':
895 case 'CountryCodeDest':
896 case 'ProvinceOrStateDest':
898 case 'SublocationDest':
899 case 'WorldRegionCreated':
900 case 'CountryCreated':
901 case 'CountryCodeCreated':
902 case 'ProvinceOrStateCreated':
904 case 'SublocationCreated':
906 case 'SpecialInstructions':
911 case 'FixtureIdentifier':
913 case 'LocationDestCode':
915 case 'JPEGFileComment':
916 case 'iimSupplementalCategory':
917 case 'OriginalTransmissionRef':
919 case 'dc-contributor':
928 case 'CameraOwnerName':
931 case 'RightsCertificate':
932 case 'CopyrightOwner':
935 case 'OriginalDocumentID':
937 case 'MorePermissionsUrl':
938 case 'AttributionUrl':
939 case 'PreferredAttributionName':
940 case 'PNGFileComment':
942 case 'ContentWarning':
943 case 'GIFFileComment':
945 case 'IntellectualGenre':
947 case 'OrginisationInImage':
948 case 'PersonInImage':
950 $val = htmlspecialchars( $val );
958 $val = $this->exifMsg( $tag, $val );
961 $val = htmlspecialchars( $val );
969 $val = $this->exifMsg( $tag, $val );
974 if ( $val == '-1' ) {
975 $val = $this->exifMsg( $tag, 'rejected' );
977 $val = $this->formatNum( $val );
982 $lang = Language
::fetchLanguageName( strtolower( $val ), $this->getLanguage()->getCode() );
983 $val = htmlspecialchars( $lang ?
: $val );
987 $val = $this->formatNum( $val );
991 // End formatting values, start flattening arrays.
992 $vals = $this->flattenArrayReal( $vals, $type );
999 * Flatten an array, using the content language for any messages.
1001 * @param array $vals Array of values
1002 * @param string $type Type of array (either lang, ul, ol).
1003 * lang = language assoc array with keys being the lang code
1004 * ul = unordered list, ol = ordered list
1005 * type can also come from the '_type' member of $vals.
1006 * @param bool $noHtml If to avoid returning anything resembling HTML.
1007 * (Ugly hack for backwards compatibility with old MediaWiki).
1008 * @param bool|IContextSource $context
1009 * @return string Single value (in wiki-syntax).
1012 public static function flattenArrayContentLang( $vals, $type = 'ul',
1013 $noHtml = false, $context = false
1015 $obj = new FormatMetadata
;
1017 $obj->setContext( $context );
1019 $context = new DerivativeContext( $obj->getContext() );
1020 $context->setLanguage( MediaWikiServices
::getInstance()->getContentLanguage() );
1021 $obj->setContext( $context );
1023 return $obj->flattenArrayReal( $vals, $type, $noHtml );
1027 * A function to collapse multivalued tags into a single value.
1028 * This turns an array of (for example) authors into a bulleted list.
1030 * This is public on the basis it might be useful outside of this class.
1032 * @param array $vals Array of values
1033 * @param string $type Type of array (either lang, ul, ol).
1034 * lang = language assoc array with keys being the lang code
1035 * ul = unordered list, ol = ordered list
1036 * type can also come from the '_type' member of $vals.
1037 * @param bool $noHtml If to avoid returning anything resembling HTML.
1038 * (Ugly hack for backwards compatibility with old mediawiki).
1039 * @return string Single value (in wiki-syntax).
1042 public function flattenArrayReal( $vals, $type = 'ul', $noHtml = false ) {
1043 if ( !is_array( $vals ) ) {
1044 return $vals; // do nothing if not an array;
1047 if ( isset( $vals['_type'] ) ) {
1048 $type = $vals['_type'];
1049 unset( $vals['_type'] );
1052 if ( !is_array( $vals ) ) {
1053 return $vals; // do nothing if not an array;
1054 } elseif ( count( $vals ) === 1 && $type !== 'lang' && isset( $vals[0] ) ) {
1056 } elseif ( count( $vals ) === 0 ) {
1057 wfDebug( __METHOD__
. " metadata array with 0 elements!\n" );
1059 return ""; // paranoia. This should never happen
1061 /* @todo FIXME: This should hide some of the list entries if there are
1062 * say more than four. Especially if a field is translated into 20
1063 * languages, we don't want to show them all by default
1067 // Display default, followed by ContentLanguage,
1068 // followed by the rest in no particular
1071 // Todo: hide some items if really long list.
1075 $priorityLanguages = $this->getPriorityLanguages();
1076 $defaultItem = false;
1077 $defaultLang = false;
1079 // If default is set, save it for later,
1080 // as we don't know if it's equal to
1081 // one of the lang codes. (In xmp
1082 // you specify the language for a
1083 // default property by having both
1084 // a default prop, and one in the language
1085 // that are identical)
1086 if ( isset( $vals['x-default'] ) ) {
1087 $defaultItem = $vals['x-default'];
1088 unset( $vals['x-default'] );
1090 foreach ( $priorityLanguages as $pLang ) {
1091 if ( isset( $vals[$pLang] ) ) {
1093 if ( $vals[$pLang] === $defaultItem ) {
1094 $defaultItem = false;
1097 $content .= $this->langItem(
1098 $vals[$pLang], $pLang,
1099 $isDefault, $noHtml );
1101 unset( $vals[$pLang] );
1103 if ( $this->singleLang
) {
1104 return Html
::rawElement( 'span',
1105 [ 'lang' => $pLang ], $vals[$pLang] );
1111 foreach ( $vals as $lang => $item ) {
1112 if ( $item === $defaultItem ) {
1113 $defaultLang = $lang;
1116 $content .= $this->langItem( $item,
1117 $lang, false, $noHtml );
1118 if ( $this->singleLang
) {
1119 return Html
::rawElement( 'span',
1120 [ 'lang' => $lang ], $item );
1123 if ( $defaultItem !== false ) {
1124 $content = $this->langItem( $defaultItem,
1125 $defaultLang, true, $noHtml ) .
1127 if ( $this->singleLang
) {
1128 return $defaultItem;
1135 return '<ul class="metadata-langlist">' .
1140 return "\n#" . implode( "\n#", $vals );
1143 return "<ol><li>" . implode( "</li>\n<li>", $vals ) . '</li></ol>';
1147 return "\n*" . implode( "\n*", $vals );
1150 return "<ul><li>" . implode( "</li>\n<li>", $vals ) . '</li></ul>';
1155 /** Helper function for creating lists of translations.
1157 * @param string $value Value (this is not escaped)
1158 * @param string $lang Lang code of item or false
1159 * @param bool $default If it is default value.
1160 * @param bool $noHtml If to avoid html (for back-compat)
1161 * @throws MWException
1162 * @return string Language item (Note: despite how this looks, this is
1163 * treated as wikitext, not as HTML).
1165 private function langItem( $value, $lang, $default = false, $noHtml = false ) {
1166 if ( $lang === false && $default === false ) {
1167 throw new MWException( '$lang and $default cannot both '
1172 $wrappedValue = $value;
1174 $wrappedValue = '<span class="mw-metadata-lang-value">'
1175 . $value . '</span>';
1178 if ( $lang === false ) {
1179 $msg = $this->msg( 'metadata-langitem-default', $wrappedValue );
1181 return $msg->text() . "\n\n";
1184 return '<li class="mw-metadata-lang-default">'
1189 $lowLang = strtolower( $lang );
1190 $langName = Language
::fetchLanguageName( $lowLang );
1191 if ( $langName === '' ) {
1192 // try just the base language name. (aka en-US -> en ).
1193 $langPrefix = explode( '-', $lowLang, 2 )[0];
1194 $langName = Language
::fetchLanguageName( $langPrefix );
1195 if ( $langName === '' ) {
1200 // else we have a language specified
1202 $msg = $this->msg( 'metadata-langitem', $wrappedValue, $langName, $lang );
1204 return '*' . $msg->text();
1207 $item = '<li class="mw-metadata-lang-code-'
1210 $item .= ' mw-metadata-lang-default';
1212 $item .= '" lang="' . $lang . '">';
1213 $item .= $msg->text();
1220 * Convenience function for getFormattedData()
1222 * @param string $tag The tag name to pass on
1223 * @param string $val The value of the tag
1224 * @param string $arg An argument to pass ($1)
1225 * @param string $arg2 A 2nd argument to pass ($2)
1226 * @return string The text content of "exif-$tag-$val" message in lower case
1228 private function exifMsg( $tag, $val, $arg = null, $arg2 = null ) {
1229 if ( $val === '' ) {
1234 MediaWikiServices
::getInstance()->getContentLanguage()->lc( "exif-$tag-$val" ),
1241 * Format a number, convert numbers from fractions into floating point
1242 * numbers, joins arrays of numbers with commas.
1244 * @param mixed $num The value to format
1245 * @param float|int|bool $round Digits to round to or false.
1246 * @return mixed A floating point number or whatever we were fed
1248 private function formatNum( $num, $round = false ) {
1250 if ( is_array( $num ) ) {
1252 foreach ( $num as $number ) {
1253 $out[] = $this->formatNum( $number );
1256 return $this->getLanguage()->commaList( $out );
1258 if ( preg_match( '/^(-?\d+)\/(\d+)$/', $num, $m ) ) {
1260 $newNum = $m[1] / $m[2];
1261 if ( $round !== false ) {
1262 $newNum = round( $newNum, $round );
1268 return $this->getLanguage()->formatNum( $newNum );
1270 if ( is_numeric( $num ) && $round !== false ) {
1271 $num = round( $num, $round );
1274 return $this->getLanguage()->formatNum( $num );
1279 * Format a rational number, reducing fractions
1281 * @param mixed $num The value to format
1282 * @return mixed A floating point number or whatever we were fed
1284 private function formatFraction( $num ) {
1286 if ( preg_match( '/^(-?\d+)\/(\d+)$/', $num, $m ) ) {
1287 $numerator = intval( $m[1] );
1288 $denominator = intval( $m[2] );
1289 $gcd = $this->gcd( abs( $numerator ), $denominator );
1291 // 0 shouldn't happen! ;)
1292 return $this->formatNum( $numerator / $gcd ) . '/' . $this->formatNum( $denominator / $gcd );
1296 return $this->formatNum( $num );
1300 * Calculate the greatest common divisor of two integers.
1302 * @param int $a Numerator
1303 * @param int $b Denominator
1306 private function gcd( $a, $b ) {
1308 // https://en.wikipedia.org/wiki/Euclidean_algorithm
1309 // Recursive form would be:
1313 return gcd( $b, $a % $b );
1316 $remainder = $a %
$b;
1318 // tail recursion...
1327 * Fetch the human readable version of a news code.
1328 * A news code is an 8 digit code. The first two
1329 * digits are a general classification, so we just
1332 * Note, leading 0's are significant, so this is
1333 * a string, not an int.
1335 * @param string $val The 8 digit news code.
1336 * @return string The human readable form
1338 private function convertNewsCode( $val ) {
1339 if ( !preg_match( '/^\d{8}$/D', $val ) ) {
1340 // Not a valid news code.
1344 switch ( substr( $val, 0, 2 ) ) {
1397 if ( $cat !== '' ) {
1398 $catMsg = $this->exifMsg( 'iimcategory', $cat );
1399 $val = $this->exifMsg( 'subjectnewscode', '', $val, $catMsg );
1406 * Format a coordinate value, convert numbers from floating point
1407 * into degree minute second representation.
1409 * @param int $coord Degrees, minutes and seconds
1410 * @param string $type Latitude or longitude (for if its a NWS or E)
1411 * @return mixed A floating point number or whatever we were fed
1413 private function formatCoords( $coord, $type ) {
1417 if ( $type === 'latitude' ) {
1419 } elseif ( $type === 'longitude' ) {
1424 if ( $type === 'latitude' ) {
1426 } elseif ( $type === 'longitude' ) {
1431 $deg = floor( $nCoord );
1432 $min = floor( ( $nCoord - $deg ) * 60.0 );
1433 $sec = round( ( ( $nCoord - $deg ) - $min / 60 ) * 3600, 2 );
1435 $deg = $this->formatNum( $deg );
1436 $min = $this->formatNum( $min );
1437 $sec = $this->formatNum( $sec );
1439 return $this->msg( 'exif-coordinate-format', $deg, $min, $sec, $ref, $coord )->text();
1443 * Format the contact info field into a single value.
1445 * This function might be called from
1446 * JpegHandler::convertMetadataVersion which is why it is
1449 * @param array $vals Array with fields of the ContactInfo
1450 * struct defined in the IPTC4XMP spec. Or potentially
1451 * an array with one element that is a free form text
1452 * value from the older iptc iim 1:118 prop.
1453 * @return string HTML-ish looking wikitext
1454 * @since 1.23 no longer static
1456 public function collapseContactInfo( $vals ) {
1457 if ( !( isset( $vals['CiAdrExtadr'] )
1458 ||
isset( $vals['CiAdrCity'] )
1459 ||
isset( $vals['CiAdrCtry'] )
1460 ||
isset( $vals['CiEmailWork'] )
1461 ||
isset( $vals['CiTelWork'] )
1462 ||
isset( $vals['CiAdrPcode'] )
1463 ||
isset( $vals['CiAdrRegion'] )
1464 ||
isset( $vals['CiUrlWork'] )
1466 // We don't have any sub-properties
1467 // This could happen if its using old
1468 // iptc that just had this as a free-form
1470 // Note: We run this through htmlspecialchars
1471 // partially to be consistent, and partially
1472 // because people often insert >, etc into
1473 // the metadata which should not be interpreted
1474 // but we still want to auto-link urls.
1475 foreach ( $vals as &$val ) {
1476 $val = htmlspecialchars( $val );
1479 return $this->flattenArrayReal( $vals );
1481 // We have a real ContactInfo field.
1482 // Its unclear if all these fields have to be
1483 // set, so assume they do not.
1484 $url = $tel = $street = $city = $country = '';
1485 $email = $postal = $region = '';
1487 // Also note, some of the class names this uses
1488 // are similar to those used by hCard. This is
1489 // mostly because they're sensible names. This
1490 // does not (and does not attempt to) output
1491 // stuff in the hCard microformat. However it
1492 // might output in the adr microformat.
1494 if ( isset( $vals['CiAdrExtadr'] ) ) {
1495 // Todo: This can potentially be multi-line.
1496 // Need to check how that works in XMP.
1497 $street = '<span class="extended-address">'
1499 $vals['CiAdrExtadr'] )
1502 if ( isset( $vals['CiAdrCity'] ) ) {
1503 $city = '<span class="locality">'
1504 . htmlspecialchars( $vals['CiAdrCity'] )
1507 if ( isset( $vals['CiAdrCtry'] ) ) {
1508 $country = '<span class="country-name">'
1509 . htmlspecialchars( $vals['CiAdrCtry'] )
1512 if ( isset( $vals['CiEmailWork'] ) ) {
1514 // Have to split multiple emails at commas/new lines.
1515 $splitEmails = explode( "\n", $vals['CiEmailWork'] );
1516 foreach ( $splitEmails as $e1 ) {
1517 // Also split on comma
1518 foreach ( explode( ',', $e1 ) as $e2 ) {
1519 $finalEmail = trim( $e2 );
1520 if ( $finalEmail == ',' ||
$finalEmail == '' ) {
1523 if ( strpos( $finalEmail, '<' ) !== false ) {
1524 // Don't do fancy formatting to
1525 // "My name" <foo@bar.com> style stuff
1526 $emails[] = $finalEmail;
1528 $emails[] = '[mailto:'
1530 . ' <span class="email">'
1536 $email = implode( ', ', $emails );
1538 if ( isset( $vals['CiTelWork'] ) ) {
1539 $tel = '<span class="tel">'
1540 . htmlspecialchars( $vals['CiTelWork'] )
1543 if ( isset( $vals['CiAdrPcode'] ) ) {
1544 $postal = '<span class="postal-code">'
1546 $vals['CiAdrPcode'] )
1549 if ( isset( $vals['CiAdrRegion'] ) ) {
1550 // Note this is province/state.
1551 $region = '<span class="region">'
1553 $vals['CiAdrRegion'] )
1556 if ( isset( $vals['CiUrlWork'] ) ) {
1557 $url = '<span class="url">'
1558 . htmlspecialchars( $vals['CiUrlWork'] )
1562 return $this->msg( 'exif-contact-value', $email, $url,
1563 $street, $city, $region, $postal, $country,
1569 * Get a list of fields that are visible by default.
1574 public static function getVisibleFields() {
1576 $lines = explode( "\n", wfMessage( 'metadata-fields' )->inContentLanguage()->text() );
1577 foreach ( $lines as $line ) {
1579 if ( preg_match( '/^\\*\s*(.*?)\s*$/', $line, $matches ) ) {
1580 $fields[] = $matches[1];
1583 $fields = array_map( 'strtolower', $fields );
1589 * Get an array of extended metadata. (See the imageinfo API for format.)
1591 * @param File $file File to use
1592 * @return array [<property name> => ['value' => <value>]], or [] on error
1595 public function fetchExtendedMetadata( File
$file ) {
1596 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1598 // If revision deleted, exit immediately
1599 if ( $file->isDeleted( File
::DELETED_FILE
) ) {
1603 $cacheKey = $cache->makeKey(
1604 'getExtendedMetadata',
1605 $this->getLanguage()->getCode(),
1606 (int)$this->singleLang
,
1610 $cachedValue = $cache->get( $cacheKey );
1613 && Hooks
::run( 'ValidateExtendedMetadataCache', [ $cachedValue['timestamp'], $file ] )
1615 $extendedMetadata = $cachedValue['data'];
1617 $maxCacheTime = ( $file instanceof ForeignAPIFile
) ?
60 * 60 * 12 : 60 * 60 * 24 * 30;
1618 $fileMetadata = $this->getExtendedMetadataFromFile( $file );
1619 $extendedMetadata = $this->getExtendedMetadataFromHook( $file, $fileMetadata, $maxCacheTime );
1620 if ( $this->singleLang
) {
1621 $this->resolveMultilangMetadata( $extendedMetadata );
1623 $this->discardMultipleValues( $extendedMetadata );
1624 // Make sure the metadata won't break the API when an XML format is used.
1625 // This is an API-specific function so it would be cleaner to call it from
1626 // outside fetchExtendedMetadata, but this way we don't need to redo the
1627 // computation on a cache hit.
1628 $this->sanitizeArrayForAPI( $extendedMetadata );
1629 $valueToCache = [ 'data' => $extendedMetadata, 'timestamp' => wfTimestampNow() ];
1630 $cache->set( $cacheKey, $valueToCache, $maxCacheTime );
1633 return $extendedMetadata;
1637 * Get file-based metadata in standardized format.
1639 * Note that for a remote file, this might return metadata supplied by extensions.
1641 * @param File $file File to use
1642 * @return array [<property name> => ['value' => <value>]], or [] on error
1645 protected function getExtendedMetadataFromFile( File
$file ) {
1646 // If this is a remote file accessed via an API request, we already
1647 // have remote metadata so we just ignore any local one
1648 if ( $file instanceof ForeignAPIFile
) {
1649 // In case of error we pretend no metadata - this will get cached.
1650 // Might or might not be a good idea.
1651 return $file->getExtendedMetadata() ?
: [];
1654 $uploadDate = wfTimestamp( TS_ISO_8601
, $file->getTimestamp() );
1657 // This is modification time, which is close to "upload" time.
1659 'value' => $uploadDate,
1660 'source' => 'mediawiki-metadata',
1664 $title = $file->getTitle();
1666 $text = $title->getText();
1667 $pos = strrpos( $text, '.' );
1670 $name = substr( $text, 0, $pos );
1675 $fileMetadata['ObjectName'] = [
1677 'source' => 'mediawiki-metadata',
1681 return $fileMetadata;
1685 * Get additional metadata from hooks in standardized format.
1687 * @param File $file File to use
1688 * @param array $extendedMetadata
1689 * @param int &$maxCacheTime Hook handlers might use this parameter to override cache time
1691 * @return array [<property name> => ['value' => <value>]], or [] on error
1694 protected function getExtendedMetadataFromHook( File
$file, array $extendedMetadata,
1697 Hooks
::run( 'GetExtendedMetadata', [
1700 $this->getContext(),
1705 $visible = array_flip( self
::getVisibleFields() );
1706 foreach ( $extendedMetadata as $key => $value ) {
1707 if ( !isset( $visible[strtolower( $key )] ) ) {
1708 $extendedMetadata[$key]['hidden'] = '';
1712 return $extendedMetadata;
1716 * Turns an XMP-style multilang array into a single value.
1717 * If the value is not a multilang array, it is returned unchanged.
1718 * See mediawiki.org/wiki/Manual:File_metadata_handling#Multi-language_array_format
1719 * @param mixed $value
1720 * @return mixed Value in best language, null if there were no languages at all
1723 protected function resolveMultilangValue( $value ) {
1726 ||
!isset( $value['_type'] )
1727 ||
$value['_type'] != 'lang'
1729 return $value; // do nothing if not a multilang array
1732 // choose the language best matching user or site settings
1733 $priorityLanguages = $this->getPriorityLanguages();
1734 foreach ( $priorityLanguages as $lang ) {
1735 if ( isset( $value[$lang] ) ) {
1736 return $value[$lang];
1740 // otherwise go with the default language, if set
1741 if ( isset( $value['x-default'] ) ) {
1742 return $value['x-default'];
1745 // otherwise just return any one language
1746 unset( $value['_type'] );
1747 if ( !empty( $value ) ) {
1748 return reset( $value );
1751 // this should not happen; signal error
1756 * Turns an XMP-style multivalue array into a single value by dropping all but the first
1757 * value. If the value is not a multivalue array (or a multivalue array inside a multilang
1758 * array), it is returned unchanged.
1759 * See mediawiki.org/wiki/Manual:File_metadata_handling#Multi-language_array_format
1760 * @param mixed $value
1761 * @return mixed The value, or the first value if there were multiple ones
1764 protected function resolveMultivalueValue( $value ) {
1765 if ( !is_array( $value ) ) {
1767 } elseif ( isset( $value['_type'] ) && $value['_type'] === 'lang' ) {
1768 // if this is a multilang array, process fields separately
1770 foreach ( $value as $k => $v ) {
1771 $newValue[$k] = $this->resolveMultivalueValue( $v );
1774 } else { // _type is 'ul' or 'ol' or missing in which case it defaults to 'ul'
1775 $v = reset( $value );
1776 if ( key( $value ) === '_type' ) {
1777 $v = next( $value );
1784 * Takes an array returned by the getExtendedMetadata* functions,
1785 * and resolves multi-language values in it.
1786 * @param array &$metadata
1789 protected function resolveMultilangMetadata( &$metadata ) {
1790 if ( !is_array( $metadata ) ) {
1793 foreach ( $metadata as &$field ) {
1794 if ( isset( $field['value'] ) ) {
1795 $field['value'] = $this->resolveMultilangValue( $field['value'] );
1801 * Takes an array returned by the getExtendedMetadata* functions,
1802 * and turns all fields into single-valued ones by dropping extra values.
1803 * @param array &$metadata
1806 protected function discardMultipleValues( &$metadata ) {
1807 if ( !is_array( $metadata ) ) {
1810 foreach ( $metadata as $key => &$field ) {
1811 if ( $key === 'Software' ||
$key === 'Contact' ) {
1812 // we skip some fields which have composite values. They are not particularly interesting
1813 // and you can get them via the metadata / commonmetadata APIs anyway.
1816 if ( isset( $field['value'] ) ) {
1817 $field['value'] = $this->resolveMultivalueValue( $field['value'] );
1823 * Makes sure the given array is a valid API response fragment
1824 * @param array &$arr
1826 protected function sanitizeArrayForAPI( &$arr ) {
1827 if ( !is_array( $arr ) ) {
1832 foreach ( $arr as $key => &$value ) {
1833 $sanitizedKey = $this->sanitizeKeyForAPI( $key );
1834 if ( $sanitizedKey !== $key ) {
1835 if ( isset( $arr[$sanitizedKey] ) ) {
1836 // Make the sanitized keys hopefully unique.
1837 // To make it definitely unique would be too much effort, given that
1838 // sanitizing is only needed for misformatted metadata anyway, but
1839 // this at least covers the case when $arr is numeric.
1840 $sanitizedKey .= $counter;
1843 $arr[$sanitizedKey] = $arr[$key];
1844 unset( $arr[$key] );
1846 if ( is_array( $value ) ) {
1847 $this->sanitizeArrayForAPI( $value );
1851 // Handle API metadata keys (particularly "_type")
1852 $keys = array_filter( array_keys( $arr ), 'ApiResult::isMetadataKey' );
1854 ApiResult
::setPreserveKeysList( $arr, $keys );
1859 * Turns a string into a valid API identifier.
1860 * @param string $key
1864 protected function sanitizeKeyForAPI( $key ) {
1865 // drop all characters which are not valid in an XML tag name
1866 // a bunch of non-ASCII letters would be valid but probably won't
1867 // be used so we take the easy way
1868 $key = preg_replace( '/[^a-zA-z0-9_:.\-]/', '', $key );
1869 // drop characters which are invalid at the first position
1870 $key = preg_replace( '/^[\d\-.]+/', '', $key );
1876 // special case for an internal keyword
1877 if ( $key == '_element' ) {
1885 * Returns a list of languages (first is best) to use when formatting multilang fields,
1886 * based on user and site preferences.
1890 protected function getPriorityLanguages() {
1891 $priorityLanguages =
1892 Language
::getFallbacksIncludingSiteLanguage( $this->getLanguage()->getCode() );
1893 $priorityLanguages = array_merge(
1894 (array)$this->getLanguage()->getCode(),
1895 $priorityLanguages[0],
1896 $priorityLanguages[1]
1899 return $priorityLanguages;