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 ) {
106 // This seems ugly to wrap non-array's in an array just to unwrap again,
107 // especially when most of the time it is not an array
108 if ( !is_array( $tags[$tag] ) ) {
109 $vals = array( $vals );
112 // _type is a special value to say what array type
113 if ( isset( $tags[$tag]['_type'] ) ) {
114 $type = $tags[$tag]['_type'];
115 unset( $vals['_type'] );
117 $type = 'ul'; // default unordered list.
120 //This is done differently as the tag is an array.
121 if ( $tag == 'GPSTimeStamp' && count( $vals ) === 3 ) {
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 ) {
183 $val = $this->exifMsg( $tag, $val );
186 /* If not recognized, display as is. */
191 case 'PhotometricInterpretation':
195 $val = $this->exifMsg( $tag, $val );
198 /* If not recognized, display as is. */
213 $val = $this->exifMsg( $tag, $val );
216 /* If not recognized, display as is. */
221 case 'PlanarConfiguration':
225 $val = $this->exifMsg( $tag, $val );
228 /* If not recognized, display as is. */
233 // TODO: YCbCrSubSampling
234 case 'YCbCrPositioning':
238 $val = $this->exifMsg( $tag, $val );
241 /* If not recognized, display as is. */
248 switch ( $resolutionunit ) {
250 $val = $this->exifMsg( 'XYResolution', 'i', $this->formatNum( $val ) );
253 $val = $this->exifMsg( 'XYResolution', 'c', $this->formatNum( $val ) );
256 /* If not recognized, display as is. */
261 // TODO: YCbCrCoefficients #p27 (see annex E)
263 case 'FlashpixVersion':
271 $val = $this->exifMsg( $tag, $val );
274 /* If not recognized, display as is. */
279 case 'ComponentsConfiguration':
288 $val = $this->exifMsg( $tag, $val );
291 /* If not recognized, display as is. */
297 case 'DateTimeOriginal':
298 case 'DateTimeDigitized':
299 case 'DateTimeReleased':
300 case 'DateTimeExpires':
303 case 'DateTimeMetadata':
304 if ( $val == '0000:00:00 00:00:00' ||
$val == ' : : : : ' ) {
305 $val = $this->msg( 'exif-unknowndate' )->text();
306 } elseif ( preg_match(
307 '/^(?:\d{4}):(?:\d\d):(?:\d\d) (?:\d\d):(?:\d\d):(?:\d\d)$/D',
311 $time = wfTimestamp( TS_MW
, $val );
312 if ( $time && intval( $time ) > 0 ) {
313 $val = $this->getLanguage()->timeanddate( $time );
315 } elseif ( preg_match( '/^(?:\d{4}):(?:\d\d):(?:\d\d) (?:\d\d):(?:\d\d)$/D', $val ) ) {
316 // No second field. Still format the same
317 // since timeanddate doesn't include seconds anyways,
318 // but second still available in api
319 $time = wfTimestamp( TS_MW
, $val . ':00' );
320 if ( $time && intval( $time ) > 0 ) {
321 $val = $this->getLanguage()->timeanddate( $time );
323 } elseif ( preg_match( '/^(?:\d{4}):(?:\d\d):(?:\d\d)$/D', $val ) ) {
324 // If only the date but not the time is filled in.
325 $time = wfTimestamp( TS_MW
, substr( $val, 0, 4 )
326 . substr( $val, 5, 2 )
327 . substr( $val, 8, 2 )
329 if ( $time && intval( $time ) > 0 ) {
330 $val = $this->getLanguage()->date( $time );
333 // else it will just output $val without formatting it.
336 case 'ExposureProgram':
347 $val = $this->exifMsg( $tag, $val );
350 /* If not recognized, display as is. */
355 case 'SubjectDistance':
356 $val = $this->exifMsg( $tag, '', $this->formatNum( $val ) );
370 $val = $this->exifMsg( $tag, $val );
373 /* If not recognized, display as is. */
401 $val = $this->exifMsg( $tag, $val );
404 /* If not recognized, display as is. */
410 $flashDecode = array(
411 'fired' => $val & bindec( '00000001' ),
412 'return' => ( $val & bindec( '00000110' ) ) >> 1,
413 'mode' => ( $val & bindec( '00011000' ) ) >> 3,
414 'function' => ( $val & bindec( '00100000' ) ) >> 5,
415 'redeye' => ( $val & bindec( '01000000' ) ) >> 6,
416 // 'reserved' => ($val & bindec( '10000000' )) >> 7,
418 $flashMsgs = array();
419 # We do not need to handle unknown values since all are used.
420 foreach ( $flashDecode as $subTag => $subValue ) {
421 # We do not need any message for zeroed values.
422 if ( $subTag != 'fired' && $subValue == 0 ) {
425 $fullTag = $tag . '-' . $subTag;
426 $flashMsgs[] = $this->exifMsg( $fullTag, $subValue );
428 $val = $this->getLanguage()->commaList( $flashMsgs );
431 case 'FocalPlaneResolutionUnit':
434 $val = $this->exifMsg( $tag, $val );
437 /* If not recognized, display as is. */
442 case 'SensingMethod':
451 $val = $this->exifMsg( $tag, $val );
454 /* If not recognized, display as is. */
462 $val = $this->exifMsg( $tag, $val );
465 /* If not recognized, display as is. */
473 $val = $this->exifMsg( $tag, $val );
476 /* If not recognized, display as is. */
481 case 'CustomRendered':
485 $val = $this->exifMsg( $tag, $val );
488 /* If not recognized, display as is. */
498 $val = $this->exifMsg( $tag, $val );
501 /* If not recognized, display as is. */
510 $val = $this->exifMsg( $tag, $val );
513 /* If not recognized, display as is. */
518 case 'SceneCaptureType':
524 $val = $this->exifMsg( $tag, $val );
527 /* If not recognized, display as is. */
539 $val = $this->exifMsg( $tag, $val );
542 /* 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. */
586 case 'SubjectDistanceRange':
592 $val = $this->exifMsg( $tag, $val );
595 /* If not recognized, display as is. */
600 //The GPS...Ref values are kept for compatibility, probably won't be reached.
601 case 'GPSLatitudeRef':
602 case 'GPSDestLatitudeRef':
606 $val = $this->exifMsg( 'GPSLatitude', $val );
609 /* If not recognized, display as is. */
614 case 'GPSLongitudeRef':
615 case 'GPSDestLongitudeRef':
619 $val = $this->exifMsg( 'GPSLongitude', $val );
622 /* If not recognized, display as is. */
629 $val = $this->exifMsg( 'GPSAltitude', 'below-sealevel', $this->formatNum( -$val, 3 ) );
631 $val = $this->exifMsg( 'GPSAltitude', 'above-sealevel', $this->formatNum( $val, 3 ) );
639 $val = $this->exifMsg( $tag, $val );
642 /* If not recognized, display as is. */
647 case 'GPSMeasureMode':
651 $val = $this->exifMsg( $tag, $val );
654 /* If not recognized, display as is. */
660 case 'GPSImgDirectionRef':
661 case 'GPSDestBearingRef':
665 $val = $this->exifMsg( 'GPSDirection', $val );
668 /* If not recognized, display as is. */
674 case 'GPSDestLatitude':
675 $val = $this->formatCoords( $val, 'latitude' );
678 case 'GPSDestLongitude':
679 $val = $this->formatCoords( $val, 'longitude' );
687 $val = $this->exifMsg( 'GPSSpeed', $val );
690 /* If not recognized, display as is. */
695 case 'GPSDestDistanceRef':
700 $val = $this->exifMsg( 'GPSDestDistance', $val );
703 /* If not recognized, display as is. */
709 // See https://en.wikipedia.org/wiki/Dilution_of_precision_(GPS)
711 $val = $this->exifMsg( $tag, 'excellent', $this->formatNum( $val ) );
712 } elseif ( $val <= 5 ) {
713 $val = $this->exifMsg( $tag, 'good', $this->formatNum( $val ) );
714 } elseif ( $val <= 10 ) {
715 $val = $this->exifMsg( $tag, 'moderate', $this->formatNum( $val ) );
716 } elseif ( $val <= 20 ) {
717 $val = $this->exifMsg( $tag, 'fair', $this->formatNum( $val ) );
719 $val = $this->exifMsg( $tag, 'poor', $this->formatNum( $val ) );
723 // This is not in the Exif standard, just a special
724 // case for our purposes which enables wikis to wikify
725 // the make, model and software name to link to their articles.
728 $val = $this->exifMsg( $tag, '', $val );
732 if ( is_array( $val ) ) {
733 //if its a software, version array.
734 $val = $this->msg( 'exif-software-version-value', $val[0], $val[1] )->text();
736 $val = $this->exifMsg( $tag, '', $val );
741 // Show the pretty fraction as well as decimal version
742 $val = $this->msg( 'exif-exposuretime-format',
743 $this->formatFraction( $val ), $this->formatNum( $val ) )->text();
745 case 'ISOSpeedRatings':
746 // If its = 65535 that means its at the
747 // limit of the size of Exif::short and
749 if ( $val == '65535' ) {
750 $val = $this->exifMsg( $tag, 'overflow' );
752 $val = $this->formatNum( $val );
756 $val = $this->msg( 'exif-fnumber-format',
757 $this->formatNum( $val ) )->text();
761 case 'FocalLengthIn35mmFilm':
762 $val = $this->msg( 'exif-focallength-format',
763 $this->formatNum( $val ) )->text();
766 case 'MaxApertureValue':
767 if ( strpos( $val, '/' ) !== false ) {
768 // need to expand this earlier to calculate fNumber
769 list( $n, $d ) = explode( '/', $val );
770 if ( is_numeric( $n ) && is_numeric( $d ) ) {
774 if ( is_numeric( $val ) ) {
775 $fNumber = pow( 2, $val / 2 );
776 if ( $fNumber !== false ) {
777 $val = $this->msg( 'exif-maxaperturevalue-value',
778 $this->formatNum( $val ),
779 $this->formatNum( $fNumber, 2 )
786 switch ( strtolower( $val ) ) {
787 // See pg 29 of IPTC photo
788 // metadata standard.
806 $val = $this->exifMsg(
812 case 'SubjectNewsCode':
813 // Essentially like iimCategory.
814 // 8 (numeric) digit hierarchical
815 // classification. We decode the
816 // first 2 digits, which provide
818 $val = $this->convertNewsCode( $val );
821 // 1-8 with 1 being highest, 5 normal
822 // 0 is reserved, and 9 is 'user-defined'.
824 if ( $val == 0 ||
$val == 9 ) {
826 } elseif ( $val < 5 && $val > 1 ) {
828 } elseif ( $val == 5 ) {
830 } elseif ( $val <= 8 && $val > 5 ) {
834 if ( $urgency !== '' ) {
835 $val = $this->exifMsg( 'urgency',
841 // Things that have a unit of pixels.
842 case 'OriginalImageHeight':
843 case 'OriginalImageWidth':
844 case 'PixelXDimension':
845 case 'PixelYDimension':
848 $val = $this->formatNum( $val ) . ' ' . $this->msg( 'unit-pixel' )->text();
851 // Do not transform fields with pure text.
852 // For some languages the formatNum()
853 // conversion results to wrong output like
854 // foo,bar@example,com or foo٫bar@example٫com.
855 // Also some 'numeric' things like Scene codes
856 // are included here as we really don't want
858 case 'ImageDescription':
861 case 'RelatedSoundFile':
862 case 'ImageUniqueID':
863 case 'SpectralSensitivity':
864 case 'GPSSatellites':
868 case 'WorldRegionDest':
870 case 'CountryCodeDest':
871 case 'ProvinceOrStateDest':
873 case 'SublocationDest':
874 case 'WorldRegionCreated':
875 case 'CountryCreated':
876 case 'CountryCodeCreated':
877 case 'ProvinceOrStateCreated':
879 case 'SublocationCreated':
881 case 'SpecialInstructions':
886 case 'FixtureIdentifier':
888 case 'LocationDestCode':
890 case 'JPEGFileComment':
891 case 'iimSupplementalCategory':
892 case 'OriginalTransmissionRef':
894 case 'dc-contributor':
903 case 'CameraOwnerName':
906 case 'RightsCertificate':
907 case 'CopyrightOwner':
910 case 'OriginalDocumentID':
912 case 'MorePermissionsUrl':
913 case 'AttributionUrl':
914 case 'PreferredAttributionName':
915 case 'PNGFileComment':
917 case 'ContentWarning':
918 case 'GIFFileComment':
920 case 'IntellectualGenre':
922 case 'OrginisationInImage':
923 case 'PersonInImage':
925 $val = htmlspecialchars( $val );
933 $val = $this->exifMsg( $tag, $val );
936 $val = htmlspecialchars( $val );
944 $val = $this->exifMsg( $tag, $val );
949 if ( $val == '-1' ) {
950 $val = $this->exifMsg( $tag, 'rejected' );
952 $val = $this->formatNum( $val );
957 $lang = Language
::fetchLanguageName( strtolower( $val ), $this->getLanguage()->getCode() );
959 $val = htmlspecialchars( $lang );
961 $val = htmlspecialchars( $val );
966 $val = $this->formatNum( $val );
970 // End formatting values, start flattening arrays.
971 $vals = $this->flattenArrayReal( $vals, $type );
978 * Flatten an array, using the content language for any messages.
980 * @param array $vals Array of values
981 * @param string $type Type of array (either lang, ul, ol).
982 * lang = language assoc array with keys being the lang code
983 * ul = unordered list, ol = ordered list
984 * type can also come from the '_type' member of $vals.
985 * @param bool $noHtml If to avoid returning anything resembling HTML.
986 * (Ugly hack for backwards compatibility with old MediaWiki).
987 * @param bool|IContextSource $context
988 * @return string Single value (in wiki-syntax).
991 public static function flattenArrayContentLang( $vals, $type = 'ul',
992 $noHtml = false, $context = false
995 $obj = new FormatMetadata
;
997 $obj->setContext( $context );
999 $context = new DerivativeContext( $obj->getContext() );
1000 $context->setLanguage( $wgContLang );
1001 $obj->setContext( $context );
1003 return $obj->flattenArrayReal( $vals, $type, $noHtml );
1007 * A function to collapse multivalued tags into a single value.
1008 * This turns an array of (for example) authors into a bulleted list.
1010 * This is public on the basis it might be useful outside of this class.
1012 * @param array $vals Array of values
1013 * @param string $type Type of array (either lang, ul, ol).
1014 * lang = language assoc array with keys being the lang code
1015 * ul = unordered list, ol = ordered list
1016 * type can also come from the '_type' member of $vals.
1017 * @param bool $noHtml If to avoid returning anything resembling HTML.
1018 * (Ugly hack for backwards compatibility with old mediawiki).
1019 * @return string Single value (in wiki-syntax).
1022 public function flattenArrayReal( $vals, $type = 'ul', $noHtml = false ) {
1023 if ( !is_array( $vals ) ) {
1024 return $vals; // do nothing if not an array;
1027 if ( isset( $vals['_type'] ) ) {
1028 $type = $vals['_type'];
1029 unset( $vals['_type'] );
1032 if ( !is_array( $vals ) ) {
1033 return $vals; // do nothing if not an array;
1034 } elseif ( count( $vals ) === 1 && $type !== 'lang' ) {
1036 } elseif ( count( $vals ) === 0 ) {
1037 wfDebug( __METHOD__
. " metadata array with 0 elements!\n" );
1039 return ""; // paranoia. This should never happen
1041 /* @todo FIXME: This should hide some of the list entries if there are
1042 * say more than four. Especially if a field is translated into 20
1043 * languages, we don't want to show them all by default
1047 // Display default, followed by ContLang,
1048 // followed by the rest in no particular
1051 // Todo: hide some items if really long list.
1055 $priorityLanguages = $this->getPriorityLanguages();
1056 $defaultItem = false;
1057 $defaultLang = false;
1059 // If default is set, save it for later,
1060 // as we don't know if it's equal to
1061 // one of the lang codes. (In xmp
1062 // you specify the language for a
1063 // default property by having both
1064 // a default prop, and one in the language
1065 // that are identical)
1066 if ( isset( $vals['x-default'] ) ) {
1067 $defaultItem = $vals['x-default'];
1068 unset( $vals['x-default'] );
1070 foreach ( $priorityLanguages as $pLang ) {
1071 if ( isset( $vals[$pLang] ) ) {
1073 if ( $vals[$pLang] === $defaultItem ) {
1074 $defaultItem = false;
1077 $content .= $this->langItem(
1078 $vals[$pLang], $pLang,
1079 $isDefault, $noHtml );
1081 unset( $vals[$pLang] );
1083 if ( $this->singleLang
) {
1084 return Html
::rawElement( 'span',
1085 array( 'lang' => $pLang ), $vals[$pLang] );
1091 foreach ( $vals as $lang => $item ) {
1092 if ( $item === $defaultItem ) {
1093 $defaultLang = $lang;
1096 $content .= $this->langItem( $item,
1097 $lang, false, $noHtml );
1098 if ( $this->singleLang
) {
1099 return Html
::rawElement( 'span',
1100 array( 'lang' => $lang ), $item );
1103 if ( $defaultItem !== false ) {
1104 $content = $this->langItem( $defaultItem,
1105 $defaultLang, true, $noHtml ) .
1107 if ( $this->singleLang
) {
1108 return $defaultItem;
1115 return '<ul class="metadata-langlist">' .
1120 return "\n#" . implode( "\n#", $vals );
1123 return "<ol><li>" . implode( "</li>\n<li>", $vals ) . '</li></ol>';
1127 return "\n*" . implode( "\n*", $vals );
1130 return "<ul><li>" . implode( "</li>\n<li>", $vals ) . '</li></ul>';
1135 /** Helper function for creating lists of translations.
1137 * @param string $value Value (this is not escaped)
1138 * @param string $lang Lang code of item or false
1139 * @param bool $default If it is default value.
1140 * @param bool $noHtml If to avoid html (for back-compat)
1141 * @throws MWException
1142 * @return string Language item (Note: despite how this looks, this is
1143 * treated as wikitext, not as HTML).
1145 private function langItem( $value, $lang, $default = false, $noHtml = false ) {
1146 if ( $lang === false && $default === false ) {
1147 throw new MWException( '$lang and $default cannot both '
1152 $wrappedValue = $value;
1154 $wrappedValue = '<span class="mw-metadata-lang-value">'
1155 . $value . '</span>';
1158 if ( $lang === false ) {
1159 $msg = $this->msg( 'metadata-langitem-default', $wrappedValue );
1161 return $msg->text() . "\n\n";
1164 return '<li class="mw-metadata-lang-default">'
1169 $lowLang = strtolower( $lang );
1170 $langName = Language
::fetchLanguageName( $lowLang );
1171 if ( $langName === '' ) {
1172 //try just the base language name. (aka en-US -> en ).
1173 list( $langPrefix ) = explode( '-', $lowLang, 2 );
1174 $langName = Language
::fetchLanguageName( $langPrefix );
1175 if ( $langName === '' ) {
1180 // else we have a language specified
1182 $msg = $this->msg( 'metadata-langitem', $wrappedValue, $langName, $lang );
1184 return '*' . $msg->text();
1187 $item = '<li class="mw-metadata-lang-code-'
1190 $item .= ' mw-metadata-lang-default';
1192 $item .= '" lang="' . $lang . '">';
1193 $item .= $msg->text();
1200 * Convenience function for getFormattedData()
1202 * @param string $tag The tag name to pass on
1203 * @param string $val The value of the tag
1204 * @param string $arg An argument to pass ($1)
1205 * @param string $arg2 A 2nd argument to pass ($2)
1206 * @return string The text content of "exif-$tag-$val" message in lower case
1208 private function exifMsg( $tag, $val, $arg = null, $arg2 = null ) {
1211 if ( $val === '' ) {
1215 return $this->msg( $wgContLang->lc( "exif-$tag-$val" ), $arg, $arg2 )->text();
1219 * Format a number, convert numbers from fractions into floating point
1220 * numbers, joins arrays of numbers with commas.
1222 * @param mixed $num The value to format
1223 * @param float|int|bool $round Digits to round to or false.
1224 * @return mixed A floating point number or whatever we were fed
1226 private function formatNum( $num, $round = false ) {
1228 if ( is_array( $num ) ) {
1230 foreach ( $num as $number ) {
1231 $out[] = $this->formatNum( $number );
1234 return $this->getLanguage()->commaList( $out );
1236 if ( preg_match( '/^(-?\d+)\/(\d+)$/', $num, $m ) ) {
1238 $newNum = $m[1] / $m[2];
1239 if ( $round !== false ) {
1240 $newNum = round( $newNum, $round );
1246 return $this->getLanguage()->formatNum( $newNum );
1248 if ( is_numeric( $num ) && $round !== false ) {
1249 $num = round( $num, $round );
1252 return $this->getLanguage()->formatNum( $num );
1257 * Format a rational number, reducing fractions
1259 * @param mixed $num The value to format
1260 * @return mixed A floating point number or whatever we were fed
1262 private function formatFraction( $num ) {
1264 if ( preg_match( '/^(-?\d+)\/(\d+)$/', $num, $m ) ) {
1265 $numerator = intval( $m[1] );
1266 $denominator = intval( $m[2] );
1267 $gcd = $this->gcd( abs( $numerator ), $denominator );
1269 // 0 shouldn't happen! ;)
1270 return $this->formatNum( $numerator / $gcd ) . '/' . $this->formatNum( $denominator / $gcd );
1274 return $this->formatNum( $num );
1278 * Calculate the greatest common divisor of two integers.
1280 * @param int $a Numerator
1281 * @param int $b Denominator
1284 private function gcd( $a, $b ) {
1286 // https://en.wikipedia.org/wiki/Euclidean_algorithm
1287 // Recursive form would be:
1291 return gcd( $b, $a % $b );
1294 $remainder = $a %
$b;
1296 // tail recursion...
1305 * Fetch the human readable version of a news code.
1306 * A news code is an 8 digit code. The first two
1307 * digits are a general classification, so we just
1310 * Note, leading 0's are significant, so this is
1311 * a string, not an int.
1313 * @param string $val The 8 digit news code.
1314 * @return string The human readable form
1316 private function convertNewsCode( $val ) {
1317 if ( !preg_match( '/^\d{8}$/D', $val ) ) {
1318 // Not a valid news code.
1322 switch ( substr( $val, 0, 2 ) ) {
1375 if ( $cat !== '' ) {
1376 $catMsg = $this->exifMsg( 'iimcategory', $cat );
1377 $val = $this->exifMsg( 'subjectnewscode', '', $val, $catMsg );
1384 * Format a coordinate value, convert numbers from floating point
1385 * into degree minute second representation.
1387 * @param int $coord Degrees, minutes and seconds
1388 * @param string $type Latitude or longitude (for if its a NWS or E)
1389 * @return mixed A floating point number or whatever we were fed
1391 private function formatCoords( $coord, $type ) {
1395 if ( $type === 'latitude' ) {
1397 } elseif ( $type === 'longitude' ) {
1402 if ( $type === 'latitude' ) {
1404 } elseif ( $type === 'longitude' ) {
1409 $deg = floor( $nCoord );
1410 $min = floor( ( $nCoord - $deg ) * 60.0 );
1411 $sec = round( ( ( $nCoord - $deg ) - $min / 60 ) * 3600, 2 );
1413 $deg = $this->formatNum( $deg );
1414 $min = $this->formatNum( $min );
1415 $sec = $this->formatNum( $sec );
1417 return $this->msg( 'exif-coordinate-format', $deg, $min, $sec, $ref, $coord )->text();
1421 * Format the contact info field into a single value.
1423 * This function might be called from
1424 * JpegHandler::convertMetadataVersion which is why it is
1427 * @param array $vals Array with fields of the ContactInfo
1428 * struct defined in the IPTC4XMP spec. Or potentially
1429 * an array with one element that is a free form text
1430 * value from the older iptc iim 1:118 prop.
1431 * @return string HTML-ish looking wikitext
1432 * @since 1.23 no longer static
1434 public function collapseContactInfo( $vals ) {
1435 if ( !( isset( $vals['CiAdrExtadr'] )
1436 ||
isset( $vals['CiAdrCity'] )
1437 ||
isset( $vals['CiAdrCtry'] )
1438 ||
isset( $vals['CiEmailWork'] )
1439 ||
isset( $vals['CiTelWork'] )
1440 ||
isset( $vals['CiAdrPcode'] )
1441 ||
isset( $vals['CiAdrRegion'] )
1442 ||
isset( $vals['CiUrlWork'] )
1444 // We don't have any sub-properties
1445 // This could happen if its using old
1446 // iptc that just had this as a free-form
1448 // Note: We run this through htmlspecialchars
1449 // partially to be consistent, and partially
1450 // because people often insert >, etc into
1451 // the metadata which should not be interpreted
1452 // but we still want to auto-link urls.
1453 foreach ( $vals as &$val ) {
1454 $val = htmlspecialchars( $val );
1457 return $this->flattenArrayReal( $vals );
1459 // We have a real ContactInfo field.
1460 // Its unclear if all these fields have to be
1461 // set, so assume they do not.
1462 $url = $tel = $street = $city = $country = '';
1463 $email = $postal = $region = '';
1465 // Also note, some of the class names this uses
1466 // are similar to those used by hCard. This is
1467 // mostly because they're sensible names. This
1468 // does not (and does not attempt to) output
1469 // stuff in the hCard microformat. However it
1470 // might output in the adr microformat.
1472 if ( isset( $vals['CiAdrExtadr'] ) ) {
1473 // Todo: This can potentially be multi-line.
1474 // Need to check how that works in XMP.
1475 $street = '<span class="extended-address">'
1477 $vals['CiAdrExtadr'] )
1480 if ( isset( $vals['CiAdrCity'] ) ) {
1481 $city = '<span class="locality">'
1482 . htmlspecialchars( $vals['CiAdrCity'] )
1485 if ( isset( $vals['CiAdrCtry'] ) ) {
1486 $country = '<span class="country-name">'
1487 . htmlspecialchars( $vals['CiAdrCtry'] )
1490 if ( isset( $vals['CiEmailWork'] ) ) {
1492 // Have to split multiple emails at commas/new lines.
1493 $splitEmails = explode( "\n", $vals['CiEmailWork'] );
1494 foreach ( $splitEmails as $e1 ) {
1495 // Also split on comma
1496 foreach ( explode( ',', $e1 ) as $e2 ) {
1497 $finalEmail = trim( $e2 );
1498 if ( $finalEmail == ',' ||
$finalEmail == '' ) {
1501 if ( strpos( $finalEmail, '<' ) !== false ) {
1502 // Don't do fancy formatting to
1503 // "My name" <foo@bar.com> style stuff
1504 $emails[] = $finalEmail;
1506 $emails[] = '[mailto:'
1508 . ' <span class="email">'
1514 $email = implode( ', ', $emails );
1516 if ( isset( $vals['CiTelWork'] ) ) {
1517 $tel = '<span class="tel">'
1518 . htmlspecialchars( $vals['CiTelWork'] )
1521 if ( isset( $vals['CiAdrPcode'] ) ) {
1522 $postal = '<span class="postal-code">'
1524 $vals['CiAdrPcode'] )
1527 if ( isset( $vals['CiAdrRegion'] ) ) {
1528 // Note this is province/state.
1529 $region = '<span class="region">'
1531 $vals['CiAdrRegion'] )
1534 if ( isset( $vals['CiUrlWork'] ) ) {
1535 $url = '<span class="url">'
1536 . htmlspecialchars( $vals['CiUrlWork'] )
1540 return $this->msg( 'exif-contact-value', $email, $url,
1541 $street, $city, $region, $postal, $country,
1547 * Get a list of fields that are visible by default.
1552 public static function getVisibleFields() {
1554 $lines = explode( "\n", wfMessage( 'metadata-fields' )->inContentLanguage()->text() );
1555 foreach ( $lines as $line ) {
1557 if ( preg_match( '/^\\*\s*(.*?)\s*$/', $line, $matches ) ) {
1558 $fields[] = $matches[1];
1561 $fields = array_map( 'strtolower', $fields );
1567 * Get an array of extended metadata. (See the imageinfo API for format.)
1569 * @param File $file File to use
1570 * @return array [<property name> => ['value' => <value>]], or [] on error
1573 public function fetchExtendedMetadata( File
$file ) {
1576 // If revision deleted, exit immediately
1577 if ( $file->isDeleted( File
::DELETED_FILE
) ) {
1582 $cacheKey = wfMemcKey(
1583 'getExtendedMetadata',
1584 $this->getLanguage()->getCode(),
1585 (int)$this->singleLang
,
1589 $cachedValue = $wgMemc->get( $cacheKey );
1592 && Hooks
::run( 'ValidateExtendedMetadataCache', array( $cachedValue['timestamp'], $file ) )
1594 $extendedMetadata = $cachedValue['data'];
1596 $maxCacheTime = ( $file instanceof ForeignAPIFile
) ?
60 * 60 * 12 : 60 * 60 * 24 * 30;
1597 $fileMetadata = $this->getExtendedMetadataFromFile( $file );
1598 $extendedMetadata = $this->getExtendedMetadataFromHook( $file, $fileMetadata, $maxCacheTime );
1599 if ( $this->singleLang
) {
1600 $this->resolveMultilangMetadata( $extendedMetadata );
1602 $this->discardMultipleValues( $extendedMetadata );
1603 // Make sure the metadata won't break the API when an XML format is used.
1604 // This is an API-specific function so it would be cleaner to call it from
1605 // outside fetchExtendedMetadata, but this way we don't need to redo the
1606 // computation on a cache hit.
1607 $this->sanitizeArrayForAPI( $extendedMetadata );
1608 $valueToCache = array( 'data' => $extendedMetadata, 'timestamp' => wfTimestampNow() );
1609 $wgMemc->set( $cacheKey, $valueToCache, $maxCacheTime );
1612 return $extendedMetadata;
1616 * Get file-based metadata in standardized format.
1618 * Note that for a remote file, this might return metadata supplied by extensions.
1620 * @param File $file File to use
1621 * @return array [<property name> => ['value' => <value>]], or [] on error
1624 protected function getExtendedMetadataFromFile( File
$file ) {
1625 // If this is a remote file accessed via an API request, we already
1626 // have remote metadata so we just ignore any local one
1627 if ( $file instanceof ForeignAPIFile
) {
1628 // In case of error we pretend no metadata - this will get cached.
1629 // Might or might not be a good idea.
1630 return $file->getExtendedMetadata() ?
: array();
1633 $uploadDate = wfTimestamp( TS_ISO_8601
, $file->getTimestamp() );
1635 $fileMetadata = array(
1636 // This is modification time, which is close to "upload" time.
1637 'DateTime' => array(
1638 'value' => $uploadDate,
1639 'source' => 'mediawiki-metadata',
1643 $title = $file->getTitle();
1645 $text = $title->getText();
1646 $pos = strrpos( $text, '.' );
1649 $name = substr( $text, 0, $pos );
1654 $fileMetadata['ObjectName'] = array(
1656 'source' => 'mediawiki-metadata',
1660 return $fileMetadata;
1664 * Get additional metadata from hooks in standardized format.
1666 * @param File $file File to use
1667 * @param array $extendedMetadata
1668 * @param int $maxCacheTime Hook handlers might use this parameter to override cache time
1670 * @return array [<property name> => ['value' => <value>]], or [] on error
1673 protected function getExtendedMetadataFromHook( File
$file, array $extendedMetadata,
1677 Hooks
::run( 'GetExtendedMetadata', array(
1680 $this->getContext(),
1685 $visible = array_flip( self
::getVisibleFields() );
1686 foreach ( $extendedMetadata as $key => $value ) {
1687 if ( !isset( $visible[strtolower( $key )] ) ) {
1688 $extendedMetadata[$key]['hidden'] = '';
1692 return $extendedMetadata;
1696 * Turns an XMP-style multilang array into a single value.
1697 * If the value is not a multilang array, it is returned unchanged.
1698 * See mediawiki.org/wiki/Manual:File_metadata_handling#Multi-language_array_format
1699 * @param mixed $value
1700 * @return mixed Value in best language, null if there were no languages at all
1703 protected function resolveMultilangValue( $value ) {
1706 ||
!isset( $value['_type'] )
1707 ||
$value['_type'] != 'lang'
1709 return $value; // do nothing if not a multilang array
1712 // choose the language best matching user or site settings
1713 $priorityLanguages = $this->getPriorityLanguages();
1714 foreach ( $priorityLanguages as $lang ) {
1715 if ( isset( $value[$lang] ) ) {
1716 return $value[$lang];
1720 // otherwise go with the default language, if set
1721 if ( isset( $value['x-default'] ) ) {
1722 return $value['x-default'];
1725 // otherwise just return any one language
1726 unset( $value['_type'] );
1727 if ( !empty( $value ) ) {
1728 return reset( $value );
1731 // this should not happen; signal error
1736 * Turns an XMP-style multivalue array into a single value by dropping all but the first value.
1737 * If the value is not a multivalue array (or a multivalue array inside a multilang array), it is returned unchanged.
1738 * See mediawiki.org/wiki/Manual:File_metadata_handling#Multi-language_array_format
1739 * @param mixed $value
1740 * @return mixed The value, or the first value if there were multiple ones
1743 protected function resolveMultivalueValue( $value ) {
1744 if ( !is_array( $value ) ) {
1746 } elseif ( isset( $value['_type'] ) && $value['_type'] === 'lang' ) { // if this is a multilang array, process fields separately
1747 $newValue = array();
1748 foreach ( $value as $k => $v ) {
1749 $newValue[$k] = $this->resolveMultivalueValue( $v );
1752 } else { // _type is 'ul' or 'ol' or missing in which case it defaults to 'ul'
1753 list( $k, $v ) = each( $value );
1754 if ( $k === '_type' ) {
1755 $v = current( $value );
1762 * Takes an array returned by the getExtendedMetadata* functions,
1763 * and resolves multi-language values in it.
1764 * @param array $metadata
1767 protected function resolveMultilangMetadata( &$metadata ) {
1768 if ( !is_array( $metadata ) ) {
1771 foreach ( $metadata as &$field ) {
1772 if ( isset( $field['value'] ) ) {
1773 $field['value'] = $this->resolveMultilangValue( $field['value'] );
1779 * Takes an array returned by the getExtendedMetadata* functions,
1780 * and turns all fields into single-valued ones by dropping extra values.
1781 * @param array $metadata
1784 protected function discardMultipleValues( &$metadata ) {
1785 if ( !is_array( $metadata ) ) {
1788 foreach ( $metadata as $key => &$field ) {
1789 if ( $key === 'Software' ||
$key === 'Contact' ) {
1790 // we skip some fields which have composite values. They are not particularly interesting
1791 // and you can get them via the metadata / commonmetadata APIs anyway.
1794 if ( isset( $field['value'] ) ) {
1795 $field['value'] = $this->resolveMultivalueValue( $field['value'] );
1802 * Makes sure the given array is a valid API response fragment
1805 protected function sanitizeArrayForAPI( &$arr ) {
1806 if ( !is_array( $arr ) ) {
1811 foreach ( $arr as $key => &$value ) {
1812 $sanitizedKey = $this->sanitizeKeyForAPI( $key );
1813 if ( $sanitizedKey !== $key ) {
1814 if ( isset( $arr[$sanitizedKey] ) ) {
1815 // Make the sanitized keys hopefully unique.
1816 // To make it definitely unique would be too much effort, given that
1817 // sanitizing is only needed for misformatted metadata anyway, but
1818 // this at least covers the case when $arr is numeric.
1819 $sanitizedKey .= $counter;
1822 $arr[$sanitizedKey] = $arr[$key];
1823 unset( $arr[$key] );
1825 if ( is_array( $value ) ) {
1826 $this->sanitizeArrayForAPI( $value );
1830 // Handle API metadata keys (particularly "_type")
1831 $keys = array_filter( array_keys( $arr ), 'ApiResult::isMetadataKey' );
1833 ApiResult
::setPreserveKeysList( $arr, $keys );
1838 * Turns a string into a valid API identifier.
1839 * @param string $key
1843 protected function sanitizeKeyForAPI( $key ) {
1844 // drop all characters which are not valid in an XML tag name
1845 // a bunch of non-ASCII letters would be valid but probably won't
1846 // be used so we take the easy way
1847 $key = preg_replace( '/[^a-zA-z0-9_:.-]/', '', $key );
1848 // drop characters which are invalid at the first position
1849 $key = preg_replace( '/^[\d-.]+/', '', $key );
1855 // special case for an internal keyword
1856 if ( $key == '_element' ) {
1864 * Returns a list of languages (first is best) to use when formatting multilang fields,
1865 * based on user and site preferences.
1869 protected function getPriorityLanguages() {
1870 $priorityLanguages =
1871 Language
::getFallbacksIncludingSiteLanguage( $this->getLanguage()->getCode() );
1872 $priorityLanguages = array_merge(
1873 (array)$this->getLanguage()->getCode(),
1874 $priorityLanguages[0],
1875 $priorityLanguages[1]
1878 return $priorityLanguages;