2 // @codingStandardsIgnoreFile
3 // PHPCS can't handle the level of nesting in this file
5 * Formatting of image metadata values into human readable form.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
23 * @author Ævar Arnfjörð Bjarmason <avarab@gmail.com>
24 * @copyright Copyright © 2005, Ævar Arnfjörð Bjarmason, 2009 Brent Garber, 2010 Brian Wolff
25 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
26 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 specification
31 * Format Image metadata values into a human readable form.
33 * Note lots of these messages use the prefix 'exif' even though
34 * they may not be exif properties. For example 'exif-ImageDescription'
35 * can be the Exif ImageDescription, or it could be the iptc-iim caption
36 * property, or it could be the xmp dc:description property. This
37 * is because these messages should be independent of how the data is
38 * stored, sine the user doesn't care if the description is stored in xmp,
39 * exif, etc only that its a description. (Additionally many of these properties
40 * are merged together following the MWG standard, such that for example,
41 * exif properties override XMP properties that mean the same thing if
42 * there is a conflict).
44 * It should perhaps use a prefix like 'metadata' instead, but there
45 * is already a large number of messages using the 'exif' prefix.
48 * @since 1.23 the class extends ContextSource and various formerly-public
49 * internal methods are private
51 class FormatMetadata
extends ContextSource
{
53 * Only output a single language for multi-language fields
57 protected $singleLang = false;
60 * Trigger only outputting single language for multilanguage fields
65 public function setSingleLanguage( $val ) {
66 $this->singleLang
= $val;
70 * Numbers given by Exif user agents are often magical, that is they
71 * should be replaced by a detailed explanation depending on their
72 * value which most of the time are plain integers. This function
73 * formats Exif (and other metadata) values into human readable form.
75 * This is the usual entry point for this class.
77 * @param array $tags The Exif data to format ( as returned by
78 * Exif::getFilteredData() or BitmapMetadataHandler )
79 * @param bool|IContextSource $context Context to use (optional)
82 public static function getFormattedData( $tags, $context = false ) {
83 $obj = new FormatMetadata
;
85 $obj->setContext( $context );
88 return $obj->makeFormattedData( $tags );
92 * Numbers given by Exif user agents are often magical, that is they
93 * should be replaced by a detailed explanation depending on their
94 * value which most of the time are plain integers. This function
95 * formats Exif (and other metadata) values into human readable form.
97 * @param array $tags The Exif data to format ( as returned by
98 * Exif::getFilteredData() or BitmapMetadataHandler )
102 public function makeFormattedData( $tags ) {
103 $resolutionunit = !isset( $tags['ResolutionUnit'] ) ||
$tags['ResolutionUnit'] == 2 ?
2 : 3;
104 unset( $tags['ResolutionUnit'] );
106 foreach ( $tags as $tag => &$vals ) {
108 // This seems ugly to wrap non-array's in an array just to unwrap again,
109 // especially when most of the time it is not an array
110 if ( !is_array( $tags[$tag] ) ) {
111 $vals = array( $vals );
114 // _type is a special value to say what array type
115 if ( isset( $tags[$tag]['_type'] ) ) {
116 $type = $tags[$tag]['_type'];
117 unset( $vals['_type'] );
119 $type = 'ul'; // default unordered list.
122 // This is done differently as the tag is an array.
123 if ( $tag == 'GPSTimeStamp' && count( $vals ) === 3 ) {
124 // hour min sec array
126 $h = explode( '/', $vals[0] );
127 $m = explode( '/', $vals[1] );
128 $s = explode( '/', $vals[2] );
130 // this should already be validated
131 // when loaded from file, but it could
132 // come from a foreign repo, so be
143 $tags[$tag] = str_pad( intval( $h[0] / $h[1] ), 2, '0', STR_PAD_LEFT
)
144 . ':' . str_pad( intval( $m[0] / $m[1] ), 2, '0', STR_PAD_LEFT
)
145 . ':' . str_pad( intval( $s[0] / $s[1] ), 2, '0', STR_PAD_LEFT
);
148 $time = wfTimestamp( TS_MW
, '1971:01:01 ' . $tags[$tag] );
149 // the 1971:01:01 is just a placeholder, and not shown to user.
150 if ( $time && intval( $time ) > 0 ) {
151 $tags[$tag] = $this->getLanguage()->time( $time );
153 } catch ( TimestampException
$e ) {
154 // This shouldn't happen, but we've seen bad formats
155 // such as 4-digit seconds in the wild.
156 // leave $tags[$tag] as-is
161 // The contact info is a multi-valued field
162 // instead of the other props which are single
163 // valued (mostly) so handle as a special case.
164 if ( $tag === 'Contact' ) {
165 $vals = $this->collapseContactInfo( $vals );
169 foreach ( $vals as &$val ) {
185 $val = $this->exifMsg( $tag, $val );
188 /* If not recognized, display as is. */
193 case 'PhotometricInterpretation':
197 $val = $this->exifMsg( $tag, $val );
200 /* If not recognized, display as is. */
215 $val = $this->exifMsg( $tag, $val );
218 /* If not recognized, display as is. */
223 case 'PlanarConfiguration':
227 $val = $this->exifMsg( $tag, $val );
230 /* If not recognized, display as is. */
235 // TODO: YCbCrSubSampling
236 case 'YCbCrPositioning':
240 $val = $this->exifMsg( $tag, $val );
243 /* If not recognized, display as is. */
250 switch ( $resolutionunit ) {
252 $val = $this->exifMsg( 'XYResolution', 'i', $this->formatNum( $val ) );
255 $val = $this->exifMsg( 'XYResolution', 'c', $this->formatNum( $val ) );
258 /* If not recognized, display as is. */
263 // TODO: YCbCrCoefficients #p27 (see annex E)
265 case 'FlashpixVersion':
273 $val = $this->exifMsg( $tag, $val );
276 /* If not recognized, display as is. */
281 case 'ComponentsConfiguration':
290 $val = $this->exifMsg( $tag, $val );
293 /* If not recognized, display as is. */
299 case 'DateTimeOriginal':
300 case 'DateTimeDigitized':
301 case 'DateTimeReleased':
302 case 'DateTimeExpires':
305 case 'DateTimeMetadata':
306 if ( $val == '0000:00:00 00:00:00' ||
$val == ' : : : : ' ) {
307 $val = $this->msg( 'exif-unknowndate' )->text();
308 } elseif ( preg_match(
309 '/^(?:\d{4}):(?:\d\d):(?:\d\d) (?:\d\d):(?:\d\d):(?:\d\d)$/D',
313 $time = wfTimestamp( TS_MW
, $val );
314 if ( $time && intval( $time ) > 0 ) {
315 $val = $this->getLanguage()->timeanddate( $time );
317 } elseif ( preg_match( '/^(?:\d{4}):(?:\d\d):(?:\d\d) (?:\d\d):(?:\d\d)$/D', $val ) ) {
318 // No second field. Still format the same
319 // since timeanddate doesn't include seconds anyways,
320 // but second still available in api
321 $time = wfTimestamp( TS_MW
, $val . ':00' );
322 if ( $time && intval( $time ) > 0 ) {
323 $val = $this->getLanguage()->timeanddate( $time );
325 } elseif ( preg_match( '/^(?:\d{4}):(?:\d\d):(?:\d\d)$/D', $val ) ) {
326 // If only the date but not the time is filled in.
327 $time = wfTimestamp( TS_MW
, substr( $val, 0, 4 )
328 . substr( $val, 5, 2 )
329 . substr( $val, 8, 2 )
331 if ( $time && intval( $time ) > 0 ) {
332 $val = $this->getLanguage()->date( $time );
335 // else it will just output $val without formatting it.
338 case 'ExposureProgram':
349 $val = $this->exifMsg( $tag, $val );
352 /* If not recognized, display as is. */
357 case 'SubjectDistance':
358 $val = $this->exifMsg( $tag, '', $this->formatNum( $val ) );
372 $val = $this->exifMsg( $tag, $val );
375 /* If not recognized, display as is. */
403 $val = $this->exifMsg( $tag, $val );
406 /* If not recognized, display as is. */
412 $flashDecode = array(
413 'fired' => $val & bindec( '00000001' ),
414 'return' => ( $val & bindec( '00000110' ) ) >> 1,
415 'mode' => ( $val & bindec( '00011000' ) ) >> 3,
416 'function' => ( $val & bindec( '00100000' ) ) >> 5,
417 'redeye' => ( $val & bindec( '01000000' ) ) >> 6,
418 // 'reserved' => ($val & bindec( '10000000' )) >> 7,
420 $flashMsgs = array();
421 # We do not need to handle unknown values since all are used.
422 foreach ( $flashDecode as $subTag => $subValue ) {
423 # We do not need any message for zeroed values.
424 if ( $subTag != 'fired' && $subValue == 0 ) {
427 $fullTag = $tag . '-' . $subTag;
428 $flashMsgs[] = $this->exifMsg( $fullTag, $subValue );
430 $val = $this->getLanguage()->commaList( $flashMsgs );
433 case 'FocalPlaneResolutionUnit':
436 $val = $this->exifMsg( $tag, $val );
439 /* If not recognized, display as is. */
444 case 'SensingMethod':
453 $val = $this->exifMsg( $tag, $val );
456 /* If not recognized, display as is. */
464 $val = $this->exifMsg( $tag, $val );
467 /* If not recognized, display as is. */
475 $val = $this->exifMsg( $tag, $val );
478 /* If not recognized, display as is. */
483 case 'CustomRendered':
487 $val = $this->exifMsg( $tag, $val );
490 /* If not recognized, display as is. */
500 $val = $this->exifMsg( $tag, $val );
503 /* If not recognized, display as is. */
512 $val = $this->exifMsg( $tag, $val );
515 /* If not recognized, display as is. */
520 case 'SceneCaptureType':
526 $val = $this->exifMsg( $tag, $val );
529 /* If not recognized, display as is. */
541 $val = $this->exifMsg( $tag, $val );
544 /* If not recognized, display as is. */
554 $val = $this->exifMsg( $tag, $val );
557 /* If not recognized, display as is. */
567 $val = $this->exifMsg( $tag, $val );
570 /* If not recognized, display as is. */
580 $val = $this->exifMsg( $tag, $val );
583 /* If not recognized, display as is. */
588 case 'SubjectDistanceRange':
594 $val = $this->exifMsg( $tag, $val );
597 /* If not recognized, display as is. */
602 // The GPS...Ref values are kept for compatibility, probably won't be reached.
603 case 'GPSLatitudeRef':
604 case 'GPSDestLatitudeRef':
608 $val = $this->exifMsg( 'GPSLatitude', $val );
611 /* If not recognized, display as is. */
616 case 'GPSLongitudeRef':
617 case 'GPSDestLongitudeRef':
621 $val = $this->exifMsg( 'GPSLongitude', $val );
624 /* If not recognized, display as is. */
631 $val = $this->exifMsg( 'GPSAltitude', 'below-sealevel', $this->formatNum( -$val, 3 ) );
633 $val = $this->exifMsg( 'GPSAltitude', 'above-sealevel', $this->formatNum( $val, 3 ) );
641 $val = $this->exifMsg( $tag, $val );
644 /* If not recognized, display as is. */
649 case 'GPSMeasureMode':
653 $val = $this->exifMsg( $tag, $val );
656 /* If not recognized, display as is. */
662 case 'GPSImgDirectionRef':
663 case 'GPSDestBearingRef':
667 $val = $this->exifMsg( 'GPSDirection', $val );
670 /* If not recognized, display as is. */
676 case 'GPSDestLatitude':
677 $val = $this->formatCoords( $val, 'latitude' );
680 case 'GPSDestLongitude':
681 $val = $this->formatCoords( $val, 'longitude' );
689 $val = $this->exifMsg( 'GPSSpeed', $val );
692 /* If not recognized, display as is. */
697 case 'GPSDestDistanceRef':
702 $val = $this->exifMsg( 'GPSDestDistance', $val );
705 /* If not recognized, display as is. */
711 // See https://en.wikipedia.org/wiki/Dilution_of_precision_(GPS)
713 $val = $this->exifMsg( $tag, 'excellent', $this->formatNum( $val ) );
714 } elseif ( $val <= 5 ) {
715 $val = $this->exifMsg( $tag, 'good', $this->formatNum( $val ) );
716 } elseif ( $val <= 10 ) {
717 $val = $this->exifMsg( $tag, 'moderate', $this->formatNum( $val ) );
718 } elseif ( $val <= 20 ) {
719 $val = $this->exifMsg( $tag, 'fair', $this->formatNum( $val ) );
721 $val = $this->exifMsg( $tag, 'poor', $this->formatNum( $val ) );
725 // This is not in the Exif standard, just a special
726 // case for our purposes which enables wikis to wikify
727 // the make, model and software name to link to their articles.
730 $val = $this->exifMsg( $tag, '', $val );
734 if ( is_array( $val ) ) {
735 // if its a software, version array.
736 $val = $this->msg( 'exif-software-version-value', $val[0], $val[1] )->text();
738 $val = $this->exifMsg( $tag, '', $val );
743 // Show the pretty fraction as well as decimal version
744 $val = $this->msg( 'exif-exposuretime-format',
745 $this->formatFraction( $val ), $this->formatNum( $val ) )->text();
747 case 'ISOSpeedRatings':
748 // If its = 65535 that means its at the
749 // limit of the size of Exif::short and
751 if ( $val == '65535' ) {
752 $val = $this->exifMsg( $tag, 'overflow' );
754 $val = $this->formatNum( $val );
758 $val = $this->msg( 'exif-fnumber-format',
759 $this->formatNum( $val ) )->text();
763 case 'FocalLengthIn35mmFilm':
764 $val = $this->msg( 'exif-focallength-format',
765 $this->formatNum( $val ) )->text();
768 case 'MaxApertureValue':
769 if ( strpos( $val, '/' ) !== false ) {
770 // need to expand this earlier to calculate fNumber
771 list( $n, $d ) = explode( '/', $val );
772 if ( is_numeric( $n ) && is_numeric( $d ) ) {
776 if ( is_numeric( $val ) ) {
777 $fNumber = pow( 2, $val / 2 );
778 if ( $fNumber !== false ) {
779 $val = $this->msg( 'exif-maxaperturevalue-value',
780 $this->formatNum( $val ),
781 $this->formatNum( $fNumber, 2 )
788 switch ( strtolower( $val ) ) {
789 // See pg 29 of IPTC photo
790 // metadata standard.
808 $val = $this->exifMsg(
814 case 'SubjectNewsCode':
815 // Essentially like iimCategory.
816 // 8 (numeric) digit hierarchical
817 // classification. We decode the
818 // first 2 digits, which provide
820 $val = $this->convertNewsCode( $val );
823 // 1-8 with 1 being highest, 5 normal
824 // 0 is reserved, and 9 is 'user-defined'.
826 if ( $val == 0 ||
$val == 9 ) {
828 } elseif ( $val < 5 && $val > 1 ) {
830 } elseif ( $val == 5 ) {
832 } elseif ( $val <= 8 && $val > 5 ) {
836 if ( $urgency !== '' ) {
837 $val = $this->exifMsg( 'urgency',
843 // Things that have a unit of pixels.
844 case 'OriginalImageHeight':
845 case 'OriginalImageWidth':
846 case 'PixelXDimension':
847 case 'PixelYDimension':
850 $val = $this->formatNum( $val ) . ' ' . $this->msg( 'unit-pixel' )->text();
853 // Do not transform fields with pure text.
854 // For some languages the formatNum()
855 // conversion results to wrong output like
856 // foo,bar@example,com or foo٫bar@example٫com.
857 // Also some 'numeric' things like Scene codes
858 // are included here as we really don't want
860 case 'ImageDescription':
863 case 'RelatedSoundFile':
864 case 'ImageUniqueID':
865 case 'SpectralSensitivity':
866 case 'GPSSatellites':
870 case 'WorldRegionDest':
872 case 'CountryCodeDest':
873 case 'ProvinceOrStateDest':
875 case 'SublocationDest':
876 case 'WorldRegionCreated':
877 case 'CountryCreated':
878 case 'CountryCodeCreated':
879 case 'ProvinceOrStateCreated':
881 case 'SublocationCreated':
883 case 'SpecialInstructions':
888 case 'FixtureIdentifier':
890 case 'LocationDestCode':
892 case 'JPEGFileComment':
893 case 'iimSupplementalCategory':
894 case 'OriginalTransmissionRef':
896 case 'dc-contributor':
905 case 'CameraOwnerName':
908 case 'RightsCertificate':
909 case 'CopyrightOwner':
912 case 'OriginalDocumentID':
914 case 'MorePermissionsUrl':
915 case 'AttributionUrl':
916 case 'PreferredAttributionName':
917 case 'PNGFileComment':
919 case 'ContentWarning':
920 case 'GIFFileComment':
922 case 'IntellectualGenre':
924 case 'OrginisationInImage':
925 case 'PersonInImage':
927 $val = htmlspecialchars( $val );
935 $val = $this->exifMsg( $tag, $val );
938 $val = htmlspecialchars( $val );
946 $val = $this->exifMsg( $tag, $val );
951 if ( $val == '-1' ) {
952 $val = $this->exifMsg( $tag, 'rejected' );
954 $val = $this->formatNum( $val );
959 $lang = Language
::fetchLanguageName( strtolower( $val ), $this->getLanguage()->getCode() );
961 $val = htmlspecialchars( $lang );
963 $val = htmlspecialchars( $val );
968 $val = $this->formatNum( $val );
972 // End formatting values, start flattening arrays.
973 $vals = $this->flattenArrayReal( $vals, $type );
980 * Flatten an array, using the content language for any messages.
982 * @param array $vals Array of values
983 * @param string $type Type of array (either lang, ul, ol).
984 * lang = language assoc array with keys being the lang code
985 * ul = unordered list, ol = ordered list
986 * type can also come from the '_type' member of $vals.
987 * @param bool $noHtml If to avoid returning anything resembling HTML.
988 * (Ugly hack for backwards compatibility with old MediaWiki).
989 * @param bool|IContextSource $context
990 * @return string Single value (in wiki-syntax).
993 public static function flattenArrayContentLang( $vals, $type = 'ul',
994 $noHtml = false, $context = false
997 $obj = new FormatMetadata
;
999 $obj->setContext( $context );
1001 $context = new DerivativeContext( $obj->getContext() );
1002 $context->setLanguage( $wgContLang );
1003 $obj->setContext( $context );
1005 return $obj->flattenArrayReal( $vals, $type, $noHtml );
1009 * A function to collapse multivalued tags into a single value.
1010 * This turns an array of (for example) authors into a bulleted list.
1012 * This is public on the basis it might be useful outside of this class.
1014 * @param array $vals Array of values
1015 * @param string $type Type of array (either lang, ul, ol).
1016 * lang = language assoc array with keys being the lang code
1017 * ul = unordered list, ol = ordered list
1018 * type can also come from the '_type' member of $vals.
1019 * @param bool $noHtml If to avoid returning anything resembling HTML.
1020 * (Ugly hack for backwards compatibility with old mediawiki).
1021 * @return string Single value (in wiki-syntax).
1024 public function flattenArrayReal( $vals, $type = 'ul', $noHtml = false ) {
1025 if ( !is_array( $vals ) ) {
1026 return $vals; // do nothing if not an array;
1029 if ( isset( $vals['_type'] ) ) {
1030 $type = $vals['_type'];
1031 unset( $vals['_type'] );
1034 if ( !is_array( $vals ) ) {
1035 return $vals; // do nothing if not an array;
1036 } elseif ( count( $vals ) === 1 && $type !== 'lang' ) {
1038 } elseif ( count( $vals ) === 0 ) {
1039 wfDebug( __METHOD__
. " metadata array with 0 elements!\n" );
1041 return ""; // paranoia. This should never happen
1043 /* @todo FIXME: This should hide some of the list entries if there are
1044 * say more than four. Especially if a field is translated into 20
1045 * languages, we don't want to show them all by default
1049 // Display default, followed by ContLang,
1050 // followed by the rest in no particular
1053 // Todo: hide some items if really long list.
1057 $priorityLanguages = $this->getPriorityLanguages();
1058 $defaultItem = false;
1059 $defaultLang = false;
1061 // If default is set, save it for later,
1062 // as we don't know if it's equal to
1063 // one of the lang codes. (In xmp
1064 // you specify the language for a
1065 // default property by having both
1066 // a default prop, and one in the language
1067 // that are identical)
1068 if ( isset( $vals['x-default'] ) ) {
1069 $defaultItem = $vals['x-default'];
1070 unset( $vals['x-default'] );
1072 foreach ( $priorityLanguages as $pLang ) {
1073 if ( isset( $vals[$pLang] ) ) {
1075 if ( $vals[$pLang] === $defaultItem ) {
1076 $defaultItem = false;
1079 $content .= $this->langItem(
1080 $vals[$pLang], $pLang,
1081 $isDefault, $noHtml );
1083 unset( $vals[$pLang] );
1085 if ( $this->singleLang
) {
1086 return Html
::rawElement( 'span',
1087 array( 'lang' => $pLang ), $vals[$pLang] );
1093 foreach ( $vals as $lang => $item ) {
1094 if ( $item === $defaultItem ) {
1095 $defaultLang = $lang;
1098 $content .= $this->langItem( $item,
1099 $lang, false, $noHtml );
1100 if ( $this->singleLang
) {
1101 return Html
::rawElement( 'span',
1102 array( 'lang' => $lang ), $item );
1105 if ( $defaultItem !== false ) {
1106 $content = $this->langItem( $defaultItem,
1107 $defaultLang, true, $noHtml ) .
1109 if ( $this->singleLang
) {
1110 return $defaultItem;
1117 return '<ul class="metadata-langlist">' .
1122 return "\n#" . implode( "\n#", $vals );
1125 return "<ol><li>" . implode( "</li>\n<li>", $vals ) . '</li></ol>';
1129 return "\n*" . implode( "\n*", $vals );
1132 return "<ul><li>" . implode( "</li>\n<li>", $vals ) . '</li></ul>';
1137 /** Helper function for creating lists of translations.
1139 * @param string $value Value (this is not escaped)
1140 * @param string $lang Lang code of item or false
1141 * @param bool $default If it is default value.
1142 * @param bool $noHtml If to avoid html (for back-compat)
1143 * @throws MWException
1144 * @return string Language item (Note: despite how this looks, this is
1145 * treated as wikitext, not as HTML).
1147 private function langItem( $value, $lang, $default = false, $noHtml = false ) {
1148 if ( $lang === false && $default === false ) {
1149 throw new MWException( '$lang and $default cannot both '
1154 $wrappedValue = $value;
1156 $wrappedValue = '<span class="mw-metadata-lang-value">'
1157 . $value . '</span>';
1160 if ( $lang === false ) {
1161 $msg = $this->msg( 'metadata-langitem-default', $wrappedValue );
1163 return $msg->text() . "\n\n";
1166 return '<li class="mw-metadata-lang-default">'
1171 $lowLang = strtolower( $lang );
1172 $langName = Language
::fetchLanguageName( $lowLang );
1173 if ( $langName === '' ) {
1174 // try just the base language name. (aka en-US -> en ).
1175 list( $langPrefix ) = explode( '-', $lowLang, 2 );
1176 $langName = Language
::fetchLanguageName( $langPrefix );
1177 if ( $langName === '' ) {
1182 // else we have a language specified
1184 $msg = $this->msg( 'metadata-langitem', $wrappedValue, $langName, $lang );
1186 return '*' . $msg->text();
1189 $item = '<li class="mw-metadata-lang-code-'
1192 $item .= ' mw-metadata-lang-default';
1194 $item .= '" lang="' . $lang . '">';
1195 $item .= $msg->text();
1202 * Convenience function for getFormattedData()
1204 * @param string $tag The tag name to pass on
1205 * @param string $val The value of the tag
1206 * @param string $arg An argument to pass ($1)
1207 * @param string $arg2 A 2nd argument to pass ($2)
1208 * @return string The text content of "exif-$tag-$val" message in lower case
1210 private function exifMsg( $tag, $val, $arg = null, $arg2 = null ) {
1213 if ( $val === '' ) {
1217 return $this->msg( $wgContLang->lc( "exif-$tag-$val" ), $arg, $arg2 )->text();
1221 * Format a number, convert numbers from fractions into floating point
1222 * numbers, joins arrays of numbers with commas.
1224 * @param mixed $num The value to format
1225 * @param float|int|bool $round Digits to round to or false.
1226 * @return mixed A floating point number or whatever we were fed
1228 private function formatNum( $num, $round = false ) {
1230 if ( is_array( $num ) ) {
1232 foreach ( $num as $number ) {
1233 $out[] = $this->formatNum( $number );
1236 return $this->getLanguage()->commaList( $out );
1238 if ( preg_match( '/^(-?\d+)\/(\d+)$/', $num, $m ) ) {
1240 $newNum = $m[1] / $m[2];
1241 if ( $round !== false ) {
1242 $newNum = round( $newNum, $round );
1248 return $this->getLanguage()->formatNum( $newNum );
1250 if ( is_numeric( $num ) && $round !== false ) {
1251 $num = round( $num, $round );
1254 return $this->getLanguage()->formatNum( $num );
1259 * Format a rational number, reducing fractions
1261 * @param mixed $num The value to format
1262 * @return mixed A floating point number or whatever we were fed
1264 private function formatFraction( $num ) {
1266 if ( preg_match( '/^(-?\d+)\/(\d+)$/', $num, $m ) ) {
1267 $numerator = intval( $m[1] );
1268 $denominator = intval( $m[2] );
1269 $gcd = $this->gcd( abs( $numerator ), $denominator );
1271 // 0 shouldn't happen! ;)
1272 return $this->formatNum( $numerator / $gcd ) . '/' . $this->formatNum( $denominator / $gcd );
1276 return $this->formatNum( $num );
1280 * Calculate the greatest common divisor of two integers.
1282 * @param int $a Numerator
1283 * @param int $b Denominator
1286 private function gcd( $a, $b ) {
1288 // https://en.wikipedia.org/wiki/Euclidean_algorithm
1289 // Recursive form would be:
1293 return gcd( $b, $a % $b );
1296 $remainder = $a %
$b;
1298 // tail recursion...
1307 * Fetch the human readable version of a news code.
1308 * A news code is an 8 digit code. The first two
1309 * digits are a general classification, so we just
1312 * Note, leading 0's are significant, so this is
1313 * a string, not an int.
1315 * @param string $val The 8 digit news code.
1316 * @return string The human readable form
1318 private function convertNewsCode( $val ) {
1319 if ( !preg_match( '/^\d{8}$/D', $val ) ) {
1320 // Not a valid news code.
1324 switch ( substr( $val, 0, 2 ) ) {
1377 if ( $cat !== '' ) {
1378 $catMsg = $this->exifMsg( 'iimcategory', $cat );
1379 $val = $this->exifMsg( 'subjectnewscode', '', $val, $catMsg );
1386 * Format a coordinate value, convert numbers from floating point
1387 * into degree minute second representation.
1389 * @param int $coord Degrees, minutes and seconds
1390 * @param string $type Latitude or longitude (for if its a NWS or E)
1391 * @return mixed A floating point number or whatever we were fed
1393 private function formatCoords( $coord, $type ) {
1397 if ( $type === 'latitude' ) {
1399 } elseif ( $type === 'longitude' ) {
1404 if ( $type === 'latitude' ) {
1406 } elseif ( $type === 'longitude' ) {
1411 $deg = floor( $nCoord );
1412 $min = floor( ( $nCoord - $deg ) * 60.0 );
1413 $sec = round( ( ( $nCoord - $deg ) - $min / 60 ) * 3600, 2 );
1415 $deg = $this->formatNum( $deg );
1416 $min = $this->formatNum( $min );
1417 $sec = $this->formatNum( $sec );
1419 return $this->msg( 'exif-coordinate-format', $deg, $min, $sec, $ref, $coord )->text();
1423 * Format the contact info field into a single value.
1425 * This function might be called from
1426 * JpegHandler::convertMetadataVersion which is why it is
1429 * @param array $vals Array with fields of the ContactInfo
1430 * struct defined in the IPTC4XMP spec. Or potentially
1431 * an array with one element that is a free form text
1432 * value from the older iptc iim 1:118 prop.
1433 * @return string HTML-ish looking wikitext
1434 * @since 1.23 no longer static
1436 public function collapseContactInfo( $vals ) {
1437 if ( !( isset( $vals['CiAdrExtadr'] )
1438 ||
isset( $vals['CiAdrCity'] )
1439 ||
isset( $vals['CiAdrCtry'] )
1440 ||
isset( $vals['CiEmailWork'] )
1441 ||
isset( $vals['CiTelWork'] )
1442 ||
isset( $vals['CiAdrPcode'] )
1443 ||
isset( $vals['CiAdrRegion'] )
1444 ||
isset( $vals['CiUrlWork'] )
1446 // We don't have any sub-properties
1447 // This could happen if its using old
1448 // iptc that just had this as a free-form
1450 // Note: We run this through htmlspecialchars
1451 // partially to be consistent, and partially
1452 // because people often insert >, etc into
1453 // the metadata which should not be interpreted
1454 // but we still want to auto-link urls.
1455 foreach ( $vals as &$val ) {
1456 $val = htmlspecialchars( $val );
1459 return $this->flattenArrayReal( $vals );
1461 // We have a real ContactInfo field.
1462 // Its unclear if all these fields have to be
1463 // set, so assume they do not.
1464 $url = $tel = $street = $city = $country = '';
1465 $email = $postal = $region = '';
1467 // Also note, some of the class names this uses
1468 // are similar to those used by hCard. This is
1469 // mostly because they're sensible names. This
1470 // does not (and does not attempt to) output
1471 // stuff in the hCard microformat. However it
1472 // might output in the adr microformat.
1474 if ( isset( $vals['CiAdrExtadr'] ) ) {
1475 // Todo: This can potentially be multi-line.
1476 // Need to check how that works in XMP.
1477 $street = '<span class="extended-address">'
1479 $vals['CiAdrExtadr'] )
1482 if ( isset( $vals['CiAdrCity'] ) ) {
1483 $city = '<span class="locality">'
1484 . htmlspecialchars( $vals['CiAdrCity'] )
1487 if ( isset( $vals['CiAdrCtry'] ) ) {
1488 $country = '<span class="country-name">'
1489 . htmlspecialchars( $vals['CiAdrCtry'] )
1492 if ( isset( $vals['CiEmailWork'] ) ) {
1494 // Have to split multiple emails at commas/new lines.
1495 $splitEmails = explode( "\n", $vals['CiEmailWork'] );
1496 foreach ( $splitEmails as $e1 ) {
1497 // Also split on comma
1498 foreach ( explode( ',', $e1 ) as $e2 ) {
1499 $finalEmail = trim( $e2 );
1500 if ( $finalEmail == ',' ||
$finalEmail == '' ) {
1503 if ( strpos( $finalEmail, '<' ) !== false ) {
1504 // Don't do fancy formatting to
1505 // "My name" <foo@bar.com> style stuff
1506 $emails[] = $finalEmail;
1508 $emails[] = '[mailto:'
1510 . ' <span class="email">'
1516 $email = implode( ', ', $emails );
1518 if ( isset( $vals['CiTelWork'] ) ) {
1519 $tel = '<span class="tel">'
1520 . htmlspecialchars( $vals['CiTelWork'] )
1523 if ( isset( $vals['CiAdrPcode'] ) ) {
1524 $postal = '<span class="postal-code">'
1526 $vals['CiAdrPcode'] )
1529 if ( isset( $vals['CiAdrRegion'] ) ) {
1530 // Note this is province/state.
1531 $region = '<span class="region">'
1533 $vals['CiAdrRegion'] )
1536 if ( isset( $vals['CiUrlWork'] ) ) {
1537 $url = '<span class="url">'
1538 . htmlspecialchars( $vals['CiUrlWork'] )
1542 return $this->msg( 'exif-contact-value', $email, $url,
1543 $street, $city, $region, $postal, $country,
1549 * Get a list of fields that are visible by default.
1554 public static function getVisibleFields() {
1556 $lines = explode( "\n", wfMessage( 'metadata-fields' )->inContentLanguage()->text() );
1557 foreach ( $lines as $line ) {
1559 if ( preg_match( '/^\\*\s*(.*?)\s*$/', $line, $matches ) ) {
1560 $fields[] = $matches[1];
1563 $fields = array_map( 'strtolower', $fields );
1569 * Get an array of extended metadata. (See the imageinfo API for format.)
1571 * @param File $file File to use
1572 * @return array [<property name> => ['value' => <value>]], or [] on error
1575 public function fetchExtendedMetadata( File
$file ) {
1578 // If revision deleted, exit immediately
1579 if ( $file->isDeleted( File
::DELETED_FILE
) ) {
1583 $cacheKey = wfMemcKey(
1584 'getExtendedMetadata',
1585 $this->getLanguage()->getCode(),
1586 (int)$this->singleLang
,
1590 $cachedValue = $wgMemc->get( $cacheKey );
1593 && Hooks
::run( 'ValidateExtendedMetadataCache', array( $cachedValue['timestamp'], $file ) )
1595 $extendedMetadata = $cachedValue['data'];
1597 $maxCacheTime = ( $file instanceof ForeignAPIFile
) ?
60 * 60 * 12 : 60 * 60 * 24 * 30;
1598 $fileMetadata = $this->getExtendedMetadataFromFile( $file );
1599 $extendedMetadata = $this->getExtendedMetadataFromHook( $file, $fileMetadata, $maxCacheTime );
1600 if ( $this->singleLang
) {
1601 $this->resolveMultilangMetadata( $extendedMetadata );
1603 $this->discardMultipleValues( $extendedMetadata );
1604 // Make sure the metadata won't break the API when an XML format is used.
1605 // This is an API-specific function so it would be cleaner to call it from
1606 // outside fetchExtendedMetadata, but this way we don't need to redo the
1607 // computation on a cache hit.
1608 $this->sanitizeArrayForAPI( $extendedMetadata );
1609 $valueToCache = array( 'data' => $extendedMetadata, 'timestamp' => wfTimestampNow() );
1610 $wgMemc->set( $cacheKey, $valueToCache, $maxCacheTime );
1613 return $extendedMetadata;
1617 * Get file-based metadata in standardized format.
1619 * Note that for a remote file, this might return metadata supplied by extensions.
1621 * @param File $file File to use
1622 * @return array [<property name> => ['value' => <value>]], or [] on error
1625 protected function getExtendedMetadataFromFile( File
$file ) {
1626 // If this is a remote file accessed via an API request, we already
1627 // have remote metadata so we just ignore any local one
1628 if ( $file instanceof ForeignAPIFile
) {
1629 // In case of error we pretend no metadata - this will get cached.
1630 // Might or might not be a good idea.
1631 return $file->getExtendedMetadata() ?
: array();
1634 $uploadDate = wfTimestamp( TS_ISO_8601
, $file->getTimestamp() );
1636 $fileMetadata = array(
1637 // This is modification time, which is close to "upload" time.
1638 'DateTime' => array(
1639 'value' => $uploadDate,
1640 'source' => 'mediawiki-metadata',
1644 $title = $file->getTitle();
1646 $text = $title->getText();
1647 $pos = strrpos( $text, '.' );
1650 $name = substr( $text, 0, $pos );
1655 $fileMetadata['ObjectName'] = array(
1657 'source' => 'mediawiki-metadata',
1661 return $fileMetadata;
1665 * Get additional metadata from hooks in standardized format.
1667 * @param File $file File to use
1668 * @param array $extendedMetadata
1669 * @param int $maxCacheTime Hook handlers might use this parameter to override cache time
1671 * @return array [<property name> => ['value' => <value>]], or [] on error
1674 protected function getExtendedMetadataFromHook( File
$file, array $extendedMetadata,
1678 Hooks
::run( 'GetExtendedMetadata', array(
1681 $this->getContext(),
1686 $visible = array_flip( self
::getVisibleFields() );
1687 foreach ( $extendedMetadata as $key => $value ) {
1688 if ( !isset( $visible[strtolower( $key )] ) ) {
1689 $extendedMetadata[$key]['hidden'] = '';
1693 return $extendedMetadata;
1697 * Turns an XMP-style multilang array into a single value.
1698 * If the value is not a multilang array, it is returned unchanged.
1699 * See mediawiki.org/wiki/Manual:File_metadata_handling#Multi-language_array_format
1700 * @param mixed $value
1701 * @return mixed Value in best language, null if there were no languages at all
1704 protected function resolveMultilangValue( $value ) {
1707 ||
!isset( $value['_type'] )
1708 ||
$value['_type'] != 'lang'
1710 return $value; // do nothing if not a multilang array
1713 // choose the language best matching user or site settings
1714 $priorityLanguages = $this->getPriorityLanguages();
1715 foreach ( $priorityLanguages as $lang ) {
1716 if ( isset( $value[$lang] ) ) {
1717 return $value[$lang];
1721 // otherwise go with the default language, if set
1722 if ( isset( $value['x-default'] ) ) {
1723 return $value['x-default'];
1726 // otherwise just return any one language
1727 unset( $value['_type'] );
1728 if ( !empty( $value ) ) {
1729 return reset( $value );
1732 // this should not happen; signal error
1737 * Turns an XMP-style multivalue array into a single value by dropping all but the first
1738 * value. If the value is not a multivalue array (or a multivalue array inside a multilang
1739 * array), it is returned unchanged.
1740 * See mediawiki.org/wiki/Manual:File_metadata_handling#Multi-language_array_format
1741 * @param mixed $value
1742 * @return mixed The value, or the first value if there were multiple ones
1745 protected function resolveMultivalueValue( $value ) {
1746 if ( !is_array( $value ) ) {
1748 } elseif ( isset( $value['_type'] ) && $value['_type'] === 'lang' ) {
1749 // if this is a multilang array, process fields separately
1750 $newValue = array();
1751 foreach ( $value as $k => $v ) {
1752 $newValue[$k] = $this->resolveMultivalueValue( $v );
1755 } else { // _type is 'ul' or 'ol' or missing in which case it defaults to 'ul'
1756 list( $k, $v ) = each( $value );
1757 if ( $k === '_type' ) {
1758 $v = current( $value );
1765 * Takes an array returned by the getExtendedMetadata* functions,
1766 * and resolves multi-language values in it.
1767 * @param array $metadata
1770 protected function resolveMultilangMetadata( &$metadata ) {
1771 if ( !is_array( $metadata ) ) {
1774 foreach ( $metadata as &$field ) {
1775 if ( isset( $field['value'] ) ) {
1776 $field['value'] = $this->resolveMultilangValue( $field['value'] );
1782 * Takes an array returned by the getExtendedMetadata* functions,
1783 * and turns all fields into single-valued ones by dropping extra values.
1784 * @param array $metadata
1787 protected function discardMultipleValues( &$metadata ) {
1788 if ( !is_array( $metadata ) ) {
1791 foreach ( $metadata as $key => &$field ) {
1792 if ( $key === 'Software' ||
$key === 'Contact' ) {
1793 // we skip some fields which have composite values. They are not particularly interesting
1794 // and you can get them via the metadata / commonmetadata APIs anyway.
1797 if ( isset( $field['value'] ) ) {
1798 $field['value'] = $this->resolveMultivalueValue( $field['value'] );
1805 * Makes sure the given array is a valid API response fragment
1808 protected function sanitizeArrayForAPI( &$arr ) {
1809 if ( !is_array( $arr ) ) {
1814 foreach ( $arr as $key => &$value ) {
1815 $sanitizedKey = $this->sanitizeKeyForAPI( $key );
1816 if ( $sanitizedKey !== $key ) {
1817 if ( isset( $arr[$sanitizedKey] ) ) {
1818 // Make the sanitized keys hopefully unique.
1819 // To make it definitely unique would be too much effort, given that
1820 // sanitizing is only needed for misformatted metadata anyway, but
1821 // this at least covers the case when $arr is numeric.
1822 $sanitizedKey .= $counter;
1825 $arr[$sanitizedKey] = $arr[$key];
1826 unset( $arr[$key] );
1828 if ( is_array( $value ) ) {
1829 $this->sanitizeArrayForAPI( $value );
1833 // Handle API metadata keys (particularly "_type")
1834 $keys = array_filter( array_keys( $arr ), 'ApiResult::isMetadataKey' );
1836 ApiResult
::setPreserveKeysList( $arr, $keys );
1841 * Turns a string into a valid API identifier.
1842 * @param string $key
1846 protected function sanitizeKeyForAPI( $key ) {
1847 // drop all characters which are not valid in an XML tag name
1848 // a bunch of non-ASCII letters would be valid but probably won't
1849 // be used so we take the easy way
1850 $key = preg_replace( '/[^a-zA-z0-9_:.-]/', '', $key );
1851 // drop characters which are invalid at the first position
1852 $key = preg_replace( '/^[\d-.]+/', '', $key );
1858 // special case for an internal keyword
1859 if ( $key == '_element' ) {
1867 * Returns a list of languages (first is best) to use when formatting multilang fields,
1868 * based on user and site preferences.
1872 protected function getPriorityLanguages() {
1873 $priorityLanguages =
1874 Language
::getFallbacksIncludingSiteLanguage( $this->getLanguage()->getCode() );
1875 $priorityLanguages = array_merge(
1876 (array)$this->getLanguage()->getCode(),
1877 $priorityLanguages[0],
1878 $priorityLanguages[1]
1881 return $priorityLanguages;