f79284f0c7eaa9265734f4f5621650c8523556c9
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 internal methods are private
48 class FormatMetadata
extends ContextSource
{
50 * Only output a single language for multi-language fields
54 protected $singleLang = false;
57 * Trigger only outputting single language for multilanguage fields
62 public function setSingleLanguage( $val ) {
63 $this->singleLang
= $val;
67 * Numbers given by Exif user agents are often magical, that is they
68 * should be replaced by a detailed explanation depending on their
69 * value which most of the time are plain integers. This function
70 * formats Exif (and other metadata) values into human readable form.
72 * This is the usual entry point for this class.
74 * @param array $tags the Exif data to format ( as returned by
75 * Exif::getFilteredData() or BitmapMetadataHandler )
76 * @param IContextSource $context Context to use (optional)
79 public static function getFormattedData( $tags, $context = false ) {
80 $obj = new FormatMetadata
;
82 $obj->setContext( $context );
85 return $obj->makeFormattedData( $tags );
89 * Numbers given by Exif user agents are often magical, that is they
90 * should be replaced by a detailed explanation depending on their
91 * value which most of the time are plain integers. This function
92 * formats Exif (and other metadata) values into human readable form.
94 * @param array $tags the Exif data to format ( as returned by
95 * Exif::getFilteredData() or BitmapMetadataHandler )
99 public function makeFormattedData( $tags ) {
100 $resolutionunit = !isset( $tags['ResolutionUnit'] ) ||
$tags['ResolutionUnit'] == 2 ?
2 : 3;
101 unset( $tags['ResolutionUnit'] );
103 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] ) ) {
108 $vals = array( $vals );
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 ) {
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 ) {
182 $val = $this->exifMsg( $tag, $val );
185 /* If not recognized, display as is. */
190 case 'PhotometricInterpretation':
194 $val = $this->exifMsg( $tag, $val );
197 /* If not recognized, display as is. */
212 $val = $this->exifMsg( $tag, $val );
215 /* If not recognized, display as is. */
220 case 'PlanarConfiguration':
224 $val = $this->exifMsg( $tag, $val );
227 /* If not recognized, display as is. */
232 // TODO: YCbCrSubSampling
233 case 'YCbCrPositioning':
237 $val = $this->exifMsg( $tag, $val );
240 /* If not recognized, display as is. */
247 switch ( $resolutionunit ) {
249 $val = $this->exifMsg( 'XYResolution', 'i', $this->formatNum( $val ) );
252 $val = $this->exifMsg( 'XYResolution', 'c', $this->formatNum( $val ) );
255 /* If not recognized, display as is. */
260 // TODO: YCbCrCoefficients #p27 (see annex E)
262 case 'FlashpixVersion':
270 $val = $this->exifMsg( $tag, $val );
273 /* If not recognized, display as is. */
278 case 'ComponentsConfiguration':
287 $val = $this->exifMsg( $tag, $val );
290 /* If not recognized, display as is. */
296 case 'DateTimeOriginal':
297 case 'DateTimeDigitized':
298 case 'DateTimeReleased':
299 case 'DateTimeExpires':
302 case 'DateTimeMetadata':
303 if ( $val == '0000:00:00 00:00:00' ||
$val == ' : : : : ' ) {
304 $val = $this->msg( 'exif-unknowndate' )->text();
305 } elseif ( preg_match( '/^(?:\d{4}):(?:\d\d):(?:\d\d) (?:\d\d):(?:\d\d):(?:\d\d)$/D', $val ) ) {
307 $time = wfTimestamp( TS_MW
, $val );
308 if ( $time && intval( $time ) > 0 ) {
309 $val = $this->getLanguage()->timeanddate( $time );
311 } elseif ( preg_match( '/^(?:\d{4}):(?:\d\d):(?:\d\d) (?:\d\d):(?:\d\d)$/D', $val ) ) {
312 // No second field. Still format the same
313 // since timeanddate doesn't include seconds anyways,
314 // but second still available in api
315 $time = wfTimestamp( TS_MW
, $val . ':00' );
316 if ( $time && intval( $time ) > 0 ) {
317 $val = $this->getLanguage()->timeanddate( $time );
319 } elseif ( preg_match( '/^(?:\d{4}):(?:\d\d):(?:\d\d)$/D', $val ) ) {
320 // If only the date but not the time is filled in.
321 $time = wfTimestamp( TS_MW
, substr( $val, 0, 4 )
322 . substr( $val, 5, 2 )
323 . substr( $val, 8, 2 )
325 if ( $time && intval( $time ) > 0 ) {
326 $val = $this->getLanguage()->date( $time );
329 // else it will just output $val without formatting it.
332 case 'ExposureProgram':
343 $val = $this->exifMsg( $tag, $val );
346 /* If not recognized, display as is. */
351 case 'SubjectDistance':
352 $val = $this->exifMsg( $tag, '', $this->formatNum( $val ) );
366 $val = $this->exifMsg( $tag, $val );
369 /* If not recognized, display as is. */
397 $val = $this->exifMsg( $tag, $val );
400 /* If not recognized, display as is. */
406 $flashDecode = array(
407 'fired' => $val & bindec( '00000001' ),
408 'return' => ( $val & bindec( '00000110' ) ) >> 1,
409 'mode' => ( $val & bindec( '00011000' ) ) >> 3,
410 'function' => ( $val & bindec( '00100000' ) ) >> 5,
411 'redeye' => ( $val & bindec( '01000000' ) ) >> 6,
412 // 'reserved' => ($val & bindec( '10000000' )) >> 7,
414 $flashMsgs = array();
415 # We do not need to handle unknown values since all are used.
416 foreach ( $flashDecode as $subTag => $subValue ) {
417 # We do not need any message for zeroed values.
418 if ( $subTag != 'fired' && $subValue == 0 ) {
421 $fullTag = $tag . '-' . $subTag;
422 $flashMsgs[] = $this->exifMsg( $fullTag, $subValue );
424 $val = $this->getLanguage()->commaList( $flashMsgs );
427 case 'FocalPlaneResolutionUnit':
430 $val = $this->exifMsg( $tag, $val );
433 /* If not recognized, display as is. */
438 case 'SensingMethod':
447 $val = $this->exifMsg( $tag, $val );
450 /* If not recognized, display as is. */
458 $val = $this->exifMsg( $tag, $val );
461 /* If not recognized, display as is. */
469 $val = $this->exifMsg( $tag, $val );
472 /* If not recognized, display as is. */
477 case 'CustomRendered':
481 $val = $this->exifMsg( $tag, $val );
484 /* If not recognized, display as is. */
494 $val = $this->exifMsg( $tag, $val );
497 /* If not recognized, display as is. */
506 $val = $this->exifMsg( $tag, $val );
509 /* If not recognized, display as is. */
514 case 'SceneCaptureType':
520 $val = $this->exifMsg( $tag, $val );
523 /* If not recognized, display as is. */
535 $val = $this->exifMsg( $tag, $val );
538 /* If not recognized, display as is. */
548 $val = $this->exifMsg( $tag, $val );
551 /* If not recognized, display as is. */
561 $val = $this->exifMsg( $tag, $val );
564 /* If not recognized, display as is. */
574 $val = $this->exifMsg( $tag, $val );
577 /* If not recognized, display as is. */
582 case 'SubjectDistanceRange':
588 $val = $this->exifMsg( $tag, $val );
591 /* If not recognized, display as is. */
596 //The GPS...Ref values are kept for compatibility, probably won't be reached.
597 case 'GPSLatitudeRef':
598 case 'GPSDestLatitudeRef':
602 $val = $this->exifMsg( 'GPSLatitude', $val );
605 /* If not recognized, display as is. */
610 case 'GPSLongitudeRef':
611 case 'GPSDestLongitudeRef':
615 $val = $this->exifMsg( 'GPSLongitude', $val );
618 /* If not recognized, display as is. */
625 $val = $this->exifMsg( 'GPSAltitude', 'below-sealevel', $this->formatNum( -$val, 3 ) );
627 $val = $this->exifMsg( 'GPSAltitude', 'above-sealevel', $this->formatNum( $val, 3 ) );
635 $val = $this->exifMsg( $tag, $val );
638 /* If not recognized, display as is. */
643 case 'GPSMeasureMode':
647 $val = $this->exifMsg( $tag, $val );
650 /* If not recognized, display as is. */
656 case 'GPSImgDirectionRef':
657 case 'GPSDestBearingRef':
661 $val = $this->exifMsg( 'GPSDirection', $val );
664 /* If not recognized, display as is. */
670 case 'GPSDestLatitude':
671 $val = $this->formatCoords( $val, 'latitude' );
674 case 'GPSDestLongitude':
675 $val = $this->formatCoords( $val, 'longitude' );
683 $val = $this->exifMsg( 'GPSSpeed', $val );
686 /* If not recognized, display as is. */
691 case 'GPSDestDistanceRef':
696 $val = $this->exifMsg( 'GPSDestDistance', $val );
699 /* If not recognized, display as is. */
705 // See http://en.wikipedia.org/wiki/Dilution_of_precision_(GPS)
707 $val = $this->exifMsg( $tag, 'excellent', $this->formatNum( $val ) );
708 } elseif ( $val <= 5 ) {
709 $val = $this->exifMsg( $tag, 'good', $this->formatNum( $val ) );
710 } elseif ( $val <= 10 ) {
711 $val = $this->exifMsg( $tag, 'moderate', $this->formatNum( $val ) );
712 } elseif ( $val <= 20 ) {
713 $val = $this->exifMsg( $tag, 'fair', $this->formatNum( $val ) );
715 $val = $this->exifMsg( $tag, 'poor', $this->formatNum( $val ) );
719 // This is not in the Exif standard, just a special
720 // case for our purposes which enables wikis to wikify
721 // the make, model and software name to link to their articles.
724 $val = $this->exifMsg( $tag, '', $val );
728 if ( is_array( $val ) ) {
729 //if its a software, version array.
730 $val = $this->msg( 'exif-software-version-value', $val[0], $val[1] )->text();
732 $val = $this->exifMsg( $tag, '', $val );
737 // Show the pretty fraction as well as decimal version
738 $val = $this->msg( 'exif-exposuretime-format',
739 $this->formatFraction( $val ), $this->formatNum( $val ) )->text();
741 case 'ISOSpeedRatings':
742 // If its = 65535 that means its at the
743 // limit of the size of Exif::short and
745 if ( $val == '65535' ) {
746 $val = $this->exifMsg( $tag, 'overflow' );
748 $val = $this->formatNum( $val );
752 $val = $this->msg( 'exif-fnumber-format',
753 $this->formatNum( $val ) )->text();
757 case 'FocalLengthIn35mmFilm':
758 $val = $this->msg( 'exif-focallength-format',
759 $this->formatNum( $val ) )->text();
762 case 'MaxApertureValue':
763 if ( strpos( $val, '/' ) !== false ) {
764 // need to expand this earlier to calculate fNumber
765 list( $n, $d ) = explode( '/', $val );
766 if ( is_numeric( $n ) && is_numeric( $d ) ) {
770 if ( is_numeric( $val ) ) {
771 $fNumber = pow( 2, $val / 2 );
772 if ( $fNumber !== false ) {
773 $val = $this->msg( 'exif-maxaperturevalue-value',
774 $this->formatNum( $val ),
775 $this->formatNum( $fNumber, 2 )
782 switch ( strtolower( $val ) ) {
783 // See pg 29 of IPTC photo
784 // metadata standard.
802 $val = $this->exifMsg(
808 case 'SubjectNewsCode':
809 // Essentially like iimCategory.
810 // 8 (numeric) digit hierarchical
811 // classification. We decode the
812 // first 2 digits, which provide
814 $val = $this->convertNewsCode( $val );
817 // 1-8 with 1 being highest, 5 normal
818 // 0 is reserved, and 9 is 'user-defined'.
820 if ( $val == 0 ||
$val == 9 ) {
822 } elseif ( $val < 5 && $val > 1 ) {
824 } elseif ( $val == 5 ) {
826 } elseif ( $val <= 8 && $val > 5 ) {
830 if ( $urgency !== '' ) {
831 $val = $this->exifMsg( 'urgency',
837 // Things that have a unit of pixels.
838 case 'OriginalImageHeight':
839 case 'OriginalImageWidth':
840 case 'PixelXDimension':
841 case 'PixelYDimension':
844 $val = $this->formatNum( $val ) . ' ' . $this->msg( 'unit-pixel' )->text();
847 // Do not transform fields with pure text.
848 // For some languages the formatNum()
849 // conversion results to wrong output like
850 // foo,bar@example,com or foo٫bar@example٫com.
851 // Also some 'numeric' things like Scene codes
852 // are included here as we really don't want
854 case 'ImageDescription':
857 case 'RelatedSoundFile':
858 case 'ImageUniqueID':
859 case 'SpectralSensitivity':
860 case 'GPSSatellites':
864 case 'WorldRegionDest':
866 case 'CountryCodeDest':
867 case 'ProvinceOrStateDest':
869 case 'SublocationDest':
870 case 'WorldRegionCreated':
871 case 'CountryCreated':
872 case 'CountryCodeCreated':
873 case 'ProvinceOrStateCreated':
875 case 'SublocationCreated':
877 case 'SpecialInstructions':
882 case 'FixtureIdentifier':
884 case 'LocationDestCode':
886 case 'JPEGFileComment':
887 case 'iimSupplementalCategory':
888 case 'OriginalTransmissionRef':
890 case 'dc-contributor':
899 case 'CameraOwnerName':
902 case 'RightsCertificate':
903 case 'CopyrightOwner':
906 case 'OriginalDocumentID':
908 case 'MorePermissionsUrl':
909 case 'AttributionUrl':
910 case 'PreferredAttributionName':
911 case 'PNGFileComment':
913 case 'ContentWarning':
914 case 'GIFFileComment':
916 case 'IntellectualGenre':
918 case 'OrginisationInImage':
919 case 'PersonInImage':
921 $val = htmlspecialchars( $val );
929 $val = $this->exifMsg( $tag, $val );
932 $val = htmlspecialchars( $val );
940 $val = $this->exifMsg( $tag, $val );
945 if ( $val == '-1' ) {
946 $val = $this->exifMsg( $tag, 'rejected' );
948 $val = $this->formatNum( $val );
953 $lang = Language
::fetchLanguageName( strtolower( $val ), $this->getLanguage()->getCode() );
955 $val = htmlspecialchars( $lang );
957 $val = htmlspecialchars( $val );
962 $val = $this->formatNum( $val );
966 // End formatting values, start flattening arrays.
967 $vals = $this->flattenArrayReal( $vals, $type );
974 * Flatten an array, using the content language for any messages.
976 * @param array $vals array of values
977 * @param string $type Type of array (either lang, ul, ol).
978 * lang = language assoc array with keys being the lang code
979 * ul = unordered list, ol = ordered list
980 * type can also come from the '_type' member of $vals.
981 * @param $noHtml Boolean If to avoid returning anything resembling
982 * html. (Ugly hack for backwards compatibility with old mediawiki).
983 * @param IContextSource $context
984 * @return String single value (in wiki-syntax).
987 public static function flattenArrayContentLang( $vals, $type = 'ul', $noHtml = false, $context = false ) {
989 $obj = new FormatMetadata
;
991 $obj->setContext( $context );
993 $context = new DerivativeContext( $obj->getContext() );
994 $context->setLanguage( $wgContLang );
995 $obj->setContext( $context );
997 return $obj->flattenArrayReal( $vals, $type, $noHtml );
1001 * Flatten an array, using the user language for any messages.
1003 * @param array $vals array of values
1004 * @param string $type Type of array (either lang, ul, ol).
1005 * lang = language assoc array with keys being the lang code
1006 * ul = unordered list, ol = ordered list
1007 * type can also come from the '_type' member of $vals.
1008 * @param $noHtml Boolean If to avoid returning anything resembling
1009 * html. (Ugly hack for backwards compatibility with old mediawiki).
1010 * @param IContextSource $context
1011 * @return String single value (in wiki-syntax).
1013 public static function flattenArray( $vals, $type = 'ul', $noHtml = false, $context = false ) {
1014 $obj = new FormatMetadata
;
1016 $obj->setContext( $context );
1019 return $obj->flattenArrayReal( $vals, $type, $noHtml );
1023 * A function to collapse multivalued tags into a single value.
1024 * This turns an array of (for example) authors into a bulleted list.
1026 * This is public on the basis it might be useful outside of this class.
1028 * @param array $vals array of values
1029 * @param string $type Type of array (either lang, ul, ol).
1030 * lang = language assoc array with keys being the lang code
1031 * ul = unordered list, ol = ordered list
1032 * type can also come from the '_type' member of $vals.
1033 * @param $noHtml Boolean If to avoid returning anything resembling
1034 * html. (Ugly hack for backwards compatibility with old mediawiki).
1035 * @return String single value (in wiki-syntax).
1038 public function flattenArrayReal( $vals, $type = 'ul', $noHtml = false ) {
1039 if ( !is_array( $vals ) ) {
1040 return $vals; // do nothing if not an array;
1043 if ( isset( $vals['_type'] ) ) {
1044 $type = $vals['_type'];
1045 unset( $vals['_type'] );
1048 if ( !is_array( $vals ) ) {
1049 return $vals; // do nothing if not an array;
1050 } elseif ( count( $vals ) === 1 && $type !== 'lang' ) {
1052 } elseif ( count( $vals ) === 0 ) {
1053 wfDebug( __METHOD__
. " metadata array with 0 elements!\n" );
1055 return ""; // paranoia. This should never happen
1057 /* @todo FIXME: This should hide some of the list entries if there are
1058 * say more than four. Especially if a field is translated into 20
1059 * languages, we don't want to show them all by default
1063 // Display default, followed by ContLang,
1064 // followed by the rest in no particular
1067 // Todo: hide some items if really long list.
1071 $priorityLanguages = $this->getPriorityLanguages();
1072 $defaultItem = false;
1073 $defaultLang = false;
1075 // If default is set, save it for later,
1076 // as we don't know if it's equal to
1077 // one of the lang codes. (In xmp
1078 // you specify the language for a
1079 // default property by having both
1080 // a default prop, and one in the language
1081 // that are identical)
1082 if ( isset( $vals['x-default'] ) ) {
1083 $defaultItem = $vals['x-default'];
1084 unset( $vals['x-default'] );
1086 foreach ( $priorityLanguages as $pLang ) {
1087 if ( isset( $vals[$pLang] ) ) {
1089 if ( $vals[$pLang] === $defaultItem ) {
1090 $defaultItem = false;
1093 $content .= $this->langItem(
1094 $vals[$pLang], $pLang,
1095 $isDefault, $noHtml );
1097 unset( $vals[$pLang] );
1099 if ( $this->singleLang
) {
1100 return Html
::rawElement( 'span',
1101 array( 'lang' => $pLang ), $vals[$pLang] );
1107 foreach ( $vals as $lang => $item ) {
1108 if ( $item === $defaultItem ) {
1109 $defaultLang = $lang;
1112 $content .= $this->langItem( $item,
1113 $lang, false, $noHtml );
1114 if ( $this->singleLang
) {
1115 return Html
::rawElement( 'span',
1116 array( 'lang' => $lang ), $item );
1119 if ( $defaultItem !== false ) {
1120 $content = $this->langItem( $defaultItem,
1121 $defaultLang, true, $noHtml ) .
1123 if ( $this->singleLang
) {
1124 return $defaultItem;
1131 return '<ul class="metadata-langlist">' .
1136 return "\n#" . implode( "\n#", $vals );
1139 return "<ol><li>" . implode( "</li>\n<li>", $vals ) . '</li></ol>';
1143 return "\n*" . implode( "\n*", $vals );
1146 return "<ul><li>" . implode( "</li>\n<li>", $vals ) . '</li></ul>';
1151 /** Helper function for creating lists of translations.
1153 * @param string $value value (this is not escaped)
1154 * @param string $lang lang code of item or false
1155 * @param $default Boolean if it is default value.
1156 * @param $noHtml Boolean If to avoid html (for back-compat)
1157 * @throws MWException
1158 * @return string language item (Note: despite how this looks,
1159 * this is treated as wikitext not html).
1161 private function langItem( $value, $lang, $default = false, $noHtml = false ) {
1162 if ( $lang === false && $default === false ) {
1163 throw new MWException( '$lang and $default cannot both '
1168 $wrappedValue = $value;
1170 $wrappedValue = '<span class="mw-metadata-lang-value">'
1171 . $value . '</span>';
1174 if ( $lang === false ) {
1175 $msg = $this->msg( 'metadata-langitem-default', $wrappedValue );
1177 return $msg->text() . "\n\n";
1180 return '<li class="mw-metadata-lang-default">'
1185 $lowLang = strtolower( $lang );
1186 $langName = Language
::fetchLanguageName( $lowLang );
1187 if ( $langName === '' ) {
1188 //try just the base language name. (aka en-US -> en ).
1189 list( $langPrefix ) = explode( '-', $lowLang, 2 );
1190 $langName = Language
::fetchLanguageName( $langPrefix );
1191 if ( $langName === '' ) {
1196 // else we have a language specified
1198 $msg = $this->msg( 'metadata-langitem', $wrappedValue, $langName, $lang );
1200 return '*' . $msg->text();
1203 $item = '<li class="mw-metadata-lang-code-'
1206 $item .= ' mw-metadata-lang-default';
1208 $item .= '" lang="' . $lang . '">';
1209 $item .= $msg->text();
1216 * Convenience function for getFormattedData()
1220 * @param string $tag the tag name to pass on
1221 * @param string $val the value of the tag
1222 * @param string $arg an argument to pass ($1)
1223 * @param string $arg2 a 2nd argument to pass ($2)
1224 * @return string The text content of "exif-$tag-$val" message in lower case
1226 private function exifMsg( $tag, $val, $arg = null, $arg2 = null ) {
1229 if ( $val === '' ) {
1233 return $this->msg( $wgContLang->lc( "exif-$tag-$val" ), $arg, $arg2 )->text();
1237 * Format a number, convert numbers from fractions into floating point
1238 * numbers, joins arrays of numbers with commas.
1240 * @param $num Mixed: the value to format
1241 * @param $round float|int|bool digits to round to or false.
1242 * @return mixed A floating point number or whatever we were fed
1244 private function formatNum( $num, $round = false ) {
1246 if ( is_array( $num ) ) {
1248 foreach ( $num as $number ) {
1249 $out[] = $this->formatNum( $number );
1252 return $this->getLanguage()->commaList( $out );
1254 if ( preg_match( '/^(-?\d+)\/(\d+)$/', $num, $m ) ) {
1256 $newNum = $m[1] / $m[2];
1257 if ( $round !== false ) {
1258 $newNum = round( $newNum, $round );
1264 return $this->getLanguage()->formatNum( $newNum );
1266 if ( is_numeric( $num ) && $round !== false ) {
1267 $num = round( $num, $round );
1270 return $this->getLanguage()->formatNum( $num );
1275 * Format a rational number, reducing fractions
1279 * @param $num Mixed: the value to format
1280 * @return mixed A floating point number or whatever we were fed
1282 private function formatFraction( $num ) {
1284 if ( preg_match( '/^(-?\d+)\/(\d+)$/', $num, $m ) ) {
1285 $numerator = intval( $m[1] );
1286 $denominator = intval( $m[2] );
1287 $gcd = $this->gcd( abs( $numerator ), $denominator );
1289 // 0 shouldn't happen! ;)
1290 return $this->formatNum( $numerator / $gcd ) . '/' . $this->formatNum( $denominator / $gcd );
1294 return $this->formatNum( $num );
1298 * Calculate the greatest common divisor of two integers.
1300 * @param $a Integer: Numerator
1301 * @param $b Integer: Denominator
1305 private function gcd( $a, $b ) {
1307 // http://en.wikipedia.org/wiki/Euclidean_algorithm
1308 // Recursive form would be:
1312 return gcd( $b, $a % $b );
1315 $remainder = $a %
$b;
1317 // tail recursion...
1326 * Fetch the human readable version of a news code.
1327 * A news code is an 8 digit code. The first two
1328 * digits are a general classification, so we just
1331 * Note, leading 0's are significant, so this is
1332 * a string, not an int.
1334 * @param string $val The 8 digit news code.
1335 * @return string The human readable form
1337 private function convertNewsCode( $val ) {
1338 if ( !preg_match( '/^\d{8}$/D', $val ) ) {
1339 // Not a valid news code.
1343 switch ( substr( $val, 0, 2 ) ) {
1396 if ( $cat !== '' ) {
1397 $catMsg = $this->exifMsg( 'iimcategory', $cat );
1398 $val = $this->exifMsg( 'subjectnewscode', '', $val, $catMsg );
1405 * Format a coordinate value, convert numbers from floating point
1406 * into degree minute second representation.
1408 * @param int $coord degrees, minutes and seconds
1409 * @param string $type latitude or longitude (for if its a NWS or E)
1410 * @return mixed A floating point number or whatever we were fed
1412 private function formatCoords( $coord, $type ) {
1416 if ( $type === 'latitude' ) {
1418 } elseif ( $type === 'longitude' ) {
1423 if ( $type === 'latitude' ) {
1425 } elseif ( $type === 'longitude' ) {
1430 $deg = floor( $nCoord );
1431 $min = floor( ( $nCoord - $deg ) * 60.0 );
1432 $sec = round( ( ( $nCoord - $deg ) - $min / 60 ) * 3600, 2 );
1434 $deg = $this->formatNum( $deg );
1435 $min = $this->formatNum( $min );
1436 $sec = $this->formatNum( $sec );
1438 return $this->msg( 'exif-coordinate-format', $deg, $min, $sec, $ref, $coord )->text();
1442 * Format the contact info field into a single value.
1444 * @param array $vals array with fields of the ContactInfo
1445 * struct defined in the IPTC4XMP spec. Or potentially
1446 * an array with one element that is a free form text
1447 * value from the older iptc iim 1:118 prop.
1449 * This function might be called from
1450 * JpegHandler::convertMetadataVersion which is why it is
1453 * @return String of html-ish looking wikitext
1454 * @since 1.23 no longer static
1456 public function collapseContactInfo( $vals ) {
1457 if ( !( isset( $vals['CiAdrExtadr'] )
1458 ||
isset( $vals['CiAdrCity'] )
1459 ||
isset( $vals['CiAdrCtry'] )
1460 ||
isset( $vals['CiEmailWork'] )
1461 ||
isset( $vals['CiTelWork'] )
1462 ||
isset( $vals['CiAdrPcode'] )
1463 ||
isset( $vals['CiAdrRegion'] )
1464 ||
isset( $vals['CiUrlWork'] )
1466 // We don't have any sub-properties
1467 // This could happen if its using old
1468 // iptc that just had this as a free-form
1470 // Note: We run this through htmlspecialchars
1471 // partially to be consistent, and partially
1472 // because people often insert >, etc into
1473 // the metadata which should not be interpreted
1474 // but we still want to auto-link urls.
1475 foreach ( $vals as &$val ) {
1476 $val = htmlspecialchars( $val );
1479 return $this->flattenArrayReal( $vals );
1481 // We have a real ContactInfo field.
1482 // Its unclear if all these fields have to be
1483 // set, so assume they do not.
1484 $url = $tel = $street = $city = $country = '';
1485 $email = $postal = $region = '';
1487 // Also note, some of the class names this uses
1488 // are similar to those used by hCard. This is
1489 // mostly because they're sensible names. This
1490 // does not (and does not attempt to) output
1491 // stuff in the hCard microformat. However it
1492 // might output in the adr microformat.
1494 if ( isset( $vals['CiAdrExtadr'] ) ) {
1495 // Todo: This can potentially be multi-line.
1496 // Need to check how that works in XMP.
1497 $street = '<span class="extended-address">'
1499 $vals['CiAdrExtadr'] )
1502 if ( isset( $vals['CiAdrCity'] ) ) {
1503 $city = '<span class="locality">'
1504 . htmlspecialchars( $vals['CiAdrCity'] )
1507 if ( isset( $vals['CiAdrCtry'] ) ) {
1508 $country = '<span class="country-name">'
1509 . htmlspecialchars( $vals['CiAdrCtry'] )
1512 if ( isset( $vals['CiEmailWork'] ) ) {
1514 // Have to split multiple emails at commas/new lines.
1515 $splitEmails = explode( "\n", $vals['CiEmailWork'] );
1516 foreach ( $splitEmails as $e1 ) {
1517 // Also split on comma
1518 foreach ( explode( ',', $e1 ) as $e2 ) {
1519 $finalEmail = trim( $e2 );
1520 if ( $finalEmail == ',' ||
$finalEmail == '' ) {
1523 if ( strpos( $finalEmail, '<' ) !== false ) {
1524 // Don't do fancy formatting to
1525 // "My name" <foo@bar.com> style stuff
1526 $emails[] = $finalEmail;
1528 $emails[] = '[mailto:'
1530 . ' <span class="email">'
1536 $email = implode( ', ', $emails );
1538 if ( isset( $vals['CiTelWork'] ) ) {
1539 $tel = '<span class="tel">'
1540 . htmlspecialchars( $vals['CiTelWork'] )
1543 if ( isset( $vals['CiAdrPcode'] ) ) {
1544 $postal = '<span class="postal-code">'
1546 $vals['CiAdrPcode'] )
1549 if ( isset( $vals['CiAdrRegion'] ) ) {
1550 // Note this is province/state.
1551 $region = '<span class="region">'
1553 $vals['CiAdrRegion'] )
1556 if ( isset( $vals['CiUrlWork'] ) ) {
1557 $url = '<span class="url">'
1558 . htmlspecialchars( $vals['CiUrlWork'] )
1562 return $this->msg( 'exif-contact-value', $email, $url,
1563 $street, $city, $region, $postal, $country,
1569 * Get a list of fields that are visible by default.
1574 public static function getVisibleFields() {
1576 $lines = explode( "\n", wfMessage( 'metadata-fields' )->inContentLanguage()->text() );
1577 foreach ( $lines as $line ) {
1579 if ( preg_match( '/^\\*\s*(.*?)\s*$/', $line, $matches ) ) {
1580 $fields[] = $matches[1];
1583 $fields = array_map( 'strtolower', $fields );
1589 * Get an array of extended metadata. (See the imageinfo API for format.)
1591 * @param File $file File to use
1592 * @return array [<property name> => ['value' => <value>]], or [] on error
1595 public function fetchExtendedMetadata( File
$file ) {
1598 wfProfileIn( __METHOD__
);
1600 // If revision deleted, exit immediately
1601 if ( $file->isDeleted( File
::DELETED_FILE
) ) {
1602 wfProfileOut( __METHOD__
);
1607 $cacheKey = wfMemcKey(
1608 'getExtendedMetadata',
1609 $this->getLanguage()->getCode(),
1610 (int)$this->singleLang
,
1614 $cachedValue = $wgMemc->get( $cacheKey );
1617 && wfRunHooks( 'ValidateExtendedMetadataCache', array( $cachedValue['timestamp'], $file ) )
1619 $extendedMetadata = $cachedValue['data'];
1621 $maxCacheTime = ( $file instanceof ForeignAPIFile
) ?
60 * 60 * 12 : 60 * 60 * 24 * 30;
1622 $fileMetadata = $this->getExtendedMetadataFromFile( $file );
1623 $extendedMetadata = $this->getExtendedMetadataFromHook( $file, $fileMetadata, $maxCacheTime );
1624 if ( $this->singleLang
) {
1625 $this->resolveMultilangMetadata( $extendedMetadata );
1627 // Make sure the metadata won't break the API when an XML format is used.
1628 // This is an API-specific function so it would be cleaner to call it from
1629 // outside fetchExtendedMetadata, but this way we don't need to redo the
1630 // computation on a cache hit.
1631 $this->sanitizeArrayForXml( $extendedMetadata );
1632 $valueToCache = array( 'data' => $extendedMetadata, 'timestamp' => wfTimestampNow() );
1633 $wgMemc->set( $cacheKey, $valueToCache, $maxCacheTime );
1636 wfProfileOut( __METHOD__
);
1638 return $extendedMetadata;
1642 * Get file-based metadata in standardized format.
1644 * Note that for a remote file, this might return metadata supplied by extensions.
1646 * @param File $file File to use
1647 * @return array [<property name> => ['value' => <value>]], or [] on error
1650 protected function getExtendedMetadataFromFile( File
$file ) {
1651 // If this is a remote file accessed via an API request, we already
1652 // have remote metadata so we just ignore any local one
1653 if ( $file instanceof ForeignAPIFile
) {
1654 // in case of error we pretend no metadata - this will get cached. Might or might not be a good idea.
1655 return $file->getExtendedMetadata() ?
: array();
1658 wfProfileIn( __METHOD__
);
1660 $uploadDate = wfTimestamp( TS_ISO_8601
, $file->getTimestamp() );
1662 $fileMetadata = array(
1663 // This is modification time, which is close to "upload" time.
1664 'DateTime' => array(
1665 'value' => $uploadDate,
1666 'source' => 'mediawiki-metadata',
1670 $title = $file->getTitle();
1672 $text = $title->getText();
1673 $pos = strrpos( $text, '.' );
1676 $name = substr( $text, 0, $pos );
1681 $fileMetadata['ObjectName'] = array(
1683 'source' => 'mediawiki-metadata',
1687 $common = $file->getCommonMetaArray();
1689 if ( $common !== false ) {
1690 foreach ( $common as $key => $value ) {
1691 $fileMetadata[$key] = array(
1693 'source' => 'file-metadata',
1698 wfProfileOut( __METHOD__
);
1700 return $fileMetadata;
1704 * Get additional metadata from hooks in standardized format.
1706 * @param File $file File to use
1707 * @param array $extendedMetadata
1708 * @param int $maxCacheTime hook handlers might use this parameter to override cache time
1710 * @return array [<property name> => ['value' => <value>]], or [] on error
1713 protected function getExtendedMetadataFromHook( File
$file, array $extendedMetadata, &$maxCacheTime ) {
1714 wfProfileIn( __METHOD__
);
1716 wfRunHooks( 'GetExtendedMetadata', array(
1719 $this->getContext(),
1724 $visible = array_flip( self
::getVisibleFields() );
1725 foreach ( $extendedMetadata as $key => $value ) {
1726 if ( !isset( $visible[strtolower( $key )] ) ) {
1727 $extendedMetadata[$key]['hidden'] = '';
1731 wfProfileOut( __METHOD__
);
1733 return $extendedMetadata;
1737 * Turns an XMP-style multilang array into a single value.
1738 * If the value is not a multilang array, it is returned unchanged.
1739 * See mediawiki.org/wiki/Manual:File_metadata_handling#Multi-language_array_format
1740 * @param mixed $value
1741 * @return mixed value in best language, null if there were no languages at all
1744 protected function resolveMultilangValue( $value ) {
1747 ||
!isset( $value['_type'] )
1748 ||
$value['_type'] != 'lang'
1750 return $value; // do nothing if not a multilang array
1753 // choose the language best matching user or site settings
1754 $priorityLanguages = $this->getPriorityLanguages();
1755 foreach ( $priorityLanguages as $lang ) {
1756 if ( isset( $value[$lang] ) ) {
1757 return $value[$lang];
1761 // otherwise go with the default language, if set
1762 if ( isset( $value['x-default'] ) ) {
1763 return $value['x-default'];
1766 // otherwise just return any one language
1767 unset( $value['_type'] );
1768 if ( !empty( $value ) ) {
1769 return reset( $value );
1772 // this should not happen; signal error
1777 * Takes an array returned by the getExtendedMetadata* functions,
1778 * and resolves multi-language values in it.
1779 * @param array $metadata
1782 protected function resolveMultilangMetadata( &$metadata ) {
1783 if ( !is_array( $metadata ) ) {
1786 foreach ( $metadata as &$field ) {
1787 if ( isset( $field['value'] ) ) {
1788 $field['value'] = $this->resolveMultilangValue( $field['value'] );
1794 * Makes sure the given array is a valid API response fragment
1795 * (can be transformed into XML)
1798 protected function sanitizeArrayForXml( &$arr ) {
1799 if ( !is_array( $arr ) ) {
1804 foreach ( $arr as $key => &$value ) {
1805 $sanitizedKey = $this->sanitizeKeyForXml( $key );
1806 if ( $sanitizedKey !== $key ) {
1807 if ( isset( $arr[$sanitizedKey] ) ) {
1808 // Make the sanitized keys hopefully unique.
1809 // To make it definitely unique would be too much effort, given that
1810 // sanitizing is only needed for misformatted metadata anyway, but
1811 // this at least covers the case when $arr is numeric.
1812 $sanitizedKey .= $counter;
1815 $arr[$sanitizedKey] = $arr[$key];
1816 unset( $arr[$key] );
1818 if ( is_array( $value ) ) {
1819 $this->sanitizeArrayForXml( $value );
1825 * Turns a string into a valid XML identifier.
1826 * Used to ensure that keys of an associative array in the
1827 * API response do not break the XML formatter.
1828 * @param string $key
1832 protected function sanitizeKeyForXml( $key ) {
1833 // drop all characters which are not valid in an XML tag name
1834 // a bunch of non-ASCII letters would be valid but probably won't
1835 // be used so we take the easy way
1836 $key = preg_replace( '/[^a-zA-z0-9_:.-]/', '', $key );
1837 // drop characters which are invalid at the first position
1838 $key = preg_replace( '/^[\d-.]+/', '', $key );
1844 // special case for an internal keyword
1845 if ( $key == '_element' ) {
1853 * Returns a list of languages (first is best) to use when formatting multilang fields,
1854 * based on user and site preferences.
1858 protected function getPriorityLanguages() {
1859 $priorityLanguages = Language
::getFallbacksIncludingSiteLanguage( $this->getLanguage()->getCode() );
1860 $priorityLanguages = array_merge( (array)$this->getLanguage()->getCode(), $priorityLanguages[0], $priorityLanguages[1] );
1862 return $priorityLanguages;
1866 /** For compatability with old FormatExif class
1867 * which some extensions use.
1869 * @deprecated since 1.18
1876 * @param $meta array
1878 function FormatExif( $meta ) {
1879 wfDeprecated( __METHOD__
, '1.18' );
1880 $this->meta
= $meta;
1886 function getFormattedData() {
1887 return FormatMetadata
::getFormattedData( $this->meta
);