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 Wikimedia\Timestamp\TimestampException
;
30 * Format Image metadata values into a human readable form.
32 * Note lots of these messages use the prefix 'exif' even though
33 * they may not be exif properties. For example 'exif-ImageDescription'
34 * can be the Exif ImageDescription, or it could be the iptc-iim caption
35 * property, or it could be the xmp dc:description property. This
36 * is because these messages should be independent of how the data is
37 * stored, sine the user doesn't care if the description is stored in xmp,
38 * exif, etc only that its a description. (Additionally many of these properties
39 * are merged together following the MWG standard, such that for example,
40 * exif properties override XMP properties that mean the same thing if
41 * there is a conflict).
43 * It should perhaps use a prefix like 'metadata' instead, but there
44 * is already a large number of messages using the 'exif' prefix.
47 * @since 1.23 the class extends ContextSource and various formerly-public
48 * internal methods are private
50 class FormatMetadata
extends ContextSource
{
52 * Only output a single language for multi-language fields
56 protected $singleLang = false;
59 * Trigger only outputting single language for multilanguage fields
64 public function setSingleLanguage( $val ) {
65 $this->singleLang
= $val;
69 * Numbers given by Exif user agents are often magical, that is they
70 * should be replaced by a detailed explanation depending on their
71 * value which most of the time are plain integers. This function
72 * formats Exif (and other metadata) values into human readable form.
74 * This is the usual entry point for this class.
76 * @param array $tags The Exif data to format ( as returned by
77 * Exif::getFilteredData() or BitmapMetadataHandler )
78 * @param bool|IContextSource $context Context to use (optional)
81 public static function getFormattedData( $tags, $context = false ) {
82 $obj = new FormatMetadata
;
84 $obj->setContext( $context );
87 return $obj->makeFormattedData( $tags );
91 * Numbers given by Exif user agents are often magical, that is they
92 * should be replaced by a detailed explanation depending on their
93 * value which most of the time are plain integers. This function
94 * formats Exif (and other metadata) values into human readable form.
96 * @param array $tags The Exif data to format ( as returned by
97 * Exif::getFilteredData() or BitmapMetadataHandler )
101 public function makeFormattedData( $tags ) {
102 $resolutionunit = !isset( $tags['ResolutionUnit'] ) ||
$tags['ResolutionUnit'] == 2 ?
2 : 3;
103 unset( $tags['ResolutionUnit'] );
105 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] ) ) {
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'] );
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
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
);
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
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 );
167 foreach ( $vals as &$val ) {
182 $val = $this->exifMsg( $tag, $val );
185 /* If not recognized, display as is. */
190 case 'PhotometricInterpretation':
204 $val = $this->exifMsg( $tag, $val );
207 /* If not recognized, display as is. */
222 $val = $this->exifMsg( $tag, $val );
225 /* If not recognized, display as is. */
230 case 'PlanarConfiguration':
234 $val = $this->exifMsg( $tag, $val );
237 /* If not recognized, display as is. */
242 // TODO: YCbCrSubSampling
243 case 'YCbCrPositioning':
247 $val = $this->exifMsg( $tag, $val );
250 /* If not recognized, display as is. */
257 switch ( $resolutionunit ) {
259 $val = $this->exifMsg( 'XYResolution', 'i', $this->formatNum( $val ) );
262 $val = $this->exifMsg( 'XYResolution', 'c', $this->formatNum( $val ) );
265 /* If not recognized, display as is. */
270 // TODO: YCbCrCoefficients #p27 (see annex E)
272 case 'FlashpixVersion':
280 $val = $this->exifMsg( $tag, $val );
283 /* If not recognized, display as is. */
288 case 'ComponentsConfiguration':
297 $val = $this->exifMsg( $tag, $val );
300 /* If not recognized, display as is. */
306 case 'DateTimeOriginal':
307 case 'DateTimeDigitized':
308 case 'DateTimeReleased':
309 case 'DateTimeExpires':
312 case 'DateTimeMetadata':
313 if ( $val == '0000:00:00 00:00:00' ||
$val == ' : : : : ' ) {
314 $val = $this->msg( 'exif-unknowndate' )->text();
315 } elseif ( preg_match(
316 '/^(?:\d{4}):(?:\d\d):(?:\d\d) (?:\d\d):(?:\d\d):(?:\d\d)$/D',
320 $time = wfTimestamp( TS_MW
, $val );
321 if ( $time && intval( $time ) > 0 ) {
322 $val = $this->getLanguage()->timeanddate( $time );
324 } elseif ( preg_match( '/^(?:\d{4}):(?:\d\d):(?:\d\d) (?:\d\d):(?:\d\d)$/D', $val ) ) {
325 // No second field. Still format the same
326 // since timeanddate doesn't include seconds anyways,
327 // but second still available in api
328 $time = wfTimestamp( TS_MW
, $val . ':00' );
329 if ( $time && intval( $time ) > 0 ) {
330 $val = $this->getLanguage()->timeanddate( $time );
332 } elseif ( preg_match( '/^(?:\d{4}):(?:\d\d):(?:\d\d)$/D', $val ) ) {
333 // If only the date but not the time is filled in.
334 $time = wfTimestamp( TS_MW
, substr( $val, 0, 4 )
335 . substr( $val, 5, 2 )
336 . substr( $val, 8, 2 )
338 if ( $time && intval( $time ) > 0 ) {
339 $val = $this->getLanguage()->date( $time );
342 // else it will just output $val without formatting it.
345 case 'ExposureProgram':
356 $val = $this->exifMsg( $tag, $val );
359 /* If not recognized, display as is. */
364 case 'SubjectDistance':
365 $val = $this->exifMsg( $tag, '', $this->formatNum( $val ) );
379 $val = $this->exifMsg( $tag, $val );
382 /* If not recognized, display as is. */
410 $val = $this->exifMsg( $tag, $val );
413 /* If not recognized, display as is. */
420 'fired' => $val & 0b00000001
,
421 'return' => ( $val & 0b00000110
) >> 1,
422 'mode' => ( $val & 0b00011000
) >> 3,
423 'function' => ( $val & 0b00100000
) >> 5,
424 'redeye' => ( $val & 0b01000000
) >> 6,
425 // 'reserved' => ( $val & 0b10000000 ) >> 7,
428 # We do not need to handle unknown values since all are used.
429 foreach ( $flashDecode as $subTag => $subValue ) {
430 # We do not need any message for zeroed values.
431 if ( $subTag != 'fired' && $subValue == 0 ) {
434 $fullTag = $tag . '-' . $subTag;
435 $flashMsgs[] = $this->exifMsg( $fullTag, $subValue );
437 $val = $this->getLanguage()->commaList( $flashMsgs );
440 case 'FocalPlaneResolutionUnit':
443 $val = $this->exifMsg( $tag, $val );
446 /* If not recognized, display as is. */
451 case 'SensingMethod':
460 $val = $this->exifMsg( $tag, $val );
463 /* If not recognized, display as is. */
471 $val = $this->exifMsg( $tag, $val );
474 /* If not recognized, display as is. */
482 $val = $this->exifMsg( $tag, $val );
485 /* If not recognized, display as is. */
490 case 'CustomRendered':
494 $val = $this->exifMsg( $tag, $val );
497 /* If not recognized, display as is. */
507 $val = $this->exifMsg( $tag, $val );
510 /* If not recognized, display as is. */
519 $val = $this->exifMsg( $tag, $val );
522 /* If not recognized, display as is. */
527 case 'SceneCaptureType':
533 $val = $this->exifMsg( $tag, $val );
536 /* If not recognized, display as is. */
548 $val = $this->exifMsg( $tag, $val );
551 /* If not recognized, display as is. */
561 $val = $this->exifMsg( $tag, $val );
564 /* If not recognized, display as is. */
574 $val = $this->exifMsg( $tag, $val );
577 /* If not recognized, display as is. */
587 $val = $this->exifMsg( $tag, $val );
590 /* If not recognized, display as is. */
595 case 'SubjectDistanceRange':
601 $val = $this->exifMsg( $tag, $val );
604 /* If not recognized, display as is. */
609 // The GPS...Ref values are kept for compatibility, probably won't be reached.
610 case 'GPSLatitudeRef':
611 case 'GPSDestLatitudeRef':
615 $val = $this->exifMsg( 'GPSLatitude', $val );
618 /* If not recognized, display as is. */
623 case 'GPSLongitudeRef':
624 case 'GPSDestLongitudeRef':
628 $val = $this->exifMsg( 'GPSLongitude', $val );
631 /* If not recognized, display as is. */
638 $val = $this->exifMsg( 'GPSAltitude', 'below-sealevel', $this->formatNum( -$val, 3 ) );
640 $val = $this->exifMsg( 'GPSAltitude', 'above-sealevel', $this->formatNum( $val, 3 ) );
648 $val = $this->exifMsg( $tag, $val );
651 /* If not recognized, display as is. */
656 case 'GPSMeasureMode':
660 $val = $this->exifMsg( $tag, $val );
663 /* If not recognized, display as is. */
669 case 'GPSImgDirectionRef':
670 case 'GPSDestBearingRef':
674 $val = $this->exifMsg( 'GPSDirection', $val );
677 /* If not recognized, display as is. */
683 case 'GPSDestLatitude':
684 $val = $this->formatCoords( $val, 'latitude' );
687 case 'GPSDestLongitude':
688 $val = $this->formatCoords( $val, 'longitude' );
696 $val = $this->exifMsg( 'GPSSpeed', $val );
699 /* If not recognized, display as is. */
704 case 'GPSDestDistanceRef':
709 $val = $this->exifMsg( 'GPSDestDistance', $val );
712 /* If not recognized, display as is. */
718 // See https://en.wikipedia.org/wiki/Dilution_of_precision_(GPS)
720 $val = $this->exifMsg( $tag, 'excellent', $this->formatNum( $val ) );
721 } elseif ( $val <= 5 ) {
722 $val = $this->exifMsg( $tag, 'good', $this->formatNum( $val ) );
723 } elseif ( $val <= 10 ) {
724 $val = $this->exifMsg( $tag, 'moderate', $this->formatNum( $val ) );
725 } elseif ( $val <= 20 ) {
726 $val = $this->exifMsg( $tag, 'fair', $this->formatNum( $val ) );
728 $val = $this->exifMsg( $tag, 'poor', $this->formatNum( $val ) );
732 // This is not in the Exif standard, just a special
733 // case for our purposes which enables wikis to wikify
734 // the make, model and software name to link to their articles.
737 $val = $this->exifMsg( $tag, '', $val );
741 if ( is_array( $val ) ) {
742 // if its a software, version array.
743 $val = $this->msg( 'exif-software-version-value', $val[0], $val[1] )->text();
745 $val = $this->exifMsg( $tag, '', $val );
750 // Show the pretty fraction as well as decimal version
751 $val = $this->msg( 'exif-exposuretime-format',
752 $this->formatFraction( $val ), $this->formatNum( $val ) )->text();
754 case 'ISOSpeedRatings':
755 // If its = 65535 that means its at the
756 // limit of the size of Exif::short and
758 if ( $val == '65535' ) {
759 $val = $this->exifMsg( $tag, 'overflow' );
761 $val = $this->formatNum( $val );
765 $val = $this->msg( 'exif-fnumber-format',
766 $this->formatNum( $val ) )->text();
770 case 'FocalLengthIn35mmFilm':
771 $val = $this->msg( 'exif-focallength-format',
772 $this->formatNum( $val ) )->text();
775 case 'MaxApertureValue':
776 if ( strpos( $val, '/' ) !== false ) {
777 // need to expand this earlier to calculate fNumber
778 list( $n, $d ) = explode( '/', $val );
779 if ( is_numeric( $n ) && is_numeric( $d ) ) {
783 if ( is_numeric( $val ) ) {
784 $fNumber = pow( 2, $val / 2 );
785 if ( $fNumber !== false ) {
786 $val = $this->msg( 'exif-maxaperturevalue-value',
787 $this->formatNum( $val ),
788 $this->formatNum( $fNumber, 2 )
795 switch ( strtolower( $val ) ) {
796 // See pg 29 of IPTC photo
797 // metadata standard.
815 $val = $this->exifMsg(
821 case 'SubjectNewsCode':
822 // Essentially like iimCategory.
823 // 8 (numeric) digit hierarchical
824 // classification. We decode the
825 // first 2 digits, which provide
827 $val = $this->convertNewsCode( $val );
830 // 1-8 with 1 being highest, 5 normal
831 // 0 is reserved, and 9 is 'user-defined'.
833 if ( $val == 0 ||
$val == 9 ) {
835 } elseif ( $val < 5 && $val > 1 ) {
837 } elseif ( $val == 5 ) {
839 } elseif ( $val <= 8 && $val > 5 ) {
843 if ( $urgency !== '' ) {
844 $val = $this->exifMsg( 'urgency',
850 // Things that have a unit of pixels.
851 case 'OriginalImageHeight':
852 case 'OriginalImageWidth':
853 case 'PixelXDimension':
854 case 'PixelYDimension':
857 $val = $this->formatNum( $val ) . ' ' . $this->msg( 'unit-pixel' )->text();
860 // Do not transform fields with pure text.
861 // For some languages the formatNum()
862 // conversion results to wrong output like
863 // foo,bar@example,com or foo٫bar@example٫com.
864 // Also some 'numeric' things like Scene codes
865 // are included here as we really don't want
867 case 'ImageDescription':
871 case 'RelatedSoundFile':
872 case 'ImageUniqueID':
873 case 'SpectralSensitivity':
874 case 'GPSSatellites':
878 case 'WorldRegionDest':
880 case 'CountryCodeDest':
881 case 'ProvinceOrStateDest':
883 case 'SublocationDest':
884 case 'WorldRegionCreated':
885 case 'CountryCreated':
886 case 'CountryCodeCreated':
887 case 'ProvinceOrStateCreated':
889 case 'SublocationCreated':
891 case 'SpecialInstructions':
896 case 'FixtureIdentifier':
898 case 'LocationDestCode':
900 case 'JPEGFileComment':
901 case 'iimSupplementalCategory':
902 case 'OriginalTransmissionRef':
904 case 'dc-contributor':
913 case 'CameraOwnerName':
916 case 'RightsCertificate':
917 case 'CopyrightOwner':
920 case 'OriginalDocumentID':
922 case 'MorePermissionsUrl':
923 case 'AttributionUrl':
924 case 'PreferredAttributionName':
925 case 'PNGFileComment':
927 case 'ContentWarning':
928 case 'GIFFileComment':
930 case 'IntellectualGenre':
932 case 'OrginisationInImage':
933 case 'PersonInImage':
935 $val = htmlspecialchars( $val );
943 $val = $this->exifMsg( $tag, $val );
946 $val = htmlspecialchars( $val );
954 $val = $this->exifMsg( $tag, $val );
959 if ( $val == '-1' ) {
960 $val = $this->exifMsg( $tag, 'rejected' );
962 $val = $this->formatNum( $val );
967 $lang = Language
::fetchLanguageName( strtolower( $val ), $this->getLanguage()->getCode() );
969 $val = htmlspecialchars( $lang );
971 $val = htmlspecialchars( $val );
976 $val = $this->formatNum( $val );
980 // End formatting values, start flattening arrays.
981 $vals = $this->flattenArrayReal( $vals, $type );
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).
1001 public static function flattenArrayContentLang( $vals, $type = 'ul',
1002 $noHtml = false, $context = false
1005 $obj = new FormatMetadata
;
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).
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' ) {
1046 } elseif ( count( $vals ) === 0 ) {
1047 wfDebug( __METHOD__
. " metadata array with 0 elements!\n" );
1049 return ""; // paranoia. This should never happen
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
1057 // Display default, followed by ContLang,
1058 // followed by the rest in no particular
1061 // Todo: hide some items if really long list.
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] ) ) {
1083 if ( $vals[$pLang] === $defaultItem ) {
1084 $defaultItem = false;
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 [ 'lang' => $pLang ], $vals[$pLang] );
1101 foreach ( $vals as $lang => $item ) {
1102 if ( $item === $defaultItem ) {
1103 $defaultLang = $lang;
1106 $content .= $this->langItem( $item,
1107 $lang, false, $noHtml );
1108 if ( $this->singleLang
) {
1109 return Html
::rawElement( 'span',
1110 [ 'lang' => $lang ], $item );
1113 if ( $defaultItem !== false ) {
1114 $content = $this->langItem( $defaultItem,
1115 $defaultLang, true, $noHtml ) .
1117 if ( $this->singleLang
) {
1118 return $defaultItem;
1125 return '<ul class="metadata-langlist">' .
1130 return "\n#" . implode( "\n#", $vals );
1133 return "<ol><li>" . implode( "</li>\n<li>", $vals ) . '</li></ol>';
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 '
1162 $wrappedValue = $value;
1164 $wrappedValue = '<span class="mw-metadata-lang-value">'
1165 . $value . '</span>';
1168 if ( $lang === false ) {
1169 $msg = $this->msg( 'metadata-langitem-default', $wrappedValue );
1171 return $msg->text() . "\n\n";
1174 return '<li class="mw-metadata-lang-default">'
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 === '' ) {
1190 // else we have a language specified
1192 $msg = $this->msg( 'metadata-langitem', $wrappedValue, $langName, $lang );
1194 return '*' . $msg->text();
1197 $item = '<li class="mw-metadata-lang-code-'
1200 $item .= ' mw-metadata-lang-default';
1202 $item .= '" lang="' . $lang . '">';
1203 $item .= $msg->text();
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 ) {
1221 if ( $val === '' ) {
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 ) {
1238 if ( is_array( $num ) ) {
1240 foreach ( $num as $number ) {
1241 $out[] = $this->formatNum( $number );
1244 return $this->getLanguage()->commaList( $out );
1246 if ( preg_match( '/^(-?\d+)\/(\d+)$/', $num, $m ) ) {
1248 $newNum = $m[1] / $m[2];
1249 if ( $round !== false ) {
1250 $newNum = round( $newNum, $round );
1256 return $this->getLanguage()->formatNum( $newNum );
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 ) {
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 );
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
1294 private function gcd( $a, $b ) {
1296 // https://en.wikipedia.org/wiki/Euclidean_algorithm
1297 // Recursive form would be:
1301 return gcd( $b, $a % $b );
1304 $remainder = $a %
$b;
1306 // tail recursion...
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
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.
1332 switch ( substr( $val, 0, 2 ) ) {
1385 if ( $cat !== '' ) {
1386 $catMsg = $this->exifMsg( 'iimcategory', $cat );
1387 $val = $this->exifMsg( 'subjectnewscode', '', $val, $catMsg );
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 ) {
1405 if ( $type === 'latitude' ) {
1407 } elseif ( $type === 'longitude' ) {
1412 if ( $type === 'latitude' ) {
1414 } elseif ( $type === 'longitude' ) {
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
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'] )
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
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 );
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">'
1487 $vals['CiAdrExtadr'] )
1490 if ( isset( $vals['CiAdrCity'] ) ) {
1491 $city = '<span class="locality">'
1492 . htmlspecialchars( $vals['CiAdrCity'] )
1495 if ( isset( $vals['CiAdrCtry'] ) ) {
1496 $country = '<span class="country-name">'
1497 . htmlspecialchars( $vals['CiAdrCtry'] )
1500 if ( isset( $vals['CiEmailWork'] ) ) {
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 == '' ) {
1511 if ( strpos( $finalEmail, '<' ) !== false ) {
1512 // Don't do fancy formatting to
1513 // "My name" <foo@bar.com> style stuff
1514 $emails[] = $finalEmail;
1516 $emails[] = '[mailto:'
1518 . ' <span class="email">'
1524 $email = implode( ', ', $emails );
1526 if ( isset( $vals['CiTelWork'] ) ) {
1527 $tel = '<span class="tel">'
1528 . htmlspecialchars( $vals['CiTelWork'] )
1531 if ( isset( $vals['CiAdrPcode'] ) ) {
1532 $postal = '<span class="postal-code">'
1534 $vals['CiAdrPcode'] )
1537 if ( isset( $vals['CiAdrRegion'] ) ) {
1538 // Note this is province/state.
1539 $region = '<span class="region">'
1541 $vals['CiAdrRegion'] )
1544 if ( isset( $vals['CiUrlWork'] ) ) {
1545 $url = '<span class="url">'
1546 . htmlspecialchars( $vals['CiUrlWork'] )
1550 return $this->msg( 'exif-contact-value', $email, $url,
1551 $street, $city, $region, $postal, $country,
1557 * Get a list of fields that are visible by default.
1562 public static function getVisibleFields() {
1564 $lines = explode( "\n", wfMessage( 'metadata-fields' )->inContentLanguage()->text() );
1565 foreach ( $lines as $line ) {
1567 if ( preg_match( '/^\\*\s*(.*?)\s*$/', $line, $matches ) ) {
1568 $fields[] = $matches[1];
1571 $fields = array_map( 'strtolower', $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
1583 public function fetchExtendedMetadata( File
$file ) {
1584 $cache = ObjectCache
::getMainWANInstance();
1586 // If revision deleted, exit immediately
1587 if ( $file->isDeleted( File
::DELETED_FILE
) ) {
1591 $cacheKey = wfMemcKey(
1592 'getExtendedMetadata',
1593 $this->getLanguage()->getCode(),
1594 (int)$this->singleLang
,
1598 $cachedValue = $cache->get( $cacheKey );
1601 && Hooks
::run( 'ValidateExtendedMetadataCache', [ $cachedValue['timestamp'], $file ] )
1603 $extendedMetadata = $cachedValue['data'];
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 = [ '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
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() ?
: [];
1642 $uploadDate = wfTimestamp( TS_ISO_8601
, $file->getTimestamp() );
1645 // This is modification time, which is close to "upload" time.
1647 'value' => $uploadDate,
1648 'source' => 'mediawiki-metadata',
1652 $title = $file->getTitle();
1654 $text = $title->getText();
1655 $pos = strrpos( $text, '.' );
1658 $name = substr( $text, 0, $pos );
1663 $fileMetadata['ObjectName'] = [
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
1682 protected function getExtendedMetadataFromHook( File
$file, array $extendedMetadata,
1685 Hooks
::run( 'GetExtendedMetadata', [
1688 $this->getContext(),
1693 $visible = array_flip( self
::getVisibleFields() );
1694 foreach ( $extendedMetadata as $key => $value ) {
1695 if ( !isset( $visible[strtolower( $key )] ) ) {
1696 $extendedMetadata[$key]['hidden'] = '';
1700 return $extendedMetadata;
1704 * Turns an XMP-style multilang array into a single value.
1705 * If the value is not a multilang array, it is returned unchanged.
1706 * See mediawiki.org/wiki/Manual:File_metadata_handling#Multi-language_array_format
1707 * @param mixed $value
1708 * @return mixed Value in best language, null if there were no languages at all
1711 protected function resolveMultilangValue( $value ) {
1714 ||
!isset( $value['_type'] )
1715 ||
$value['_type'] != 'lang'
1717 return $value; // do nothing if not a multilang array
1720 // choose the language best matching user or site settings
1721 $priorityLanguages = $this->getPriorityLanguages();
1722 foreach ( $priorityLanguages as $lang ) {
1723 if ( isset( $value[$lang] ) ) {
1724 return $value[$lang];
1728 // otherwise go with the default language, if set
1729 if ( isset( $value['x-default'] ) ) {
1730 return $value['x-default'];
1733 // otherwise just return any one language
1734 unset( $value['_type'] );
1735 if ( !empty( $value ) ) {
1736 return reset( $value );
1739 // this should not happen; signal error
1744 * Turns an XMP-style multivalue array into a single value by dropping all but the first
1745 * value. If the value is not a multivalue array (or a multivalue array inside a multilang
1746 * array), it is returned unchanged.
1747 * See mediawiki.org/wiki/Manual:File_metadata_handling#Multi-language_array_format
1748 * @param mixed $value
1749 * @return mixed The value, or the first value if there were multiple ones
1752 protected function resolveMultivalueValue( $value ) {
1753 if ( !is_array( $value ) ) {
1755 } elseif ( isset( $value['_type'] ) && $value['_type'] === 'lang' ) {
1756 // if this is a multilang array, process fields separately
1758 foreach ( $value as $k => $v ) {
1759 $newValue[$k] = $this->resolveMultivalueValue( $v );
1762 } else { // _type is 'ul' or 'ol' or missing in which case it defaults to 'ul'
1763 list( $k, $v ) = each( $value );
1764 if ( $k === '_type' ) {
1765 $v = current( $value );
1772 * Takes an array returned by the getExtendedMetadata* functions,
1773 * and resolves multi-language values in it.
1774 * @param array $metadata
1777 protected function resolveMultilangMetadata( &$metadata ) {
1778 if ( !is_array( $metadata ) ) {
1781 foreach ( $metadata as &$field ) {
1782 if ( isset( $field['value'] ) ) {
1783 $field['value'] = $this->resolveMultilangValue( $field['value'] );
1789 * Takes an array returned by the getExtendedMetadata* functions,
1790 * and turns all fields into single-valued ones by dropping extra values.
1791 * @param array $metadata
1794 protected function discardMultipleValues( &$metadata ) {
1795 if ( !is_array( $metadata ) ) {
1798 foreach ( $metadata as $key => &$field ) {
1799 if ( $key === 'Software' ||
$key === 'Contact' ) {
1800 // we skip some fields which have composite values. They are not particularly interesting
1801 // and you can get them via the metadata / commonmetadata APIs anyway.
1804 if ( isset( $field['value'] ) ) {
1805 $field['value'] = $this->resolveMultivalueValue( $field['value'] );
1811 * Makes sure the given array is a valid API response fragment
1814 protected function sanitizeArrayForAPI( &$arr ) {
1815 if ( !is_array( $arr ) ) {
1820 foreach ( $arr as $key => &$value ) {
1821 $sanitizedKey = $this->sanitizeKeyForAPI( $key );
1822 if ( $sanitizedKey !== $key ) {
1823 if ( isset( $arr[$sanitizedKey] ) ) {
1824 // Make the sanitized keys hopefully unique.
1825 // To make it definitely unique would be too much effort, given that
1826 // sanitizing is only needed for misformatted metadata anyway, but
1827 // this at least covers the case when $arr is numeric.
1828 $sanitizedKey .= $counter;
1831 $arr[$sanitizedKey] = $arr[$key];
1832 unset( $arr[$key] );
1834 if ( is_array( $value ) ) {
1835 $this->sanitizeArrayForAPI( $value );
1839 // Handle API metadata keys (particularly "_type")
1840 $keys = array_filter( array_keys( $arr ), 'ApiResult::isMetadataKey' );
1842 ApiResult
::setPreserveKeysList( $arr, $keys );
1847 * Turns a string into a valid API identifier.
1848 * @param string $key
1852 protected function sanitizeKeyForAPI( $key ) {
1853 // drop all characters which are not valid in an XML tag name
1854 // a bunch of non-ASCII letters would be valid but probably won't
1855 // be used so we take the easy way
1856 $key = preg_replace( '/[^a-zA-z0-9_:.-]/', '', $key );
1857 // drop characters which are invalid at the first position
1858 $key = preg_replace( '/^[\d-.]+/', '', $key );
1864 // special case for an internal keyword
1865 if ( $key == '_element' ) {
1873 * Returns a list of languages (first is best) to use when formatting multilang fields,
1874 * based on user and site preferences.
1878 protected function getPriorityLanguages() {
1879 $priorityLanguages =
1880 Language
::getFallbacksIncludingSiteLanguage( $this->getLanguage()->getCode() );
1881 $priorityLanguages = array_merge(
1882 (array)$this->getLanguage()->getCode(),
1883 $priorityLanguages[0],
1884 $priorityLanguages[1]
1887 return $priorityLanguages;