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 http://www.gnu.org/copyleft/gpl.html GNU General Public License
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 )
102 public function makeFormattedData( $tags ) {
103 $resolutionunit = !isset( $tags['ResolutionUnit'] ) ||
$tags['ResolutionUnit'] == 2 ?
2 : 3;
104 unset( $tags['ResolutionUnit'] );
105 // Width and height are for internal use and already available & displayed outside of metadata
106 unset( $tags['Width'] );
107 unset( $tags['Height'] );
109 foreach ( $tags as $tag => &$vals ) {
110 // This seems ugly to wrap non-array's in an array just to unwrap again,
111 // especially when most of the time it is not an array
112 if ( !is_array( $tags[$tag] ) ) {
116 // _type is a special value to say what array type
117 if ( isset( $tags[$tag]['_type'] ) ) {
118 $type = $tags[$tag]['_type'];
119 unset( $vals['_type'] );
121 $type = 'ul'; // default unordered list.
124 // This is done differently as the tag is an array.
125 if ( $tag == 'GPSTimeStamp' && count( $vals ) === 3 ) {
126 // hour min sec array
128 $h = explode( '/', $vals[0] );
129 $m = explode( '/', $vals[1] );
130 $s = explode( '/', $vals[2] );
132 // this should already be validated
133 // when loaded from file, but it could
134 // come from a foreign repo, so be
145 $tags[$tag] = str_pad( intval( $h[0] / $h[1] ), 2, '0', STR_PAD_LEFT
)
146 . ':' . str_pad( intval( $m[0] / $m[1] ), 2, '0', STR_PAD_LEFT
)
147 . ':' . str_pad( intval( $s[0] / $s[1] ), 2, '0', STR_PAD_LEFT
);
150 $time = wfTimestamp( TS_MW
, '1971:01:01 ' . $tags[$tag] );
151 // the 1971:01:01 is just a placeholder, and not shown to user.
152 if ( $time && intval( $time ) > 0 ) {
153 $tags[$tag] = $this->getLanguage()->time( $time );
155 } catch ( TimestampException
$e ) {
156 // This shouldn't happen, but we've seen bad formats
157 // such as 4-digit seconds in the wild.
158 // leave $tags[$tag] as-is
163 // The contact info is a multi-valued field
164 // instead of the other props which are single
165 // valued (mostly) so handle as a special case.
166 if ( $tag === 'Contact' ) {
167 $vals = $this->collapseContactInfo( $vals );
171 foreach ( $vals as &$val ) {
186 $val = $this->exifMsg( $tag, $val );
189 /* If not recognized, display as is. */
194 case 'PhotometricInterpretation':
208 $val = $this->exifMsg( $tag, $val );
211 /* If not recognized, display as is. */
226 $val = $this->exifMsg( $tag, $val );
229 /* If not recognized, display as is. */
234 case 'PlanarConfiguration':
238 $val = $this->exifMsg( $tag, $val );
241 /* If not recognized, display as is. */
246 // TODO: YCbCrSubSampling
247 case 'YCbCrPositioning':
251 $val = $this->exifMsg( $tag, $val );
254 /* If not recognized, display as is. */
261 switch ( $resolutionunit ) {
263 $val = $this->exifMsg( 'XYResolution', 'i', $this->formatNum( $val ) );
266 $val = $this->exifMsg( 'XYResolution', 'c', $this->formatNum( $val ) );
269 /* If not recognized, display as is. */
274 // TODO: YCbCrCoefficients #p27 (see annex E)
276 case 'FlashpixVersion':
284 $val = $this->exifMsg( $tag, $val );
287 /* If not recognized, display as is. */
292 case 'ComponentsConfiguration':
301 $val = $this->exifMsg( $tag, $val );
304 /* If not recognized, display as is. */
310 case 'DateTimeOriginal':
311 case 'DateTimeDigitized':
312 case 'DateTimeReleased':
313 case 'DateTimeExpires':
316 case 'DateTimeMetadata':
317 if ( $val == '0000:00:00 00:00:00' ||
$val == ' : : : : ' ) {
318 $val = $this->msg( 'exif-unknowndate' )->text();
319 } elseif ( preg_match(
320 '/^(?:\d{4}):(?:\d\d):(?:\d\d) (?:\d\d):(?:\d\d):(?:\d\d)$/D',
324 $time = wfTimestamp( TS_MW
, $val );
325 if ( $time && intval( $time ) > 0 ) {
326 $val = $this->getLanguage()->timeanddate( $time );
328 } elseif ( preg_match( '/^(?:\d{4}):(?:\d\d):(?:\d\d) (?:\d\d):(?:\d\d)$/D', $val ) ) {
329 // No second field. Still format the same
330 // since timeanddate doesn't include seconds anyways,
331 // but second still available in api
332 $time = wfTimestamp( TS_MW
, $val . ':00' );
333 if ( $time && intval( $time ) > 0 ) {
334 $val = $this->getLanguage()->timeanddate( $time );
336 } elseif ( preg_match( '/^(?:\d{4}):(?:\d\d):(?:\d\d)$/D', $val ) ) {
337 // If only the date but not the time is filled in.
338 $time = wfTimestamp( TS_MW
, substr( $val, 0, 4 )
339 . substr( $val, 5, 2 )
340 . substr( $val, 8, 2 )
342 if ( $time && intval( $time ) > 0 ) {
343 $val = $this->getLanguage()->date( $time );
346 // else it will just output $val without formatting it.
349 case 'ExposureProgram':
360 $val = $this->exifMsg( $tag, $val );
363 /* If not recognized, display as is. */
368 case 'SubjectDistance':
369 $val = $this->exifMsg( $tag, '', $this->formatNum( $val ) );
383 $val = $this->exifMsg( $tag, $val );
386 /* If not recognized, display as is. */
414 $val = $this->exifMsg( $tag, $val );
417 /* If not recognized, display as is. */
424 'fired' => $val & 0b00000001
,
425 'return' => ( $val & 0b00000110
) >> 1,
426 'mode' => ( $val & 0b00011000
) >> 3,
427 'function' => ( $val & 0b00100000
) >> 5,
428 'redeye' => ( $val & 0b01000000
) >> 6,
429 // 'reserved' => ( $val & 0b10000000 ) >> 7,
432 # We do not need to handle unknown values since all are used.
433 foreach ( $flashDecode as $subTag => $subValue ) {
434 # We do not need any message for zeroed values.
435 if ( $subTag != 'fired' && $subValue == 0 ) {
438 $fullTag = $tag . '-' . $subTag;
439 $flashMsgs[] = $this->exifMsg( $fullTag, $subValue );
441 $val = $this->getLanguage()->commaList( $flashMsgs );
444 case 'FocalPlaneResolutionUnit':
447 $val = $this->exifMsg( $tag, $val );
450 /* If not recognized, display as is. */
455 case 'SensingMethod':
464 $val = $this->exifMsg( $tag, $val );
467 /* If not recognized, display as is. */
475 $val = $this->exifMsg( $tag, $val );
478 /* If not recognized, display as is. */
486 $val = $this->exifMsg( $tag, $val );
489 /* If not recognized, display as is. */
494 case 'CustomRendered':
498 $val = $this->exifMsg( $tag, $val );
501 /* If not recognized, display as is. */
511 $val = $this->exifMsg( $tag, $val );
514 /* If not recognized, display as is. */
523 $val = $this->exifMsg( $tag, $val );
526 /* If not recognized, display as is. */
531 case 'SceneCaptureType':
537 $val = $this->exifMsg( $tag, $val );
540 /* If not recognized, display as is. */
552 $val = $this->exifMsg( $tag, $val );
555 /* If not recognized, display as is. */
565 $val = $this->exifMsg( $tag, $val );
568 /* If not recognized, display as is. */
578 $val = $this->exifMsg( $tag, $val );
581 /* If not recognized, display as is. */
591 $val = $this->exifMsg( $tag, $val );
594 /* If not recognized, display as is. */
599 case 'SubjectDistanceRange':
605 $val = $this->exifMsg( $tag, $val );
608 /* If not recognized, display as is. */
613 // The GPS...Ref values are kept for compatibility, probably won't be reached.
614 case 'GPSLatitudeRef':
615 case 'GPSDestLatitudeRef':
619 $val = $this->exifMsg( 'GPSLatitude', $val );
622 /* If not recognized, display as is. */
627 case 'GPSLongitudeRef':
628 case 'GPSDestLongitudeRef':
632 $val = $this->exifMsg( 'GPSLongitude', $val );
635 /* If not recognized, display as is. */
642 $val = $this->exifMsg( 'GPSAltitude', 'below-sealevel', $this->formatNum( -$val, 3 ) );
644 $val = $this->exifMsg( 'GPSAltitude', 'above-sealevel', $this->formatNum( $val, 3 ) );
652 $val = $this->exifMsg( $tag, $val );
655 /* If not recognized, display as is. */
660 case 'GPSMeasureMode':
664 $val = $this->exifMsg( $tag, $val );
667 /* If not recognized, display as is. */
673 case 'GPSImgDirectionRef':
674 case 'GPSDestBearingRef':
678 $val = $this->exifMsg( 'GPSDirection', $val );
681 /* If not recognized, display as is. */
687 case 'GPSDestLatitude':
688 $val = $this->formatCoords( $val, 'latitude' );
691 case 'GPSDestLongitude':
692 $val = $this->formatCoords( $val, 'longitude' );
700 $val = $this->exifMsg( 'GPSSpeed', $val );
703 /* If not recognized, display as is. */
708 case 'GPSDestDistanceRef':
713 $val = $this->exifMsg( 'GPSDestDistance', $val );
716 /* If not recognized, display as is. */
722 // See https://en.wikipedia.org/wiki/Dilution_of_precision_(GPS)
724 $val = $this->exifMsg( $tag, 'excellent', $this->formatNum( $val ) );
725 } elseif ( $val <= 5 ) {
726 $val = $this->exifMsg( $tag, 'good', $this->formatNum( $val ) );
727 } elseif ( $val <= 10 ) {
728 $val = $this->exifMsg( $tag, 'moderate', $this->formatNum( $val ) );
729 } elseif ( $val <= 20 ) {
730 $val = $this->exifMsg( $tag, 'fair', $this->formatNum( $val ) );
732 $val = $this->exifMsg( $tag, 'poor', $this->formatNum( $val ) );
736 // This is not in the Exif standard, just a special
737 // case for our purposes which enables wikis to wikify
738 // the make, model and software name to link to their articles.
741 $val = $this->exifMsg( $tag, '', $val );
745 if ( is_array( $val ) ) {
746 // if its a software, version array.
747 $val = $this->msg( 'exif-software-version-value', $val[0], $val[1] )->text();
749 $val = $this->exifMsg( $tag, '', $val );
754 // Show the pretty fraction as well as decimal version
755 $val = $this->msg( 'exif-exposuretime-format',
756 $this->formatFraction( $val ), $this->formatNum( $val ) )->text();
758 case 'ISOSpeedRatings':
759 // If its = 65535 that means its at the
760 // limit of the size of Exif::short and
762 if ( $val == '65535' ) {
763 $val = $this->exifMsg( $tag, 'overflow' );
765 $val = $this->formatNum( $val );
769 $val = $this->msg( 'exif-fnumber-format',
770 $this->formatNum( $val ) )->text();
774 case 'FocalLengthIn35mmFilm':
775 $val = $this->msg( 'exif-focallength-format',
776 $this->formatNum( $val ) )->text();
779 case 'MaxApertureValue':
780 if ( strpos( $val, '/' ) !== false ) {
781 // need to expand this earlier to calculate fNumber
782 list( $n, $d ) = explode( '/', $val );
783 if ( is_numeric( $n ) && is_numeric( $d ) ) {
787 if ( is_numeric( $val ) ) {
788 $fNumber = pow( 2, $val / 2 );
789 if ( $fNumber !== false ) {
790 $val = $this->msg( 'exif-maxaperturevalue-value',
791 $this->formatNum( $val ),
792 $this->formatNum( $fNumber, 2 )
799 switch ( strtolower( $val ) ) {
800 // See pg 29 of IPTC photo
801 // metadata standard.
819 $val = $this->exifMsg(
825 case 'SubjectNewsCode':
826 // Essentially like iimCategory.
827 // 8 (numeric) digit hierarchical
828 // classification. We decode the
829 // first 2 digits, which provide
831 $val = $this->convertNewsCode( $val );
834 // 1-8 with 1 being highest, 5 normal
835 // 0 is reserved, and 9 is 'user-defined'.
837 if ( $val == 0 ||
$val == 9 ) {
839 } elseif ( $val < 5 && $val > 1 ) {
841 } elseif ( $val == 5 ) {
843 } elseif ( $val <= 8 && $val > 5 ) {
847 if ( $urgency !== '' ) {
848 $val = $this->exifMsg( 'urgency',
854 // Things that have a unit of pixels.
855 case 'OriginalImageHeight':
856 case 'OriginalImageWidth':
857 case 'PixelXDimension':
858 case 'PixelYDimension':
861 $val = $this->formatNum( $val ) . ' ' . $this->msg( 'unit-pixel' )->text();
864 // Do not transform fields with pure text.
865 // For some languages the formatNum()
866 // conversion results to wrong output like
867 // foo,bar@example,com or foo٫bar@example٫com.
868 // Also some 'numeric' things like Scene codes
869 // are included here as we really don't want
871 case 'ImageDescription':
875 case 'RelatedSoundFile':
876 case 'ImageUniqueID':
877 case 'SpectralSensitivity':
878 case 'GPSSatellites':
882 case 'WorldRegionDest':
884 case 'CountryCodeDest':
885 case 'ProvinceOrStateDest':
887 case 'SublocationDest':
888 case 'WorldRegionCreated':
889 case 'CountryCreated':
890 case 'CountryCodeCreated':
891 case 'ProvinceOrStateCreated':
893 case 'SublocationCreated':
895 case 'SpecialInstructions':
900 case 'FixtureIdentifier':
902 case 'LocationDestCode':
904 case 'JPEGFileComment':
905 case 'iimSupplementalCategory':
906 case 'OriginalTransmissionRef':
908 case 'dc-contributor':
917 case 'CameraOwnerName':
920 case 'RightsCertificate':
921 case 'CopyrightOwner':
924 case 'OriginalDocumentID':
926 case 'MorePermissionsUrl':
927 case 'AttributionUrl':
928 case 'PreferredAttributionName':
929 case 'PNGFileComment':
931 case 'ContentWarning':
932 case 'GIFFileComment':
934 case 'IntellectualGenre':
936 case 'OrginisationInImage':
937 case 'PersonInImage':
939 $val = htmlspecialchars( $val );
947 $val = $this->exifMsg( $tag, $val );
950 $val = htmlspecialchars( $val );
958 $val = $this->exifMsg( $tag, $val );
963 if ( $val == '-1' ) {
964 $val = $this->exifMsg( $tag, 'rejected' );
966 $val = $this->formatNum( $val );
971 $lang = Language
::fetchLanguageName( strtolower( $val ), $this->getLanguage()->getCode() );
973 $val = htmlspecialchars( $lang );
975 $val = htmlspecialchars( $val );
980 $val = $this->formatNum( $val );
984 // End formatting values, start flattening arrays.
985 $vals = $this->flattenArrayReal( $vals, $type );
992 * Flatten an array, using the content language for any messages.
994 * @param array $vals Array of values
995 * @param string $type Type of array (either lang, ul, ol).
996 * lang = language assoc array with keys being the lang code
997 * ul = unordered list, ol = ordered list
998 * type can also come from the '_type' member of $vals.
999 * @param bool $noHtml If to avoid returning anything resembling HTML.
1000 * (Ugly hack for backwards compatibility with old MediaWiki).
1001 * @param bool|IContextSource $context
1002 * @return string Single value (in wiki-syntax).
1005 public static function flattenArrayContentLang( $vals, $type = 'ul',
1006 $noHtml = false, $context = false
1009 $obj = new FormatMetadata
;
1011 $obj->setContext( $context );
1013 $context = new DerivativeContext( $obj->getContext() );
1014 $context->setLanguage( $wgContLang );
1015 $obj->setContext( $context );
1017 return $obj->flattenArrayReal( $vals, $type, $noHtml );
1021 * A function to collapse multivalued tags into a single value.
1022 * This turns an array of (for example) authors into a bulleted list.
1024 * This is public on the basis it might be useful outside of this class.
1026 * @param array $vals Array of values
1027 * @param string $type Type of array (either lang, ul, ol).
1028 * lang = language assoc array with keys being the lang code
1029 * ul = unordered list, ol = ordered list
1030 * type can also come from the '_type' member of $vals.
1031 * @param bool $noHtml If to avoid returning anything resembling HTML.
1032 * (Ugly hack for backwards compatibility with old mediawiki).
1033 * @return string Single value (in wiki-syntax).
1036 public function flattenArrayReal( $vals, $type = 'ul', $noHtml = false ) {
1037 if ( !is_array( $vals ) ) {
1038 return $vals; // do nothing if not an array;
1041 if ( isset( $vals['_type'] ) ) {
1042 $type = $vals['_type'];
1043 unset( $vals['_type'] );
1046 if ( !is_array( $vals ) ) {
1047 return $vals; // do nothing if not an array;
1048 } elseif ( count( $vals ) === 1 && $type !== 'lang' ) {
1050 } elseif ( count( $vals ) === 0 ) {
1051 wfDebug( __METHOD__
. " metadata array with 0 elements!\n" );
1053 return ""; // paranoia. This should never happen
1055 /* @todo FIXME: This should hide some of the list entries if there are
1056 * say more than four. Especially if a field is translated into 20
1057 * languages, we don't want to show them all by default
1061 // Display default, followed by ContLang,
1062 // followed by the rest in no particular
1065 // Todo: hide some items if really long list.
1069 $priorityLanguages = $this->getPriorityLanguages();
1070 $defaultItem = false;
1071 $defaultLang = false;
1073 // If default is set, save it for later,
1074 // as we don't know if it's equal to
1075 // one of the lang codes. (In xmp
1076 // you specify the language for a
1077 // default property by having both
1078 // a default prop, and one in the language
1079 // that are identical)
1080 if ( isset( $vals['x-default'] ) ) {
1081 $defaultItem = $vals['x-default'];
1082 unset( $vals['x-default'] );
1084 foreach ( $priorityLanguages as $pLang ) {
1085 if ( isset( $vals[$pLang] ) ) {
1087 if ( $vals[$pLang] === $defaultItem ) {
1088 $defaultItem = false;
1091 $content .= $this->langItem(
1092 $vals[$pLang], $pLang,
1093 $isDefault, $noHtml );
1095 unset( $vals[$pLang] );
1097 if ( $this->singleLang
) {
1098 return Html
::rawElement( 'span',
1099 [ 'lang' => $pLang ], $vals[$pLang] );
1105 foreach ( $vals as $lang => $item ) {
1106 if ( $item === $defaultItem ) {
1107 $defaultLang = $lang;
1110 $content .= $this->langItem( $item,
1111 $lang, false, $noHtml );
1112 if ( $this->singleLang
) {
1113 return Html
::rawElement( 'span',
1114 [ 'lang' => $lang ], $item );
1117 if ( $defaultItem !== false ) {
1118 $content = $this->langItem( $defaultItem,
1119 $defaultLang, true, $noHtml ) .
1121 if ( $this->singleLang
) {
1122 return $defaultItem;
1129 return '<ul class="metadata-langlist">' .
1134 return "\n#" . implode( "\n#", $vals );
1137 return "<ol><li>" . implode( "</li>\n<li>", $vals ) . '</li></ol>';
1141 return "\n*" . implode( "\n*", $vals );
1144 return "<ul><li>" . implode( "</li>\n<li>", $vals ) . '</li></ul>';
1149 /** Helper function for creating lists of translations.
1151 * @param string $value Value (this is not escaped)
1152 * @param string $lang Lang code of item or false
1153 * @param bool $default If it is default value.
1154 * @param bool $noHtml If to avoid html (for back-compat)
1155 * @throws MWException
1156 * @return string Language item (Note: despite how this looks, this is
1157 * treated as wikitext, not as HTML).
1159 private function langItem( $value, $lang, $default = false, $noHtml = false ) {
1160 if ( $lang === false && $default === false ) {
1161 throw new MWException( '$lang and $default cannot both '
1166 $wrappedValue = $value;
1168 $wrappedValue = '<span class="mw-metadata-lang-value">'
1169 . $value . '</span>';
1172 if ( $lang === false ) {
1173 $msg = $this->msg( 'metadata-langitem-default', $wrappedValue );
1175 return $msg->text() . "\n\n";
1178 return '<li class="mw-metadata-lang-default">'
1183 $lowLang = strtolower( $lang );
1184 $langName = Language
::fetchLanguageName( $lowLang );
1185 if ( $langName === '' ) {
1186 // try just the base language name. (aka en-US -> en ).
1187 list( $langPrefix ) = explode( '-', $lowLang, 2 );
1188 $langName = Language
::fetchLanguageName( $langPrefix );
1189 if ( $langName === '' ) {
1194 // else we have a language specified
1196 $msg = $this->msg( 'metadata-langitem', $wrappedValue, $langName, $lang );
1198 return '*' . $msg->text();
1201 $item = '<li class="mw-metadata-lang-code-'
1204 $item .= ' mw-metadata-lang-default';
1206 $item .= '" lang="' . $lang . '">';
1207 $item .= $msg->text();
1214 * Convenience function for getFormattedData()
1216 * @param string $tag The tag name to pass on
1217 * @param string $val The value of the tag
1218 * @param string $arg An argument to pass ($1)
1219 * @param string $arg2 A 2nd argument to pass ($2)
1220 * @return string The text content of "exif-$tag-$val" message in lower case
1222 private function exifMsg( $tag, $val, $arg = null, $arg2 = null ) {
1225 if ( $val === '' ) {
1229 return $this->msg( $wgContLang->lc( "exif-$tag-$val" ), $arg, $arg2 )->text();
1233 * Format a number, convert numbers from fractions into floating point
1234 * numbers, joins arrays of numbers with commas.
1236 * @param mixed $num The value to format
1237 * @param float|int|bool $round Digits to round to or false.
1238 * @return mixed A floating point number or whatever we were fed
1240 private function formatNum( $num, $round = false ) {
1242 if ( is_array( $num ) ) {
1244 foreach ( $num as $number ) {
1245 $out[] = $this->formatNum( $number );
1248 return $this->getLanguage()->commaList( $out );
1250 if ( preg_match( '/^(-?\d+)\/(\d+)$/', $num, $m ) ) {
1252 $newNum = $m[1] / $m[2];
1253 if ( $round !== false ) {
1254 $newNum = round( $newNum, $round );
1260 return $this->getLanguage()->formatNum( $newNum );
1262 if ( is_numeric( $num ) && $round !== false ) {
1263 $num = round( $num, $round );
1266 return $this->getLanguage()->formatNum( $num );
1271 * Format a rational number, reducing fractions
1273 * @param mixed $num The value to format
1274 * @return mixed A floating point number or whatever we were fed
1276 private function formatFraction( $num ) {
1278 if ( preg_match( '/^(-?\d+)\/(\d+)$/', $num, $m ) ) {
1279 $numerator = intval( $m[1] );
1280 $denominator = intval( $m[2] );
1281 $gcd = $this->gcd( abs( $numerator ), $denominator );
1283 // 0 shouldn't happen! ;)
1284 return $this->formatNum( $numerator / $gcd ) . '/' . $this->formatNum( $denominator / $gcd );
1288 return $this->formatNum( $num );
1292 * Calculate the greatest common divisor of two integers.
1294 * @param int $a Numerator
1295 * @param int $b Denominator
1298 private function gcd( $a, $b ) {
1300 // https://en.wikipedia.org/wiki/Euclidean_algorithm
1301 // Recursive form would be:
1305 return gcd( $b, $a % $b );
1308 $remainder = $a %
$b;
1310 // tail recursion...
1319 * Fetch the human readable version of a news code.
1320 * A news code is an 8 digit code. The first two
1321 * digits are a general classification, so we just
1324 * Note, leading 0's are significant, so this is
1325 * a string, not an int.
1327 * @param string $val The 8 digit news code.
1328 * @return string The human readable form
1330 private function convertNewsCode( $val ) {
1331 if ( !preg_match( '/^\d{8}$/D', $val ) ) {
1332 // Not a valid news code.
1336 switch ( substr( $val, 0, 2 ) ) {
1389 if ( $cat !== '' ) {
1390 $catMsg = $this->exifMsg( 'iimcategory', $cat );
1391 $val = $this->exifMsg( 'subjectnewscode', '', $val, $catMsg );
1398 * Format a coordinate value, convert numbers from floating point
1399 * into degree minute second representation.
1401 * @param int $coord Degrees, minutes and seconds
1402 * @param string $type Latitude or longitude (for if its a NWS or E)
1403 * @return mixed A floating point number or whatever we were fed
1405 private function formatCoords( $coord, $type ) {
1409 if ( $type === 'latitude' ) {
1411 } elseif ( $type === 'longitude' ) {
1416 if ( $type === 'latitude' ) {
1418 } elseif ( $type === 'longitude' ) {
1423 $deg = floor( $nCoord );
1424 $min = floor( ( $nCoord - $deg ) * 60.0 );
1425 $sec = round( ( ( $nCoord - $deg ) - $min / 60 ) * 3600, 2 );
1427 $deg = $this->formatNum( $deg );
1428 $min = $this->formatNum( $min );
1429 $sec = $this->formatNum( $sec );
1431 return $this->msg( 'exif-coordinate-format', $deg, $min, $sec, $ref, $coord )->text();
1435 * Format the contact info field into a single value.
1437 * This function might be called from
1438 * JpegHandler::convertMetadataVersion which is why it is
1441 * @param array $vals Array with fields of the ContactInfo
1442 * struct defined in the IPTC4XMP spec. Or potentially
1443 * an array with one element that is a free form text
1444 * value from the older iptc iim 1:118 prop.
1445 * @return string HTML-ish looking wikitext
1446 * @since 1.23 no longer static
1448 public function collapseContactInfo( $vals ) {
1449 if ( !( isset( $vals['CiAdrExtadr'] )
1450 ||
isset( $vals['CiAdrCity'] )
1451 ||
isset( $vals['CiAdrCtry'] )
1452 ||
isset( $vals['CiEmailWork'] )
1453 ||
isset( $vals['CiTelWork'] )
1454 ||
isset( $vals['CiAdrPcode'] )
1455 ||
isset( $vals['CiAdrRegion'] )
1456 ||
isset( $vals['CiUrlWork'] )
1458 // We don't have any sub-properties
1459 // This could happen if its using old
1460 // iptc that just had this as a free-form
1462 // Note: We run this through htmlspecialchars
1463 // partially to be consistent, and partially
1464 // because people often insert >, etc into
1465 // the metadata which should not be interpreted
1466 // but we still want to auto-link urls.
1467 foreach ( $vals as &$val ) {
1468 $val = htmlspecialchars( $val );
1471 return $this->flattenArrayReal( $vals );
1473 // We have a real ContactInfo field.
1474 // Its unclear if all these fields have to be
1475 // set, so assume they do not.
1476 $url = $tel = $street = $city = $country = '';
1477 $email = $postal = $region = '';
1479 // Also note, some of the class names this uses
1480 // are similar to those used by hCard. This is
1481 // mostly because they're sensible names. This
1482 // does not (and does not attempt to) output
1483 // stuff in the hCard microformat. However it
1484 // might output in the adr microformat.
1486 if ( isset( $vals['CiAdrExtadr'] ) ) {
1487 // Todo: This can potentially be multi-line.
1488 // Need to check how that works in XMP.
1489 $street = '<span class="extended-address">'
1491 $vals['CiAdrExtadr'] )
1494 if ( isset( $vals['CiAdrCity'] ) ) {
1495 $city = '<span class="locality">'
1496 . htmlspecialchars( $vals['CiAdrCity'] )
1499 if ( isset( $vals['CiAdrCtry'] ) ) {
1500 $country = '<span class="country-name">'
1501 . htmlspecialchars( $vals['CiAdrCtry'] )
1504 if ( isset( $vals['CiEmailWork'] ) ) {
1506 // Have to split multiple emails at commas/new lines.
1507 $splitEmails = explode( "\n", $vals['CiEmailWork'] );
1508 foreach ( $splitEmails as $e1 ) {
1509 // Also split on comma
1510 foreach ( explode( ',', $e1 ) as $e2 ) {
1511 $finalEmail = trim( $e2 );
1512 if ( $finalEmail == ',' ||
$finalEmail == '' ) {
1515 if ( strpos( $finalEmail, '<' ) !== false ) {
1516 // Don't do fancy formatting to
1517 // "My name" <foo@bar.com> style stuff
1518 $emails[] = $finalEmail;
1520 $emails[] = '[mailto:'
1522 . ' <span class="email">'
1528 $email = implode( ', ', $emails );
1530 if ( isset( $vals['CiTelWork'] ) ) {
1531 $tel = '<span class="tel">'
1532 . htmlspecialchars( $vals['CiTelWork'] )
1535 if ( isset( $vals['CiAdrPcode'] ) ) {
1536 $postal = '<span class="postal-code">'
1538 $vals['CiAdrPcode'] )
1541 if ( isset( $vals['CiAdrRegion'] ) ) {
1542 // Note this is province/state.
1543 $region = '<span class="region">'
1545 $vals['CiAdrRegion'] )
1548 if ( isset( $vals['CiUrlWork'] ) ) {
1549 $url = '<span class="url">'
1550 . htmlspecialchars( $vals['CiUrlWork'] )
1554 return $this->msg( 'exif-contact-value', $email, $url,
1555 $street, $city, $region, $postal, $country,
1561 * Get a list of fields that are visible by default.
1566 public static function getVisibleFields() {
1568 $lines = explode( "\n", wfMessage( 'metadata-fields' )->inContentLanguage()->text() );
1569 foreach ( $lines as $line ) {
1571 if ( preg_match( '/^\\*\s*(.*?)\s*$/', $line, $matches ) ) {
1572 $fields[] = $matches[1];
1575 $fields = array_map( 'strtolower', $fields );
1581 * Get an array of extended metadata. (See the imageinfo API for format.)
1583 * @param File $file File to use
1584 * @return array [<property name> => ['value' => <value>]], or [] on error
1587 public function fetchExtendedMetadata( File
$file ) {
1588 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1590 // If revision deleted, exit immediately
1591 if ( $file->isDeleted( File
::DELETED_FILE
) ) {
1595 $cacheKey = $cache->makeKey(
1596 'getExtendedMetadata',
1597 $this->getLanguage()->getCode(),
1598 (int)$this->singleLang
,
1602 $cachedValue = $cache->get( $cacheKey );
1605 && Hooks
::run( 'ValidateExtendedMetadataCache', [ $cachedValue['timestamp'], $file ] )
1607 $extendedMetadata = $cachedValue['data'];
1609 $maxCacheTime = ( $file instanceof ForeignAPIFile
) ?
60 * 60 * 12 : 60 * 60 * 24 * 30;
1610 $fileMetadata = $this->getExtendedMetadataFromFile( $file );
1611 $extendedMetadata = $this->getExtendedMetadataFromHook( $file, $fileMetadata, $maxCacheTime );
1612 if ( $this->singleLang
) {
1613 $this->resolveMultilangMetadata( $extendedMetadata );
1615 $this->discardMultipleValues( $extendedMetadata );
1616 // Make sure the metadata won't break the API when an XML format is used.
1617 // This is an API-specific function so it would be cleaner to call it from
1618 // outside fetchExtendedMetadata, but this way we don't need to redo the
1619 // computation on a cache hit.
1620 $this->sanitizeArrayForAPI( $extendedMetadata );
1621 $valueToCache = [ 'data' => $extendedMetadata, 'timestamp' => wfTimestampNow() ];
1622 $cache->set( $cacheKey, $valueToCache, $maxCacheTime );
1625 return $extendedMetadata;
1629 * Get file-based metadata in standardized format.
1631 * Note that for a remote file, this might return metadata supplied by extensions.
1633 * @param File $file File to use
1634 * @return array [<property name> => ['value' => <value>]], or [] on error
1637 protected function getExtendedMetadataFromFile( File
$file ) {
1638 // If this is a remote file accessed via an API request, we already
1639 // have remote metadata so we just ignore any local one
1640 if ( $file instanceof ForeignAPIFile
) {
1641 // In case of error we pretend no metadata - this will get cached.
1642 // Might or might not be a good idea.
1643 return $file->getExtendedMetadata() ?
: [];
1646 $uploadDate = wfTimestamp( TS_ISO_8601
, $file->getTimestamp() );
1649 // This is modification time, which is close to "upload" time.
1651 'value' => $uploadDate,
1652 'source' => 'mediawiki-metadata',
1656 $title = $file->getTitle();
1658 $text = $title->getText();
1659 $pos = strrpos( $text, '.' );
1662 $name = substr( $text, 0, $pos );
1667 $fileMetadata['ObjectName'] = [
1669 'source' => 'mediawiki-metadata',
1673 return $fileMetadata;
1677 * Get additional metadata from hooks in standardized format.
1679 * @param File $file File to use
1680 * @param array $extendedMetadata
1681 * @param int $maxCacheTime Hook handlers might use this parameter to override cache time
1683 * @return array [<property name> => ['value' => <value>]], or [] on error
1686 protected function getExtendedMetadataFromHook( File
$file, array $extendedMetadata,
1689 Hooks
::run( 'GetExtendedMetadata', [
1692 $this->getContext(),
1697 $visible = array_flip( self
::getVisibleFields() );
1698 foreach ( $extendedMetadata as $key => $value ) {
1699 if ( !isset( $visible[strtolower( $key )] ) ) {
1700 $extendedMetadata[$key]['hidden'] = '';
1704 return $extendedMetadata;
1708 * Turns an XMP-style multilang array into a single value.
1709 * If the value is not a multilang array, it is returned unchanged.
1710 * See mediawiki.org/wiki/Manual:File_metadata_handling#Multi-language_array_format
1711 * @param mixed $value
1712 * @return mixed Value in best language, null if there were no languages at all
1715 protected function resolveMultilangValue( $value ) {
1718 ||
!isset( $value['_type'] )
1719 ||
$value['_type'] != 'lang'
1721 return $value; // do nothing if not a multilang array
1724 // choose the language best matching user or site settings
1725 $priorityLanguages = $this->getPriorityLanguages();
1726 foreach ( $priorityLanguages as $lang ) {
1727 if ( isset( $value[$lang] ) ) {
1728 return $value[$lang];
1732 // otherwise go with the default language, if set
1733 if ( isset( $value['x-default'] ) ) {
1734 return $value['x-default'];
1737 // otherwise just return any one language
1738 unset( $value['_type'] );
1739 if ( !empty( $value ) ) {
1740 return reset( $value );
1743 // this should not happen; signal error
1748 * Turns an XMP-style multivalue array into a single value by dropping all but the first
1749 * value. If the value is not a multivalue array (or a multivalue array inside a multilang
1750 * array), it is returned unchanged.
1751 * See mediawiki.org/wiki/Manual:File_metadata_handling#Multi-language_array_format
1752 * @param mixed $value
1753 * @return mixed The value, or the first value if there were multiple ones
1756 protected function resolveMultivalueValue( $value ) {
1757 if ( !is_array( $value ) ) {
1759 } elseif ( isset( $value['_type'] ) && $value['_type'] === 'lang' ) {
1760 // if this is a multilang array, process fields separately
1762 foreach ( $value as $k => $v ) {
1763 $newValue[$k] = $this->resolveMultivalueValue( $v );
1766 } else { // _type is 'ul' or 'ol' or missing in which case it defaults to 'ul'
1767 list( $k, $v ) = each( $value );
1768 if ( $k === '_type' ) {
1769 $v = current( $value );
1776 * Takes an array returned by the getExtendedMetadata* functions,
1777 * and resolves multi-language values in it.
1778 * @param array $metadata
1781 protected function resolveMultilangMetadata( &$metadata ) {
1782 if ( !is_array( $metadata ) ) {
1785 foreach ( $metadata as &$field ) {
1786 if ( isset( $field['value'] ) ) {
1787 $field['value'] = $this->resolveMultilangValue( $field['value'] );
1793 * Takes an array returned by the getExtendedMetadata* functions,
1794 * and turns all fields into single-valued ones by dropping extra values.
1795 * @param array $metadata
1798 protected function discardMultipleValues( &$metadata ) {
1799 if ( !is_array( $metadata ) ) {
1802 foreach ( $metadata as $key => &$field ) {
1803 if ( $key === 'Software' ||
$key === 'Contact' ) {
1804 // we skip some fields which have composite values. They are not particularly interesting
1805 // and you can get them via the metadata / commonmetadata APIs anyway.
1808 if ( isset( $field['value'] ) ) {
1809 $field['value'] = $this->resolveMultivalueValue( $field['value'] );
1815 * Makes sure the given array is a valid API response fragment
1818 protected function sanitizeArrayForAPI( &$arr ) {
1819 if ( !is_array( $arr ) ) {
1824 foreach ( $arr as $key => &$value ) {
1825 $sanitizedKey = $this->sanitizeKeyForAPI( $key );
1826 if ( $sanitizedKey !== $key ) {
1827 if ( isset( $arr[$sanitizedKey] ) ) {
1828 // Make the sanitized keys hopefully unique.
1829 // To make it definitely unique would be too much effort, given that
1830 // sanitizing is only needed for misformatted metadata anyway, but
1831 // this at least covers the case when $arr is numeric.
1832 $sanitizedKey .= $counter;
1835 $arr[$sanitizedKey] = $arr[$key];
1836 unset( $arr[$key] );
1838 if ( is_array( $value ) ) {
1839 $this->sanitizeArrayForAPI( $value );
1843 // Handle API metadata keys (particularly "_type")
1844 $keys = array_filter( array_keys( $arr ), 'ApiResult::isMetadataKey' );
1846 ApiResult
::setPreserveKeysList( $arr, $keys );
1851 * Turns a string into a valid API identifier.
1852 * @param string $key
1856 protected function sanitizeKeyForAPI( $key ) {
1857 // drop all characters which are not valid in an XML tag name
1858 // a bunch of non-ASCII letters would be valid but probably won't
1859 // be used so we take the easy way
1860 $key = preg_replace( '/[^a-zA-z0-9_:.-]/', '', $key );
1861 // drop characters which are invalid at the first position
1862 $key = preg_replace( '/^[\d-.]+/', '', $key );
1868 // special case for an internal keyword
1869 if ( $key == '_element' ) {
1877 * Returns a list of languages (first is best) to use when formatting multilang fields,
1878 * based on user and site preferences.
1882 protected function getPriorityLanguages() {
1883 $priorityLanguages =
1884 Language
::getFallbacksIncludingSiteLanguage( $this->getLanguage()->getCode() );
1885 $priorityLanguages = array_merge(
1886 (array)$this->getLanguage()->getCode(),
1887 $priorityLanguages[0],
1888 $priorityLanguages[1]
1891 return $priorityLanguages;