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
29 * Format Image metadata values into a human readable form.
31 * Note lots of these messages use the prefix 'exif' even though
32 * they may not be exif properties. For example 'exif-ImageDescription'
33 * can be the Exif ImageDescription, or it could be the iptc-iim caption
34 * property, or it could be the xmp dc:description property. This
35 * is because these messages should be independent of how the data is
36 * stored, sine the user doesn't care if the description is stored in xmp,
37 * exif, etc only that its a description. (Additionally many of these properties
38 * are merged together following the MWG standard, such that for example,
39 * exif properties override XMP properties that mean the same thing if
40 * there is a conflict).
42 * It should perhaps use a prefix like 'metadata' instead, but there
43 * is already a large number of messages using the 'exif' prefix.
46 * @since 1.23 the class extends ContextSource and various formerly-public
47 * internal methods are private
49 class FormatMetadata
extends ContextSource
{
51 * Only output a single language for multi-language fields
55 protected $singleLang = false;
58 * Trigger only outputting single language for multilanguage fields
63 public function setSingleLanguage( $val ) {
64 $this->singleLang
= $val;
68 * Numbers given by Exif user agents are often magical, that is they
69 * should be replaced by a detailed explanation depending on their
70 * value which most of the time are plain integers. This function
71 * formats Exif (and other metadata) values into human readable form.
73 * This is the usual entry point for this class.
75 * @param array $tags The Exif data to format ( as returned by
76 * Exif::getFilteredData() or BitmapMetadataHandler )
77 * @param bool|IContextSource $context Context to use (optional)
80 public static function getFormattedData( $tags, $context = false ) {
81 $obj = new FormatMetadata
;
83 $obj->setContext( $context );
86 return $obj->makeFormattedData( $tags );
90 * Numbers given by Exif user agents are often magical, that is they
91 * should be replaced by a detailed explanation depending on their
92 * value which most of the time are plain integers. This function
93 * formats Exif (and other metadata) values into human readable form.
95 * @param array $tags The Exif data to format ( as returned by
96 * Exif::getFilteredData() or BitmapMetadataHandler )
100 public function makeFormattedData( $tags ) {
101 $resolutionunit = !isset( $tags['ResolutionUnit'] ) ||
$tags['ResolutionUnit'] == 2 ?
2 : 3;
102 unset( $tags['ResolutionUnit'] );
104 foreach ( $tags as $tag => &$vals ) {
105 // This seems ugly to wrap non-array's in an array just to unwrap again,
106 // especially when most of the time it is not an array
107 if ( !is_array( $tags[$tag] ) ) {
111 // _type is a special value to say what array type
112 if ( isset( $tags[$tag]['_type'] ) ) {
113 $type = $tags[$tag]['_type'];
114 unset( $vals['_type'] );
116 $type = 'ul'; // default unordered list.
119 // This is done differently as the tag is an array.
120 if ( $tag == 'GPSTimeStamp' && count( $vals ) === 3 ) {
121 // hour min sec array
123 $h = explode( '/', $vals[0] );
124 $m = explode( '/', $vals[1] );
125 $s = explode( '/', $vals[2] );
127 // this should already be validated
128 // when loaded from file, but it could
129 // come from a foreign repo, so be
140 $tags[$tag] = str_pad( intval( $h[0] / $h[1] ), 2, '0', STR_PAD_LEFT
)
141 . ':' . str_pad( intval( $m[0] / $m[1] ), 2, '0', STR_PAD_LEFT
)
142 . ':' . str_pad( intval( $s[0] / $s[1] ), 2, '0', STR_PAD_LEFT
);
145 $time = wfTimestamp( TS_MW
, '1971:01:01 ' . $tags[$tag] );
146 // the 1971:01:01 is just a placeholder, and not shown to user.
147 if ( $time && intval( $time ) > 0 ) {
148 $tags[$tag] = $this->getLanguage()->time( $time );
150 } catch ( TimestampException
$e ) {
151 // This shouldn't happen, but we've seen bad formats
152 // such as 4-digit seconds in the wild.
153 // leave $tags[$tag] as-is
158 // The contact info is a multi-valued field
159 // instead of the other props which are single
160 // valued (mostly) so handle as a special case.
161 if ( $tag === 'Contact' ) {
162 $vals = $this->collapseContactInfo( $vals );
166 foreach ( $vals as &$val ) {
181 $val = $this->exifMsg( $tag, $val );
184 /* If not recognized, display as is. */
189 case 'PhotometricInterpretation':
203 $val = $this->exifMsg( $tag, $val );
206 /* If not recognized, display as is. */
221 $val = $this->exifMsg( $tag, $val );
224 /* If not recognized, display as is. */
229 case 'PlanarConfiguration':
233 $val = $this->exifMsg( $tag, $val );
236 /* If not recognized, display as is. */
241 // TODO: YCbCrSubSampling
242 case 'YCbCrPositioning':
246 $val = $this->exifMsg( $tag, $val );
249 /* If not recognized, display as is. */
256 switch ( $resolutionunit ) {
258 $val = $this->exifMsg( 'XYResolution', 'i', $this->formatNum( $val ) );
261 $val = $this->exifMsg( 'XYResolution', 'c', $this->formatNum( $val ) );
264 /* If not recognized, display as is. */
269 // TODO: YCbCrCoefficients #p27 (see annex E)
271 case 'FlashpixVersion':
279 $val = $this->exifMsg( $tag, $val );
282 /* If not recognized, display as is. */
287 case 'ComponentsConfiguration':
296 $val = $this->exifMsg( $tag, $val );
299 /* If not recognized, display as is. */
305 case 'DateTimeOriginal':
306 case 'DateTimeDigitized':
307 case 'DateTimeReleased':
308 case 'DateTimeExpires':
311 case 'DateTimeMetadata':
312 if ( $val == '0000:00:00 00:00:00' ||
$val == ' : : : : ' ) {
313 $val = $this->msg( 'exif-unknowndate' )->text();
314 } elseif ( preg_match(
315 '/^(?:\d{4}):(?:\d\d):(?:\d\d) (?:\d\d):(?:\d\d):(?:\d\d)$/D',
319 $time = wfTimestamp( TS_MW
, $val );
320 if ( $time && intval( $time ) > 0 ) {
321 $val = $this->getLanguage()->timeanddate( $time );
323 } elseif ( preg_match( '/^(?:\d{4}):(?:\d\d):(?:\d\d) (?:\d\d):(?:\d\d)$/D', $val ) ) {
324 // No second field. Still format the same
325 // since timeanddate doesn't include seconds anyways,
326 // but second still available in api
327 $time = wfTimestamp( TS_MW
, $val . ':00' );
328 if ( $time && intval( $time ) > 0 ) {
329 $val = $this->getLanguage()->timeanddate( $time );
331 } elseif ( preg_match( '/^(?:\d{4}):(?:\d\d):(?:\d\d)$/D', $val ) ) {
332 // If only the date but not the time is filled in.
333 $time = wfTimestamp( TS_MW
, substr( $val, 0, 4 )
334 . substr( $val, 5, 2 )
335 . substr( $val, 8, 2 )
337 if ( $time && intval( $time ) > 0 ) {
338 $val = $this->getLanguage()->date( $time );
341 // else it will just output $val without formatting it.
344 case 'ExposureProgram':
355 $val = $this->exifMsg( $tag, $val );
358 /* If not recognized, display as is. */
363 case 'SubjectDistance':
364 $val = $this->exifMsg( $tag, '', $this->formatNum( $val ) );
378 $val = $this->exifMsg( $tag, $val );
381 /* If not recognized, display as is. */
409 $val = $this->exifMsg( $tag, $val );
412 /* If not recognized, display as is. */
419 'fired' => $val & 0b00000001
,
420 'return' => ( $val & 0b00000110
) >> 1,
421 'mode' => ( $val & 0b00011000
) >> 3,
422 'function' => ( $val & 0b00100000
) >> 5,
423 'redeye' => ( $val & 0b01000000
) >> 6,
424 // 'reserved' => ( $val & 0b10000000 ) >> 7,
427 # We do not need to handle unknown values since all are used.
428 foreach ( $flashDecode as $subTag => $subValue ) {
429 # We do not need any message for zeroed values.
430 if ( $subTag != 'fired' && $subValue == 0 ) {
433 $fullTag = $tag . '-' . $subTag;
434 $flashMsgs[] = $this->exifMsg( $fullTag, $subValue );
436 $val = $this->getLanguage()->commaList( $flashMsgs );
439 case 'FocalPlaneResolutionUnit':
442 $val = $this->exifMsg( $tag, $val );
445 /* If not recognized, display as is. */
450 case 'SensingMethod':
459 $val = $this->exifMsg( $tag, $val );
462 /* If not recognized, display as is. */
470 $val = $this->exifMsg( $tag, $val );
473 /* If not recognized, display as is. */
481 $val = $this->exifMsg( $tag, $val );
484 /* If not recognized, display as is. */
489 case 'CustomRendered':
493 $val = $this->exifMsg( $tag, $val );
496 /* If not recognized, display as is. */
506 $val = $this->exifMsg( $tag, $val );
509 /* If not recognized, display as is. */
518 $val = $this->exifMsg( $tag, $val );
521 /* If not recognized, display as is. */
526 case 'SceneCaptureType':
532 $val = $this->exifMsg( $tag, $val );
535 /* If not recognized, display as is. */
547 $val = $this->exifMsg( $tag, $val );
550 /* If not recognized, display as is. */
560 $val = $this->exifMsg( $tag, $val );
563 /* If not recognized, display as is. */
573 $val = $this->exifMsg( $tag, $val );
576 /* If not recognized, display as is. */
586 $val = $this->exifMsg( $tag, $val );
589 /* If not recognized, display as is. */
594 case 'SubjectDistanceRange':
600 $val = $this->exifMsg( $tag, $val );
603 /* If not recognized, display as is. */
608 // The GPS...Ref values are kept for compatibility, probably won't be reached.
609 case 'GPSLatitudeRef':
610 case 'GPSDestLatitudeRef':
614 $val = $this->exifMsg( 'GPSLatitude', $val );
617 /* If not recognized, display as is. */
622 case 'GPSLongitudeRef':
623 case 'GPSDestLongitudeRef':
627 $val = $this->exifMsg( 'GPSLongitude', $val );
630 /* If not recognized, display as is. */
637 $val = $this->exifMsg( 'GPSAltitude', 'below-sealevel', $this->formatNum( -$val, 3 ) );
639 $val = $this->exifMsg( 'GPSAltitude', 'above-sealevel', $this->formatNum( $val, 3 ) );
647 $val = $this->exifMsg( $tag, $val );
650 /* If not recognized, display as is. */
655 case 'GPSMeasureMode':
659 $val = $this->exifMsg( $tag, $val );
662 /* If not recognized, display as is. */
668 case 'GPSImgDirectionRef':
669 case 'GPSDestBearingRef':
673 $val = $this->exifMsg( 'GPSDirection', $val );
676 /* If not recognized, display as is. */
682 case 'GPSDestLatitude':
683 $val = $this->formatCoords( $val, 'latitude' );
686 case 'GPSDestLongitude':
687 $val = $this->formatCoords( $val, 'longitude' );
695 $val = $this->exifMsg( 'GPSSpeed', $val );
698 /* If not recognized, display as is. */
703 case 'GPSDestDistanceRef':
708 $val = $this->exifMsg( 'GPSDestDistance', $val );
711 /* If not recognized, display as is. */
717 // See https://en.wikipedia.org/wiki/Dilution_of_precision_(GPS)
719 $val = $this->exifMsg( $tag, 'excellent', $this->formatNum( $val ) );
720 } elseif ( $val <= 5 ) {
721 $val = $this->exifMsg( $tag, 'good', $this->formatNum( $val ) );
722 } elseif ( $val <= 10 ) {
723 $val = $this->exifMsg( $tag, 'moderate', $this->formatNum( $val ) );
724 } elseif ( $val <= 20 ) {
725 $val = $this->exifMsg( $tag, 'fair', $this->formatNum( $val ) );
727 $val = $this->exifMsg( $tag, 'poor', $this->formatNum( $val ) );
731 // This is not in the Exif standard, just a special
732 // case for our purposes which enables wikis to wikify
733 // the make, model and software name to link to their articles.
736 $val = $this->exifMsg( $tag, '', $val );
740 if ( is_array( $val ) ) {
741 // if its a software, version array.
742 $val = $this->msg( 'exif-software-version-value', $val[0], $val[1] )->text();
744 $val = $this->exifMsg( $tag, '', $val );
749 // Show the pretty fraction as well as decimal version
750 $val = $this->msg( 'exif-exposuretime-format',
751 $this->formatFraction( $val ), $this->formatNum( $val ) )->text();
753 case 'ISOSpeedRatings':
754 // If its = 65535 that means its at the
755 // limit of the size of Exif::short and
757 if ( $val == '65535' ) {
758 $val = $this->exifMsg( $tag, 'overflow' );
760 $val = $this->formatNum( $val );
764 $val = $this->msg( 'exif-fnumber-format',
765 $this->formatNum( $val ) )->text();
769 case 'FocalLengthIn35mmFilm':
770 $val = $this->msg( 'exif-focallength-format',
771 $this->formatNum( $val ) )->text();
774 case 'MaxApertureValue':
775 if ( strpos( $val, '/' ) !== false ) {
776 // need to expand this earlier to calculate fNumber
777 list( $n, $d ) = explode( '/', $val );
778 if ( is_numeric( $n ) && is_numeric( $d ) ) {
782 if ( is_numeric( $val ) ) {
783 $fNumber = pow( 2, $val / 2 );
784 if ( $fNumber !== false ) {
785 $val = $this->msg( 'exif-maxaperturevalue-value',
786 $this->formatNum( $val ),
787 $this->formatNum( $fNumber, 2 )
794 switch ( strtolower( $val ) ) {
795 // See pg 29 of IPTC photo
796 // metadata standard.
814 $val = $this->exifMsg(
820 case 'SubjectNewsCode':
821 // Essentially like iimCategory.
822 // 8 (numeric) digit hierarchical
823 // classification. We decode the
824 // first 2 digits, which provide
826 $val = $this->convertNewsCode( $val );
829 // 1-8 with 1 being highest, 5 normal
830 // 0 is reserved, and 9 is 'user-defined'.
832 if ( $val == 0 ||
$val == 9 ) {
834 } elseif ( $val < 5 && $val > 1 ) {
836 } elseif ( $val == 5 ) {
838 } elseif ( $val <= 8 && $val > 5 ) {
842 if ( $urgency !== '' ) {
843 $val = $this->exifMsg( 'urgency',
849 // Things that have a unit of pixels.
850 case 'OriginalImageHeight':
851 case 'OriginalImageWidth':
852 case 'PixelXDimension':
853 case 'PixelYDimension':
856 $val = $this->formatNum( $val ) . ' ' . $this->msg( 'unit-pixel' )->text();
859 // Do not transform fields with pure text.
860 // For some languages the formatNum()
861 // conversion results to wrong output like
862 // foo,bar@example,com or foo٫bar@example٫com.
863 // Also some 'numeric' things like Scene codes
864 // are included here as we really don't want
866 case 'ImageDescription':
870 case 'RelatedSoundFile':
871 case 'ImageUniqueID':
872 case 'SpectralSensitivity':
873 case 'GPSSatellites':
877 case 'WorldRegionDest':
879 case 'CountryCodeDest':
880 case 'ProvinceOrStateDest':
882 case 'SublocationDest':
883 case 'WorldRegionCreated':
884 case 'CountryCreated':
885 case 'CountryCodeCreated':
886 case 'ProvinceOrStateCreated':
888 case 'SublocationCreated':
890 case 'SpecialInstructions':
895 case 'FixtureIdentifier':
897 case 'LocationDestCode':
899 case 'JPEGFileComment':
900 case 'iimSupplementalCategory':
901 case 'OriginalTransmissionRef':
903 case 'dc-contributor':
912 case 'CameraOwnerName':
915 case 'RightsCertificate':
916 case 'CopyrightOwner':
919 case 'OriginalDocumentID':
921 case 'MorePermissionsUrl':
922 case 'AttributionUrl':
923 case 'PreferredAttributionName':
924 case 'PNGFileComment':
926 case 'ContentWarning':
927 case 'GIFFileComment':
929 case 'IntellectualGenre':
931 case 'OrginisationInImage':
932 case 'PersonInImage':
934 $val = htmlspecialchars( $val );
942 $val = $this->exifMsg( $tag, $val );
945 $val = htmlspecialchars( $val );
953 $val = $this->exifMsg( $tag, $val );
958 if ( $val == '-1' ) {
959 $val = $this->exifMsg( $tag, 'rejected' );
961 $val = $this->formatNum( $val );
966 $lang = Language
::fetchLanguageName( strtolower( $val ), $this->getLanguage()->getCode() );
968 $val = htmlspecialchars( $lang );
970 $val = htmlspecialchars( $val );
975 $val = $this->formatNum( $val );
979 // End formatting values, start flattening arrays.
980 $vals = $this->flattenArrayReal( $vals, $type );
987 * Flatten an array, using the content language for any messages.
989 * @param array $vals Array of values
990 * @param string $type Type of array (either lang, ul, ol).
991 * lang = language assoc array with keys being the lang code
992 * ul = unordered list, ol = ordered list
993 * type can also come from the '_type' member of $vals.
994 * @param bool $noHtml If to avoid returning anything resembling HTML.
995 * (Ugly hack for backwards compatibility with old MediaWiki).
996 * @param bool|IContextSource $context
997 * @return string Single value (in wiki-syntax).
1000 public static function flattenArrayContentLang( $vals, $type = 'ul',
1001 $noHtml = false, $context = false
1004 $obj = new FormatMetadata
;
1006 $obj->setContext( $context );
1008 $context = new DerivativeContext( $obj->getContext() );
1009 $context->setLanguage( $wgContLang );
1010 $obj->setContext( $context );
1012 return $obj->flattenArrayReal( $vals, $type, $noHtml );
1016 * A function to collapse multivalued tags into a single value.
1017 * This turns an array of (for example) authors into a bulleted list.
1019 * This is public on the basis it might be useful outside of this class.
1021 * @param array $vals Array of values
1022 * @param string $type Type of array (either lang, ul, ol).
1023 * lang = language assoc array with keys being the lang code
1024 * ul = unordered list, ol = ordered list
1025 * type can also come from the '_type' member of $vals.
1026 * @param bool $noHtml If to avoid returning anything resembling HTML.
1027 * (Ugly hack for backwards compatibility with old mediawiki).
1028 * @return string Single value (in wiki-syntax).
1031 public function flattenArrayReal( $vals, $type = 'ul', $noHtml = false ) {
1032 if ( !is_array( $vals ) ) {
1033 return $vals; // do nothing if not an array;
1036 if ( isset( $vals['_type'] ) ) {
1037 $type = $vals['_type'];
1038 unset( $vals['_type'] );
1041 if ( !is_array( $vals ) ) {
1042 return $vals; // do nothing if not an array;
1043 } elseif ( count( $vals ) === 1 && $type !== 'lang' ) {
1045 } elseif ( count( $vals ) === 0 ) {
1046 wfDebug( __METHOD__
. " metadata array with 0 elements!\n" );
1048 return ""; // paranoia. This should never happen
1050 /* @todo FIXME: This should hide some of the list entries if there are
1051 * say more than four. Especially if a field is translated into 20
1052 * languages, we don't want to show them all by default
1056 // Display default, followed by ContLang,
1057 // followed by the rest in no particular
1060 // Todo: hide some items if really long list.
1064 $priorityLanguages = $this->getPriorityLanguages();
1065 $defaultItem = false;
1066 $defaultLang = false;
1068 // If default is set, save it for later,
1069 // as we don't know if it's equal to
1070 // one of the lang codes. (In xmp
1071 // you specify the language for a
1072 // default property by having both
1073 // a default prop, and one in the language
1074 // that are identical)
1075 if ( isset( $vals['x-default'] ) ) {
1076 $defaultItem = $vals['x-default'];
1077 unset( $vals['x-default'] );
1079 foreach ( $priorityLanguages as $pLang ) {
1080 if ( isset( $vals[$pLang] ) ) {
1082 if ( $vals[$pLang] === $defaultItem ) {
1083 $defaultItem = false;
1086 $content .= $this->langItem(
1087 $vals[$pLang], $pLang,
1088 $isDefault, $noHtml );
1090 unset( $vals[$pLang] );
1092 if ( $this->singleLang
) {
1093 return Html
::rawElement( 'span',
1094 [ 'lang' => $pLang ], $vals[$pLang] );
1100 foreach ( $vals as $lang => $item ) {
1101 if ( $item === $defaultItem ) {
1102 $defaultLang = $lang;
1105 $content .= $this->langItem( $item,
1106 $lang, false, $noHtml );
1107 if ( $this->singleLang
) {
1108 return Html
::rawElement( 'span',
1109 [ 'lang' => $lang ], $item );
1112 if ( $defaultItem !== false ) {
1113 $content = $this->langItem( $defaultItem,
1114 $defaultLang, true, $noHtml ) .
1116 if ( $this->singleLang
) {
1117 return $defaultItem;
1124 return '<ul class="metadata-langlist">' .
1129 return "\n#" . implode( "\n#", $vals );
1132 return "<ol><li>" . implode( "</li>\n<li>", $vals ) . '</li></ol>';
1136 return "\n*" . implode( "\n*", $vals );
1139 return "<ul><li>" . implode( "</li>\n<li>", $vals ) . '</li></ul>';
1144 /** Helper function for creating lists of translations.
1146 * @param string $value Value (this is not escaped)
1147 * @param string $lang Lang code of item or false
1148 * @param bool $default If it is default value.
1149 * @param bool $noHtml If to avoid html (for back-compat)
1150 * @throws MWException
1151 * @return string Language item (Note: despite how this looks, this is
1152 * treated as wikitext, not as HTML).
1154 private function langItem( $value, $lang, $default = false, $noHtml = false ) {
1155 if ( $lang === false && $default === false ) {
1156 throw new MWException( '$lang and $default cannot both '
1161 $wrappedValue = $value;
1163 $wrappedValue = '<span class="mw-metadata-lang-value">'
1164 . $value . '</span>';
1167 if ( $lang === false ) {
1168 $msg = $this->msg( 'metadata-langitem-default', $wrappedValue );
1170 return $msg->text() . "\n\n";
1173 return '<li class="mw-metadata-lang-default">'
1178 $lowLang = strtolower( $lang );
1179 $langName = Language
::fetchLanguageName( $lowLang );
1180 if ( $langName === '' ) {
1181 // try just the base language name. (aka en-US -> en ).
1182 list( $langPrefix ) = explode( '-', $lowLang, 2 );
1183 $langName = Language
::fetchLanguageName( $langPrefix );
1184 if ( $langName === '' ) {
1189 // else we have a language specified
1191 $msg = $this->msg( 'metadata-langitem', $wrappedValue, $langName, $lang );
1193 return '*' . $msg->text();
1196 $item = '<li class="mw-metadata-lang-code-'
1199 $item .= ' mw-metadata-lang-default';
1201 $item .= '" lang="' . $lang . '">';
1202 $item .= $msg->text();
1209 * Convenience function for getFormattedData()
1211 * @param string $tag The tag name to pass on
1212 * @param string $val The value of the tag
1213 * @param string $arg An argument to pass ($1)
1214 * @param string $arg2 A 2nd argument to pass ($2)
1215 * @return string The text content of "exif-$tag-$val" message in lower case
1217 private function exifMsg( $tag, $val, $arg = null, $arg2 = null ) {
1220 if ( $val === '' ) {
1224 return $this->msg( $wgContLang->lc( "exif-$tag-$val" ), $arg, $arg2 )->text();
1228 * Format a number, convert numbers from fractions into floating point
1229 * numbers, joins arrays of numbers with commas.
1231 * @param mixed $num The value to format
1232 * @param float|int|bool $round Digits to round to or false.
1233 * @return mixed A floating point number or whatever we were fed
1235 private function formatNum( $num, $round = false ) {
1237 if ( is_array( $num ) ) {
1239 foreach ( $num as $number ) {
1240 $out[] = $this->formatNum( $number );
1243 return $this->getLanguage()->commaList( $out );
1245 if ( preg_match( '/^(-?\d+)\/(\d+)$/', $num, $m ) ) {
1247 $newNum = $m[1] / $m[2];
1248 if ( $round !== false ) {
1249 $newNum = round( $newNum, $round );
1255 return $this->getLanguage()->formatNum( $newNum );
1257 if ( is_numeric( $num ) && $round !== false ) {
1258 $num = round( $num, $round );
1261 return $this->getLanguage()->formatNum( $num );
1266 * Format a rational number, reducing fractions
1268 * @param mixed $num The value to format
1269 * @return mixed A floating point number or whatever we were fed
1271 private function formatFraction( $num ) {
1273 if ( preg_match( '/^(-?\d+)\/(\d+)$/', $num, $m ) ) {
1274 $numerator = intval( $m[1] );
1275 $denominator = intval( $m[2] );
1276 $gcd = $this->gcd( abs( $numerator ), $denominator );
1278 // 0 shouldn't happen! ;)
1279 return $this->formatNum( $numerator / $gcd ) . '/' . $this->formatNum( $denominator / $gcd );
1283 return $this->formatNum( $num );
1287 * Calculate the greatest common divisor of two integers.
1289 * @param int $a Numerator
1290 * @param int $b Denominator
1293 private function gcd( $a, $b ) {
1295 // https://en.wikipedia.org/wiki/Euclidean_algorithm
1296 // Recursive form would be:
1300 return gcd( $b, $a % $b );
1303 $remainder = $a %
$b;
1305 // tail recursion...
1314 * Fetch the human readable version of a news code.
1315 * A news code is an 8 digit code. The first two
1316 * digits are a general classification, so we just
1319 * Note, leading 0's are significant, so this is
1320 * a string, not an int.
1322 * @param string $val The 8 digit news code.
1323 * @return string The human readable form
1325 private function convertNewsCode( $val ) {
1326 if ( !preg_match( '/^\d{8}$/D', $val ) ) {
1327 // Not a valid news code.
1331 switch ( substr( $val, 0, 2 ) ) {
1384 if ( $cat !== '' ) {
1385 $catMsg = $this->exifMsg( 'iimcategory', $cat );
1386 $val = $this->exifMsg( 'subjectnewscode', '', $val, $catMsg );
1393 * Format a coordinate value, convert numbers from floating point
1394 * into degree minute second representation.
1396 * @param int $coord Degrees, minutes and seconds
1397 * @param string $type Latitude or longitude (for if its a NWS or E)
1398 * @return mixed A floating point number or whatever we were fed
1400 private function formatCoords( $coord, $type ) {
1404 if ( $type === 'latitude' ) {
1406 } elseif ( $type === 'longitude' ) {
1411 if ( $type === 'latitude' ) {
1413 } elseif ( $type === 'longitude' ) {
1418 $deg = floor( $nCoord );
1419 $min = floor( ( $nCoord - $deg ) * 60.0 );
1420 $sec = round( ( ( $nCoord - $deg ) - $min / 60 ) * 3600, 2 );
1422 $deg = $this->formatNum( $deg );
1423 $min = $this->formatNum( $min );
1424 $sec = $this->formatNum( $sec );
1426 return $this->msg( 'exif-coordinate-format', $deg, $min, $sec, $ref, $coord )->text();
1430 * Format the contact info field into a single value.
1432 * This function might be called from
1433 * JpegHandler::convertMetadataVersion which is why it is
1436 * @param array $vals Array with fields of the ContactInfo
1437 * struct defined in the IPTC4XMP spec. Or potentially
1438 * an array with one element that is a free form text
1439 * value from the older iptc iim 1:118 prop.
1440 * @return string HTML-ish looking wikitext
1441 * @since 1.23 no longer static
1443 public function collapseContactInfo( $vals ) {
1444 if ( !( isset( $vals['CiAdrExtadr'] )
1445 ||
isset( $vals['CiAdrCity'] )
1446 ||
isset( $vals['CiAdrCtry'] )
1447 ||
isset( $vals['CiEmailWork'] )
1448 ||
isset( $vals['CiTelWork'] )
1449 ||
isset( $vals['CiAdrPcode'] )
1450 ||
isset( $vals['CiAdrRegion'] )
1451 ||
isset( $vals['CiUrlWork'] )
1453 // We don't have any sub-properties
1454 // This could happen if its using old
1455 // iptc that just had this as a free-form
1457 // Note: We run this through htmlspecialchars
1458 // partially to be consistent, and partially
1459 // because people often insert >, etc into
1460 // the metadata which should not be interpreted
1461 // but we still want to auto-link urls.
1462 foreach ( $vals as &$val ) {
1463 $val = htmlspecialchars( $val );
1466 return $this->flattenArrayReal( $vals );
1468 // We have a real ContactInfo field.
1469 // Its unclear if all these fields have to be
1470 // set, so assume they do not.
1471 $url = $tel = $street = $city = $country = '';
1472 $email = $postal = $region = '';
1474 // Also note, some of the class names this uses
1475 // are similar to those used by hCard. This is
1476 // mostly because they're sensible names. This
1477 // does not (and does not attempt to) output
1478 // stuff in the hCard microformat. However it
1479 // might output in the adr microformat.
1481 if ( isset( $vals['CiAdrExtadr'] ) ) {
1482 // Todo: This can potentially be multi-line.
1483 // Need to check how that works in XMP.
1484 $street = '<span class="extended-address">'
1486 $vals['CiAdrExtadr'] )
1489 if ( isset( $vals['CiAdrCity'] ) ) {
1490 $city = '<span class="locality">'
1491 . htmlspecialchars( $vals['CiAdrCity'] )
1494 if ( isset( $vals['CiAdrCtry'] ) ) {
1495 $country = '<span class="country-name">'
1496 . htmlspecialchars( $vals['CiAdrCtry'] )
1499 if ( isset( $vals['CiEmailWork'] ) ) {
1501 // Have to split multiple emails at commas/new lines.
1502 $splitEmails = explode( "\n", $vals['CiEmailWork'] );
1503 foreach ( $splitEmails as $e1 ) {
1504 // Also split on comma
1505 foreach ( explode( ',', $e1 ) as $e2 ) {
1506 $finalEmail = trim( $e2 );
1507 if ( $finalEmail == ',' ||
$finalEmail == '' ) {
1510 if ( strpos( $finalEmail, '<' ) !== false ) {
1511 // Don't do fancy formatting to
1512 // "My name" <foo@bar.com> style stuff
1513 $emails[] = $finalEmail;
1515 $emails[] = '[mailto:'
1517 . ' <span class="email">'
1523 $email = implode( ', ', $emails );
1525 if ( isset( $vals['CiTelWork'] ) ) {
1526 $tel = '<span class="tel">'
1527 . htmlspecialchars( $vals['CiTelWork'] )
1530 if ( isset( $vals['CiAdrPcode'] ) ) {
1531 $postal = '<span class="postal-code">'
1533 $vals['CiAdrPcode'] )
1536 if ( isset( $vals['CiAdrRegion'] ) ) {
1537 // Note this is province/state.
1538 $region = '<span class="region">'
1540 $vals['CiAdrRegion'] )
1543 if ( isset( $vals['CiUrlWork'] ) ) {
1544 $url = '<span class="url">'
1545 . htmlspecialchars( $vals['CiUrlWork'] )
1549 return $this->msg( 'exif-contact-value', $email, $url,
1550 $street, $city, $region, $postal, $country,
1556 * Get a list of fields that are visible by default.
1561 public static function getVisibleFields() {
1563 $lines = explode( "\n", wfMessage( 'metadata-fields' )->inContentLanguage()->text() );
1564 foreach ( $lines as $line ) {
1566 if ( preg_match( '/^\\*\s*(.*?)\s*$/', $line, $matches ) ) {
1567 $fields[] = $matches[1];
1570 $fields = array_map( 'strtolower', $fields );
1576 * Get an array of extended metadata. (See the imageinfo API for format.)
1578 * @param File $file File to use
1579 * @return array [<property name> => ['value' => <value>]], or [] on error
1582 public function fetchExtendedMetadata( File
$file ) {
1583 $cache = ObjectCache
::getMainWANInstance();
1585 // If revision deleted, exit immediately
1586 if ( $file->isDeleted( File
::DELETED_FILE
) ) {
1590 $cacheKey = wfMemcKey(
1591 'getExtendedMetadata',
1592 $this->getLanguage()->getCode(),
1593 (int)$this->singleLang
,
1597 $cachedValue = $cache->get( $cacheKey );
1600 && Hooks
::run( 'ValidateExtendedMetadataCache', [ $cachedValue['timestamp'], $file ] )
1602 $extendedMetadata = $cachedValue['data'];
1604 $maxCacheTime = ( $file instanceof ForeignAPIFile
) ?
60 * 60 * 12 : 60 * 60 * 24 * 30;
1605 $fileMetadata = $this->getExtendedMetadataFromFile( $file );
1606 $extendedMetadata = $this->getExtendedMetadataFromHook( $file, $fileMetadata, $maxCacheTime );
1607 if ( $this->singleLang
) {
1608 $this->resolveMultilangMetadata( $extendedMetadata );
1610 $this->discardMultipleValues( $extendedMetadata );
1611 // Make sure the metadata won't break the API when an XML format is used.
1612 // This is an API-specific function so it would be cleaner to call it from
1613 // outside fetchExtendedMetadata, but this way we don't need to redo the
1614 // computation on a cache hit.
1615 $this->sanitizeArrayForAPI( $extendedMetadata );
1616 $valueToCache = [ 'data' => $extendedMetadata, 'timestamp' => wfTimestampNow() ];
1617 $cache->set( $cacheKey, $valueToCache, $maxCacheTime );
1620 return $extendedMetadata;
1624 * Get file-based metadata in standardized format.
1626 * Note that for a remote file, this might return metadata supplied by extensions.
1628 * @param File $file File to use
1629 * @return array [<property name> => ['value' => <value>]], or [] on error
1632 protected function getExtendedMetadataFromFile( File
$file ) {
1633 // If this is a remote file accessed via an API request, we already
1634 // have remote metadata so we just ignore any local one
1635 if ( $file instanceof ForeignAPIFile
) {
1636 // In case of error we pretend no metadata - this will get cached.
1637 // Might or might not be a good idea.
1638 return $file->getExtendedMetadata() ?
: [];
1641 $uploadDate = wfTimestamp( TS_ISO_8601
, $file->getTimestamp() );
1644 // This is modification time, which is close to "upload" time.
1646 'value' => $uploadDate,
1647 'source' => 'mediawiki-metadata',
1651 $title = $file->getTitle();
1653 $text = $title->getText();
1654 $pos = strrpos( $text, '.' );
1657 $name = substr( $text, 0, $pos );
1662 $fileMetadata['ObjectName'] = [
1664 'source' => 'mediawiki-metadata',
1668 return $fileMetadata;
1672 * Get additional metadata from hooks in standardized format.
1674 * @param File $file File to use
1675 * @param array $extendedMetadata
1676 * @param int $maxCacheTime Hook handlers might use this parameter to override cache time
1678 * @return array [<property name> => ['value' => <value>]], or [] on error
1681 protected function getExtendedMetadataFromHook( File
$file, array $extendedMetadata,
1684 Hooks
::run( 'GetExtendedMetadata', [
1687 $this->getContext(),
1692 $visible = array_flip( self
::getVisibleFields() );
1693 foreach ( $extendedMetadata as $key => $value ) {
1694 if ( !isset( $visible[strtolower( $key )] ) ) {
1695 $extendedMetadata[$key]['hidden'] = '';
1699 return $extendedMetadata;
1703 * Turns an XMP-style multilang array into a single value.
1704 * If the value is not a multilang array, it is returned unchanged.
1705 * See mediawiki.org/wiki/Manual:File_metadata_handling#Multi-language_array_format
1706 * @param mixed $value
1707 * @return mixed Value in best language, null if there were no languages at all
1710 protected function resolveMultilangValue( $value ) {
1713 ||
!isset( $value['_type'] )
1714 ||
$value['_type'] != 'lang'
1716 return $value; // do nothing if not a multilang array
1719 // choose the language best matching user or site settings
1720 $priorityLanguages = $this->getPriorityLanguages();
1721 foreach ( $priorityLanguages as $lang ) {
1722 if ( isset( $value[$lang] ) ) {
1723 return $value[$lang];
1727 // otherwise go with the default language, if set
1728 if ( isset( $value['x-default'] ) ) {
1729 return $value['x-default'];
1732 // otherwise just return any one language
1733 unset( $value['_type'] );
1734 if ( !empty( $value ) ) {
1735 return reset( $value );
1738 // this should not happen; signal error
1743 * Turns an XMP-style multivalue array into a single value by dropping all but the first
1744 * value. If the value is not a multivalue array (or a multivalue array inside a multilang
1745 * array), it is returned unchanged.
1746 * See mediawiki.org/wiki/Manual:File_metadata_handling#Multi-language_array_format
1747 * @param mixed $value
1748 * @return mixed The value, or the first value if there were multiple ones
1751 protected function resolveMultivalueValue( $value ) {
1752 if ( !is_array( $value ) ) {
1754 } elseif ( isset( $value['_type'] ) && $value['_type'] === 'lang' ) {
1755 // if this is a multilang array, process fields separately
1757 foreach ( $value as $k => $v ) {
1758 $newValue[$k] = $this->resolveMultivalueValue( $v );
1761 } else { // _type is 'ul' or 'ol' or missing in which case it defaults to 'ul'
1762 list( $k, $v ) = each( $value );
1763 if ( $k === '_type' ) {
1764 $v = current( $value );
1771 * Takes an array returned by the getExtendedMetadata* functions,
1772 * and resolves multi-language values in it.
1773 * @param array $metadata
1776 protected function resolveMultilangMetadata( &$metadata ) {
1777 if ( !is_array( $metadata ) ) {
1780 foreach ( $metadata as &$field ) {
1781 if ( isset( $field['value'] ) ) {
1782 $field['value'] = $this->resolveMultilangValue( $field['value'] );
1788 * Takes an array returned by the getExtendedMetadata* functions,
1789 * and turns all fields into single-valued ones by dropping extra values.
1790 * @param array $metadata
1793 protected function discardMultipleValues( &$metadata ) {
1794 if ( !is_array( $metadata ) ) {
1797 foreach ( $metadata as $key => &$field ) {
1798 if ( $key === 'Software' ||
$key === 'Contact' ) {
1799 // we skip some fields which have composite values. They are not particularly interesting
1800 // and you can get them via the metadata / commonmetadata APIs anyway.
1803 if ( isset( $field['value'] ) ) {
1804 $field['value'] = $this->resolveMultivalueValue( $field['value'] );
1810 * Makes sure the given array is a valid API response fragment
1813 protected function sanitizeArrayForAPI( &$arr ) {
1814 if ( !is_array( $arr ) ) {
1819 foreach ( $arr as $key => &$value ) {
1820 $sanitizedKey = $this->sanitizeKeyForAPI( $key );
1821 if ( $sanitizedKey !== $key ) {
1822 if ( isset( $arr[$sanitizedKey] ) ) {
1823 // Make the sanitized keys hopefully unique.
1824 // To make it definitely unique would be too much effort, given that
1825 // sanitizing is only needed for misformatted metadata anyway, but
1826 // this at least covers the case when $arr is numeric.
1827 $sanitizedKey .= $counter;
1830 $arr[$sanitizedKey] = $arr[$key];
1831 unset( $arr[$key] );
1833 if ( is_array( $value ) ) {
1834 $this->sanitizeArrayForAPI( $value );
1838 // Handle API metadata keys (particularly "_type")
1839 $keys = array_filter( array_keys( $arr ), 'ApiResult::isMetadataKey' );
1841 ApiResult
::setPreserveKeysList( $arr, $keys );
1846 * Turns a string into a valid API identifier.
1847 * @param string $key
1851 protected function sanitizeKeyForAPI( $key ) {
1852 // drop all characters which are not valid in an XML tag name
1853 // a bunch of non-ASCII letters would be valid but probably won't
1854 // be used so we take the easy way
1855 $key = preg_replace( '/[^a-zA-z0-9_:.-]/', '', $key );
1856 // drop characters which are invalid at the first position
1857 $key = preg_replace( '/^[\d-.]+/', '', $key );
1863 // special case for an internal keyword
1864 if ( $key == '_element' ) {
1872 * Returns a list of languages (first is best) to use when formatting multilang fields,
1873 * based on user and site preferences.
1877 protected function getPriorityLanguages() {
1878 $priorityLanguages =
1879 Language
::getFallbacksIncludingSiteLanguage( $this->getLanguage()->getCode() );
1880 $priorityLanguages = array_merge(
1881 (array)$this->getLanguage()->getCode(),
1882 $priorityLanguages[0],
1883 $priorityLanguages[1]
1886 return $priorityLanguages;