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 http://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 * Flatten an array, using the user language for any messages.
1009 * @param array $vals Array of values
1010 * @param string $type Type of array (either lang, ul, ol).
1011 * lang = language assoc array with keys being the lang code
1012 * ul = unordered list, ol = ordered list
1013 * type can also come from the '_type' member of $vals.
1014 * @param bool $noHtml If to avoid returning anything resembling HTML.
1015 * (Ugly hack for backwards compatibility with old MediaWiki).
1016 * @param bool|IContextSource $context
1017 * @return string Single value (in wiki-syntax).
1019 public static function flattenArray( $vals, $type = 'ul', $noHtml = false, $context = false ) {
1020 $obj = new FormatMetadata
;
1022 $obj->setContext( $context );
1025 return $obj->flattenArrayReal( $vals, $type, $noHtml );
1029 * A function to collapse multivalued tags into a single value.
1030 * This turns an array of (for example) authors into a bulleted list.
1032 * This is public on the basis it might be useful outside of this class.
1034 * @param array $vals Array of values
1035 * @param string $type Type of array (either lang, ul, ol).
1036 * lang = language assoc array with keys being the lang code
1037 * ul = unordered list, ol = ordered list
1038 * type can also come from the '_type' member of $vals.
1039 * @param bool $noHtml If to avoid returning anything resembling HTML.
1040 * (Ugly hack for backwards compatibility with old mediawiki).
1041 * @return string Single value (in wiki-syntax).
1044 public function flattenArrayReal( $vals, $type = 'ul', $noHtml = false ) {
1045 if ( !is_array( $vals ) ) {
1046 return $vals; // do nothing if not an array;
1049 if ( isset( $vals['_type'] ) ) {
1050 $type = $vals['_type'];
1051 unset( $vals['_type'] );
1054 if ( !is_array( $vals ) ) {
1055 return $vals; // do nothing if not an array;
1056 } elseif ( count( $vals ) === 1 && $type !== 'lang' ) {
1058 } elseif ( count( $vals ) === 0 ) {
1059 wfDebug( __METHOD__
. " metadata array with 0 elements!\n" );
1061 return ""; // paranoia. This should never happen
1063 /* @todo FIXME: This should hide some of the list entries if there are
1064 * say more than four. Especially if a field is translated into 20
1065 * languages, we don't want to show them all by default
1069 // Display default, followed by ContLang,
1070 // followed by the rest in no particular
1073 // Todo: hide some items if really long list.
1077 $priorityLanguages = $this->getPriorityLanguages();
1078 $defaultItem = false;
1079 $defaultLang = false;
1081 // If default is set, save it for later,
1082 // as we don't know if it's equal to
1083 // one of the lang codes. (In xmp
1084 // you specify the language for a
1085 // default property by having both
1086 // a default prop, and one in the language
1087 // that are identical)
1088 if ( isset( $vals['x-default'] ) ) {
1089 $defaultItem = $vals['x-default'];
1090 unset( $vals['x-default'] );
1092 foreach ( $priorityLanguages as $pLang ) {
1093 if ( isset( $vals[$pLang] ) ) {
1095 if ( $vals[$pLang] === $defaultItem ) {
1096 $defaultItem = false;
1099 $content .= $this->langItem(
1100 $vals[$pLang], $pLang,
1101 $isDefault, $noHtml );
1103 unset( $vals[$pLang] );
1105 if ( $this->singleLang
) {
1106 return Html
::rawElement( 'span',
1107 array( 'lang' => $pLang ), $vals[$pLang] );
1113 foreach ( $vals as $lang => $item ) {
1114 if ( $item === $defaultItem ) {
1115 $defaultLang = $lang;
1118 $content .= $this->langItem( $item,
1119 $lang, false, $noHtml );
1120 if ( $this->singleLang
) {
1121 return Html
::rawElement( 'span',
1122 array( 'lang' => $lang ), $item );
1125 if ( $defaultItem !== false ) {
1126 $content = $this->langItem( $defaultItem,
1127 $defaultLang, true, $noHtml ) .
1129 if ( $this->singleLang
) {
1130 return $defaultItem;
1137 return '<ul class="metadata-langlist">' .
1142 return "\n#" . implode( "\n#", $vals );
1145 return "<ol><li>" . implode( "</li>\n<li>", $vals ) . '</li></ol>';
1149 return "\n*" . implode( "\n*", $vals );
1152 return "<ul><li>" . implode( "</li>\n<li>", $vals ) . '</li></ul>';
1157 /** Helper function for creating lists of translations.
1159 * @param string $value Value (this is not escaped)
1160 * @param string $lang Lang code of item or false
1161 * @param bool $default If it is default value.
1162 * @param bool $noHtml If to avoid html (for back-compat)
1163 * @throws MWException
1164 * @return string Language item (Note: despite how this looks, this is
1165 * treated as wikitext, not as HTML).
1167 private function langItem( $value, $lang, $default = false, $noHtml = false ) {
1168 if ( $lang === false && $default === false ) {
1169 throw new MWException( '$lang and $default cannot both '
1174 $wrappedValue = $value;
1176 $wrappedValue = '<span class="mw-metadata-lang-value">'
1177 . $value . '</span>';
1180 if ( $lang === false ) {
1181 $msg = $this->msg( 'metadata-langitem-default', $wrappedValue );
1183 return $msg->text() . "\n\n";
1186 return '<li class="mw-metadata-lang-default">'
1191 $lowLang = strtolower( $lang );
1192 $langName = Language
::fetchLanguageName( $lowLang );
1193 if ( $langName === '' ) {
1194 //try just the base language name. (aka en-US -> en ).
1195 list( $langPrefix ) = explode( '-', $lowLang, 2 );
1196 $langName = Language
::fetchLanguageName( $langPrefix );
1197 if ( $langName === '' ) {
1202 // else we have a language specified
1204 $msg = $this->msg( 'metadata-langitem', $wrappedValue, $langName, $lang );
1206 return '*' . $msg->text();
1209 $item = '<li class="mw-metadata-lang-code-'
1212 $item .= ' mw-metadata-lang-default';
1214 $item .= '" lang="' . $lang . '">';
1215 $item .= $msg->text();
1222 * Convenience function for getFormattedData()
1224 * @param string $tag The tag name to pass on
1225 * @param string $val The value of the tag
1226 * @param string $arg An argument to pass ($1)
1227 * @param string $arg2 A 2nd argument to pass ($2)
1228 * @return string The text content of "exif-$tag-$val" message in lower case
1230 private function exifMsg( $tag, $val, $arg = null, $arg2 = null ) {
1233 if ( $val === '' ) {
1237 return $this->msg( $wgContLang->lc( "exif-$tag-$val" ), $arg, $arg2 )->text();
1241 * Format a number, convert numbers from fractions into floating point
1242 * numbers, joins arrays of numbers with commas.
1244 * @param mixed $num The value to format
1245 * @param float|int|bool $round Digits to round to or false.
1246 * @return mixed A floating point number or whatever we were fed
1248 private function formatNum( $num, $round = false ) {
1250 if ( is_array( $num ) ) {
1252 foreach ( $num as $number ) {
1253 $out[] = $this->formatNum( $number );
1256 return $this->getLanguage()->commaList( $out );
1258 if ( preg_match( '/^(-?\d+)\/(\d+)$/', $num, $m ) ) {
1260 $newNum = $m[1] / $m[2];
1261 if ( $round !== false ) {
1262 $newNum = round( $newNum, $round );
1268 return $this->getLanguage()->formatNum( $newNum );
1270 if ( is_numeric( $num ) && $round !== false ) {
1271 $num = round( $num, $round );
1274 return $this->getLanguage()->formatNum( $num );
1279 * Format a rational number, reducing fractions
1281 * @param mixed $num The value to format
1282 * @return mixed A floating point number or whatever we were fed
1284 private function formatFraction( $num ) {
1286 if ( preg_match( '/^(-?\d+)\/(\d+)$/', $num, $m ) ) {
1287 $numerator = intval( $m[1] );
1288 $denominator = intval( $m[2] );
1289 $gcd = $this->gcd( abs( $numerator ), $denominator );
1291 // 0 shouldn't happen! ;)
1292 return $this->formatNum( $numerator / $gcd ) . '/' . $this->formatNum( $denominator / $gcd );
1296 return $this->formatNum( $num );
1300 * Calculate the greatest common divisor of two integers.
1302 * @param int $a Numerator
1303 * @param int $b Denominator
1306 private function gcd( $a, $b ) {
1308 // http://en.wikipedia.org/wiki/Euclidean_algorithm
1309 // Recursive form would be:
1313 return gcd( $b, $a % $b );
1316 $remainder = $a %
$b;
1318 // tail recursion...
1327 * Fetch the human readable version of a news code.
1328 * A news code is an 8 digit code. The first two
1329 * digits are a general classification, so we just
1332 * Note, leading 0's are significant, so this is
1333 * a string, not an int.
1335 * @param string $val The 8 digit news code.
1336 * @return string The human readable form
1338 private function convertNewsCode( $val ) {
1339 if ( !preg_match( '/^\d{8}$/D', $val ) ) {
1340 // Not a valid news code.
1344 switch ( substr( $val, 0, 2 ) ) {
1397 if ( $cat !== '' ) {
1398 $catMsg = $this->exifMsg( 'iimcategory', $cat );
1399 $val = $this->exifMsg( 'subjectnewscode', '', $val, $catMsg );
1406 * Format a coordinate value, convert numbers from floating point
1407 * into degree minute second representation.
1409 * @param int $coord Degrees, minutes and seconds
1410 * @param string $type Latitude or longitude (for if its a NWS or E)
1411 * @return mixed A floating point number or whatever we were fed
1413 private function formatCoords( $coord, $type ) {
1417 if ( $type === 'latitude' ) {
1419 } elseif ( $type === 'longitude' ) {
1424 if ( $type === 'latitude' ) {
1426 } elseif ( $type === 'longitude' ) {
1431 $deg = floor( $nCoord );
1432 $min = floor( ( $nCoord - $deg ) * 60.0 );
1433 $sec = round( ( ( $nCoord - $deg ) - $min / 60 ) * 3600, 2 );
1435 $deg = $this->formatNum( $deg );
1436 $min = $this->formatNum( $min );
1437 $sec = $this->formatNum( $sec );
1439 return $this->msg( 'exif-coordinate-format', $deg, $min, $sec, $ref, $coord )->text();
1443 * Format the contact info field into a single value.
1445 * This function might be called from
1446 * JpegHandler::convertMetadataVersion which is why it is
1449 * @param array $vals Array with fields of the ContactInfo
1450 * struct defined in the IPTC4XMP spec. Or potentially
1451 * an array with one element that is a free form text
1452 * value from the older iptc iim 1:118 prop.
1453 * @return string 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.
1655 // Might or might not be a good idea.
1656 return $file->getExtendedMetadata() ?
: array();
1659 wfProfileIn( __METHOD__
);
1661 $uploadDate = wfTimestamp( TS_ISO_8601
, $file->getTimestamp() );
1663 $fileMetadata = array(
1664 // This is modification time, which is close to "upload" time.
1665 'DateTime' => array(
1666 'value' => $uploadDate,
1667 'source' => 'mediawiki-metadata',
1671 $title = $file->getTitle();
1673 $text = $title->getText();
1674 $pos = strrpos( $text, '.' );
1677 $name = substr( $text, 0, $pos );
1682 $fileMetadata['ObjectName'] = array(
1684 'source' => 'mediawiki-metadata',
1688 $common = $file->getCommonMetaArray();
1690 if ( $common !== false ) {
1691 foreach ( $common as $key => $value ) {
1692 $fileMetadata[$key] = array(
1694 'source' => 'file-metadata',
1699 wfProfileOut( __METHOD__
);
1701 return $fileMetadata;
1705 * Get additional metadata from hooks in standardized format.
1707 * @param File $file File to use
1708 * @param array $extendedMetadata
1709 * @param int $maxCacheTime Hook handlers might use this parameter to override cache time
1711 * @return array [<property name> => ['value' => <value>]], or [] on error
1714 protected function getExtendedMetadataFromHook( File
$file, array $extendedMetadata,
1717 wfProfileIn( __METHOD__
);
1719 wfRunHooks( 'GetExtendedMetadata', array(
1722 $this->getContext(),
1727 $visible = array_flip( self
::getVisibleFields() );
1728 foreach ( $extendedMetadata as $key => $value ) {
1729 if ( !isset( $visible[strtolower( $key )] ) ) {
1730 $extendedMetadata[$key]['hidden'] = '';
1734 wfProfileOut( __METHOD__
);
1736 return $extendedMetadata;
1740 * Turns an XMP-style multilang array into a single value.
1741 * If the value is not a multilang array, it is returned unchanged.
1742 * See mediawiki.org/wiki/Manual:File_metadata_handling#Multi-language_array_format
1743 * @param mixed $value
1744 * @return mixed Value in best language, null if there were no languages at all
1747 protected function resolveMultilangValue( $value ) {
1750 ||
!isset( $value['_type'] )
1751 ||
$value['_type'] != 'lang'
1753 return $value; // do nothing if not a multilang array
1756 // choose the language best matching user or site settings
1757 $priorityLanguages = $this->getPriorityLanguages();
1758 foreach ( $priorityLanguages as $lang ) {
1759 if ( isset( $value[$lang] ) ) {
1760 return $value[$lang];
1764 // otherwise go with the default language, if set
1765 if ( isset( $value['x-default'] ) ) {
1766 return $value['x-default'];
1769 // otherwise just return any one language
1770 unset( $value['_type'] );
1771 if ( !empty( $value ) ) {
1772 return reset( $value );
1775 // this should not happen; signal error
1780 * Takes an array returned by the getExtendedMetadata* functions,
1781 * and resolves multi-language values in it.
1782 * @param array $metadata
1785 protected function resolveMultilangMetadata( &$metadata ) {
1786 if ( !is_array( $metadata ) ) {
1789 foreach ( $metadata as &$field ) {
1790 if ( isset( $field['value'] ) ) {
1791 $field['value'] = $this->resolveMultilangValue( $field['value'] );
1797 * Makes sure the given array is a valid API response fragment
1798 * (can be transformed into XML)
1801 protected function sanitizeArrayForXml( &$arr ) {
1802 if ( !is_array( $arr ) ) {
1807 foreach ( $arr as $key => &$value ) {
1808 $sanitizedKey = $this->sanitizeKeyForXml( $key );
1809 if ( $sanitizedKey !== $key ) {
1810 if ( isset( $arr[$sanitizedKey] ) ) {
1811 // Make the sanitized keys hopefully unique.
1812 // To make it definitely unique would be too much effort, given that
1813 // sanitizing is only needed for misformatted metadata anyway, but
1814 // this at least covers the case when $arr is numeric.
1815 $sanitizedKey .= $counter;
1818 $arr[$sanitizedKey] = $arr[$key];
1819 unset( $arr[$key] );
1821 if ( is_array( $value ) ) {
1822 $this->sanitizeArrayForXml( $value );
1828 * Turns a string into a valid XML identifier.
1829 * Used to ensure that keys of an associative array in the
1830 * API response do not break the XML formatter.
1831 * @param string $key
1835 protected function sanitizeKeyForXml( $key ) {
1836 // drop all characters which are not valid in an XML tag name
1837 // a bunch of non-ASCII letters would be valid but probably won't
1838 // be used so we take the easy way
1839 $key = preg_replace( '/[^a-zA-z0-9_:.-]/', '', $key );
1840 // drop characters which are invalid at the first position
1841 $key = preg_replace( '/^[\d-.]+/', '', $key );
1847 // special case for an internal keyword
1848 if ( $key == '_element' ) {
1856 * Returns a list of languages (first is best) to use when formatting multilang fields,
1857 * based on user and site preferences.
1861 protected function getPriorityLanguages() {
1862 $priorityLanguages =
1863 Language
::getFallbacksIncludingSiteLanguage( $this->getLanguage()->getCode() );
1864 $priorityLanguages = array_merge(
1865 (array)$this->getLanguage()->getCode(),
1866 $priorityLanguages[0],
1867 $priorityLanguages[1]
1870 return $priorityLanguages;