1b1841c3a3bbdebc09ce0fae6287c494a31504bf
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
{
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 IContextSource $context Context to use (optional)
80 public static function getFormattedData( $tags, $context = false ) {
81 $obj = new FormatMetadata
;
83 $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 ) {
171 case 1: case 2: case 3: case 4:
172 case 5: case 6: case 7: case 8:
173 case 32773: case 32946: case 34712:
174 $val = $this->exifMsg( $tag, $val );
177 /* If not recognized, display as is. */
182 case 'PhotometricInterpretation':
185 $val = $this->exifMsg( $tag, $val );
188 /* If not recognized, display as is. */
195 case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8:
196 $val = $this->exifMsg( $tag, $val );
199 /* If not recognized, display as is. */
204 case 'PlanarConfiguration':
207 $val = $this->exifMsg( $tag, $val );
210 /* If not recognized, display as is. */
215 // TODO: YCbCrSubSampling
216 case 'YCbCrPositioning':
220 $val = $this->exifMsg( $tag, $val );
223 /* If not recognized, display as is. */
230 switch ( $resolutionunit ) {
232 $val = $this->exifMsg( 'XYResolution', 'i', $this->formatNum( $val ) );
235 $val = $this->exifMsg( 'XYResolution', 'c', $this->formatNum( $val ) );
238 /* If not recognized, display as is. */
243 // TODO: YCbCrCoefficients #p27 (see annex E)
244 case 'ExifVersion': case 'FlashpixVersion':
251 $val = $this->exifMsg( $tag, $val );
254 /* If not recognized, display as is. */
259 case 'ComponentsConfiguration':
261 case 0: case 1: case 2: case 3: case 4: case 5: case 6:
262 $val = $this->exifMsg( $tag, $val );
265 /* If not recognized, display as is. */
271 case 'DateTimeOriginal':
272 case 'DateTimeDigitized':
273 case 'DateTimeReleased':
274 case 'DateTimeExpires':
277 case 'DateTimeMetadata':
278 if ( $val == '0000:00:00 00:00:00' ||
$val == ' : : : : ' ) {
279 $val = $this->msg( 'exif-unknowndate' )->text();
280 } elseif ( preg_match( '/^(?:\d{4}):(?:\d\d):(?:\d\d) (?:\d\d):(?:\d\d):(?:\d\d)$/D', $val ) ) {
282 $time = wfTimestamp( TS_MW
, $val );
283 if ( $time && intval( $time ) > 0 ) {
284 $val = $this->getLanguage()->timeanddate( $time );
286 } elseif ( preg_match( '/^(?:\d{4}):(?:\d\d):(?:\d\d) (?:\d\d):(?:\d\d)$/D', $val ) ) {
287 // No second field. Still format the same
288 // since timeanddate doesn't include seconds anyways,
289 // but second still available in api
290 $time = wfTimestamp( TS_MW
, $val . ':00' );
291 if ( $time && intval( $time ) > 0 ) {
292 $val = $this->getLanguage()->timeanddate( $time );
294 } elseif ( preg_match( '/^(?:\d{4}):(?:\d\d):(?:\d\d)$/D', $val ) ) {
295 // If only the date but not the time is filled in.
296 $time = wfTimestamp( TS_MW
, substr( $val, 0, 4 )
297 . substr( $val, 5, 2 )
298 . substr( $val, 8, 2 )
300 if ( $time && intval( $time ) > 0 ) {
301 $val = $this->getLanguage()->date( $time );
304 // else it will just output $val without formatting it.
307 case 'ExposureProgram':
309 case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8:
310 $val = $this->exifMsg( $tag, $val );
313 /* If not recognized, display as is. */
318 case 'SubjectDistance':
319 $val = $this->exifMsg( $tag, '', $this->formatNum( $val ) );
324 case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 255:
325 $val = $this->exifMsg( $tag, $val );
328 /* If not recognized, display as is. */
335 case 0: case 1: case 2: case 3: case 4: case 9: case 10: case 11:
336 case 12: case 13: case 14: case 15: case 17: case 18: case 19: case 20:
337 case 21: case 22: case 23: case 24: case 255:
338 $val = $this->exifMsg( $tag, $val );
341 /* If not recognized, display as is. */
347 $flashDecode = array(
348 'fired' => $val & bindec( '00000001' ),
349 'return' => ( $val & bindec( '00000110' ) ) >> 1,
350 'mode' => ( $val & bindec( '00011000' ) ) >> 3,
351 'function' => ( $val & bindec( '00100000' ) ) >> 5,
352 'redeye' => ( $val & bindec( '01000000' ) ) >> 6,
353 // 'reserved' => ($val & bindec( '10000000' )) >> 7,
355 $flashMsgs = array();
356 # We do not need to handle unknown values since all are used.
357 foreach ( $flashDecode as $subTag => $subValue ) {
358 # We do not need any message for zeroed values.
359 if ( $subTag != 'fired' && $subValue == 0 ) {
362 $fullTag = $tag . '-' . $subTag;
363 $flashMsgs[] = $this->exifMsg( $fullTag, $subValue );
365 $val = $this->getLanguage()->commaList( $flashMsgs );
368 case 'FocalPlaneResolutionUnit':
371 $val = $this->exifMsg( $tag, $val );
374 /* If not recognized, display as is. */
379 case 'SensingMethod':
381 case 1: case 2: case 3: case 4: case 5: case 7: case 8:
382 $val = $this->exifMsg( $tag, $val );
385 /* If not recognized, display as is. */
393 $val = $this->exifMsg( $tag, $val );
396 /* If not recognized, display as is. */
404 $val = $this->exifMsg( $tag, $val );
407 /* If not recognized, display as is. */
412 case 'CustomRendered':
415 $val = $this->exifMsg( $tag, $val );
418 /* If not recognized, display as is. */
425 case 0: case 1: case 2:
426 $val = $this->exifMsg( $tag, $val );
429 /* If not recognized, display as is. */
437 $val = $this->exifMsg( $tag, $val );
440 /* If not recognized, display as is. */
445 case 'SceneCaptureType':
447 case 0: case 1: case 2: case 3:
448 $val = $this->exifMsg( $tag, $val );
451 /* If not recognized, display as is. */
458 case 0: case 1: case 2: case 3: case 4:
459 $val = $this->exifMsg( $tag, $val );
462 /* If not recognized, display as is. */
469 case 0: case 1: case 2:
470 $val = $this->exifMsg( $tag, $val );
473 /* If not recognized, display as is. */
480 case 0: case 1: case 2:
481 $val = $this->exifMsg( $tag, $val );
484 /* If not recognized, display as is. */
491 case 0: case 1: case 2:
492 $val = $this->exifMsg( $tag, $val );
495 /* If not recognized, display as is. */
500 case 'SubjectDistanceRange':
502 case 0: case 1: case 2: case 3:
503 $val = $this->exifMsg( $tag, $val );
506 /* If not recognized, display as is. */
511 //The GPS...Ref values are kept for compatibility, probably won't be reached.
512 case 'GPSLatitudeRef':
513 case 'GPSDestLatitudeRef':
516 $val = $this->exifMsg( 'GPSLatitude', $val );
519 /* If not recognized, display as is. */
524 case 'GPSLongitudeRef':
525 case 'GPSDestLongitudeRef':
528 $val = $this->exifMsg( 'GPSLongitude', $val );
531 /* If not recognized, display as is. */
538 $val = $this->exifMsg( 'GPSAltitude', 'below-sealevel', $this->formatNum( -$val, 3 ) );
540 $val = $this->exifMsg( 'GPSAltitude', 'above-sealevel', $this->formatNum( $val, 3 ) );
547 $val = $this->exifMsg( $tag, $val );
550 /* If not recognized, display as is. */
555 case 'GPSMeasureMode':
558 $val = $this->exifMsg( $tag, $val );
561 /* If not recognized, display as is. */
567 case 'GPSImgDirectionRef':
568 case 'GPSDestBearingRef':
571 $val = $this->exifMsg( 'GPSDirection', $val );
574 /* If not recognized, display as is. */
580 case 'GPSDestLatitude':
581 $val = $this->formatCoords( $val, 'latitude' );
584 case 'GPSDestLongitude':
585 $val = $this->formatCoords( $val, 'longitude' );
590 case 'K': case 'M': case 'N':
591 $val = $this->exifMsg( 'GPSSpeed', $val );
594 /* If not recognized, display as is. */
599 case 'GPSDestDistanceRef':
601 case 'K': case 'M': case 'N':
602 $val = $this->exifMsg( 'GPSDestDistance', $val );
605 /* If not recognized, display as is. */
611 // See http://en.wikipedia.org/wiki/Dilution_of_precision_(GPS)
613 $val = $this->exifMsg( $tag, 'excellent', $this->formatNum( $val ) );
614 } elseif ( $val <= 5 ) {
615 $val = $this->exifMsg( $tag, 'good', $this->formatNum( $val ) );
616 } elseif ( $val <= 10 ) {
617 $val = $this->exifMsg( $tag, 'moderate', $this->formatNum( $val ) );
618 } elseif ( $val <= 20 ) {
619 $val = $this->exifMsg( $tag, 'fair', $this->formatNum( $val ) );
621 $val = $this->exifMsg( $tag, 'poor', $this->formatNum( $val ) );
625 // This is not in the Exif standard, just a special
626 // case for our purposes which enables wikis to wikify
627 // the make, model and software name to link to their articles.
630 $val = $this->exifMsg( $tag, '', $val );
634 if ( is_array( $val ) ) {
635 //if its a software, version array.
636 $val = $this->msg( 'exif-software-version-value', $val[0], $val[1] )->text();
638 $val = $this->exifMsg( $tag, '', $val );
643 // Show the pretty fraction as well as decimal version
644 $val = $this->msg( 'exif-exposuretime-format',
645 $this->formatFraction( $val ), $this->formatNum( $val ) )->text();
647 case 'ISOSpeedRatings':
648 // If its = 65535 that means its at the
649 // limit of the size of Exif::short and
651 if ( $val == '65535' ) {
652 $val = $this->exifMsg( $tag, 'overflow' );
654 $val = $this->formatNum( $val );
658 $val = $this->msg( 'exif-fnumber-format',
659 $this->formatNum( $val ) )->text();
662 case 'FocalLength': case 'FocalLengthIn35mmFilm':
663 $val = $this->msg( 'exif-focallength-format',
664 $this->formatNum( $val ) )->text();
667 case 'MaxApertureValue':
668 if ( strpos( $val, '/' ) !== false ) {
669 // need to expand this earlier to calculate fNumber
670 list( $n, $d ) = explode( '/', $val );
671 if ( is_numeric( $n ) && is_numeric( $d ) ) {
675 if ( is_numeric( $val ) ) {
676 $fNumber = pow( 2, $val / 2 );
677 if ( $fNumber !== false ) {
678 $val = $this->msg( 'exif-maxaperturevalue-value',
679 $this->formatNum( $val ),
680 $this->formatNum( $fNumber, 2 )
687 switch ( strtolower( $val ) ) {
688 // See pg 29 of IPTC photo
689 // metadata standard.
690 case 'ace': case 'clj':
691 case 'dis': case 'fin':
692 case 'edu': case 'evn':
693 case 'hth': case 'hum':
694 case 'lab': case 'lif':
695 case 'pol': case 'rel':
696 case 'sci': case 'soi':
697 case 'spo': case 'war':
699 $val = $this->exifMsg(
705 case 'SubjectNewsCode':
706 // Essentially like iimCategory.
707 // 8 (numeric) digit hierarchical
708 // classification. We decode the
709 // first 2 digits, which provide
711 $val = $this->convertNewsCode( $val );
714 // 1-8 with 1 being highest, 5 normal
715 // 0 is reserved, and 9 is 'user-defined'.
717 if ( $val == 0 ||
$val == 9 ) {
719 } elseif ( $val < 5 && $val > 1 ) {
721 } elseif ( $val == 5 ) {
723 } elseif ( $val <= 8 && $val > 5 ) {
727 if ( $urgency !== '' ) {
728 $val = $this->exifMsg( 'urgency',
734 // Things that have a unit of pixels.
735 case 'OriginalImageHeight':
736 case 'OriginalImageWidth':
737 case 'PixelXDimension':
738 case 'PixelYDimension':
741 $val = $this->formatNum( $val ) . ' ' . $this->msg( 'unit-pixel' )->text();
744 // Do not transform fields with pure text.
745 // For some languages the formatNum()
746 // conversion results to wrong output like
747 // foo,bar@example,com or foo٫bar@example٫com.
748 // Also some 'numeric' things like Scene codes
749 // are included here as we really don't want
751 case 'ImageDescription':
754 case 'RelatedSoundFile':
755 case 'ImageUniqueID':
756 case 'SpectralSensitivity':
757 case 'GPSSatellites':
761 case 'WorldRegionDest':
763 case 'CountryCodeDest':
764 case 'ProvinceOrStateDest':
766 case 'SublocationDest':
767 case 'WorldRegionCreated':
768 case 'CountryCreated':
769 case 'CountryCodeCreated':
770 case 'ProvinceOrStateCreated':
772 case 'SublocationCreated':
774 case 'SpecialInstructions':
779 case 'FixtureIdentifier':
781 case 'LocationDestCode':
783 case 'JPEGFileComment':
784 case 'iimSupplementalCategory':
785 case 'OriginalTransmissionRef':
787 case 'dc-contributor':
796 case 'CameraOwnerName':
799 case 'RightsCertificate':
800 case 'CopyrightOwner':
803 case 'OriginalDocumentID':
805 case 'MorePermissionsUrl':
806 case 'AttributionUrl':
807 case 'PreferredAttributionName':
808 case 'PNGFileComment':
810 case 'ContentWarning':
811 case 'GIFFileComment':
813 case 'IntellectualGenre':
815 case 'OrginisationInImage':
816 case 'PersonInImage':
818 $val = htmlspecialchars( $val );
823 case 'a': case 'p': case 'b':
824 $val = $this->exifMsg( $tag, $val );
827 $val = htmlspecialchars( $val );
833 case 'True': case 'False':
834 $val = $this->exifMsg( $tag, $val );
839 if ( $val == '-1' ) {
840 $val = $this->exifMsg( $tag, 'rejected' );
842 $val = $this->formatNum( $val );
847 $lang = Language
::fetchLanguageName( strtolower( $val ), $this->getLanguage()->getCode() );
849 $val = htmlspecialchars( $lang );
851 $val = htmlspecialchars( $val );
856 $val = $this->formatNum( $val );
860 // End formatting values, start flattening arrays.
861 $vals = $this->flattenArrayReal( $vals, $type );
868 * Flatten an array, using the content language for any messages.
870 * @param array $vals array of values
871 * @param string $type Type of array (either lang, ul, ol).
872 * lang = language assoc array with keys being the lang code
873 * ul = unordered list, ol = ordered list
874 * type can also come from the '_type' member of $vals.
875 * @param $noHtml Boolean If to avoid returning anything resembling
876 * html. (Ugly hack for backwards compatibility with old mediawiki).
877 * @param IContextSource $context
878 * @return String single value (in wiki-syntax).
881 public static function flattenArrayContentLang( $vals, $type = 'ul', $noHtml = false, $context = false ) {
883 $obj = new FormatMetadata
;
885 $obj->setContext( $context );
887 $context = new DerivativeContext( $obj->getContext() );
888 $context->setLanguage( $wgContLang );
889 $obj->setContext( $context );
890 return $obj->flattenArrayReal( $vals, $type, $noHtml );
894 * Flatten an array, using the user language for any messages.
896 * @param array $vals array of values
897 * @param string $type Type of array (either lang, ul, ol).
898 * lang = language assoc array with keys being the lang code
899 * ul = unordered list, ol = ordered list
900 * type can also come from the '_type' member of $vals.
901 * @param $noHtml Boolean If to avoid returning anything resembling
902 * html. (Ugly hack for backwards compatibility with old mediawiki).
903 * @param IContextSource $context
904 * @return String single value (in wiki-syntax).
906 public static function flattenArray( $vals, $type = 'ul', $noHtml = false, $context = false ) {
907 $obj = new FormatMetadata
;
909 $obj->setContext( $context );
911 return $obj->flattenArrayReal( $vals, $type, $noHtml );
915 * A function to collapse multivalued tags into a single value.
916 * This turns an array of (for example) authors into a bulleted list.
918 * This is public on the basis it might be useful outside of this class.
920 * @param array $vals array of values
921 * @param string $type Type of array (either lang, ul, ol).
922 * lang = language assoc array with keys being the lang code
923 * ul = unordered list, ol = ordered list
924 * type can also come from the '_type' member of $vals.
925 * @param $noHtml Boolean If to avoid returning anything resembling
926 * html. (Ugly hack for backwards compatibility with old mediawiki).
927 * @return String single value (in wiki-syntax).
930 public function flattenArrayReal( $vals, $type = 'ul', $noHtml = false ) {
931 if ( !is_array( $vals ) ) {
932 return $vals; // do nothing if not an array;
935 if ( isset( $vals['_type'] ) ) {
936 $type = $vals['_type'];
937 unset( $vals['_type'] );
940 if ( !is_array( $vals ) ) {
941 return $vals; // do nothing if not an array;
943 elseif ( count( $vals ) === 1 && $type !== 'lang' ) {
946 elseif ( count( $vals ) === 0 ) {
947 wfDebug( __METHOD__
. " metadata array with 0 elements!\n" );
948 return ""; // paranoia. This should never happen
950 /* @todo FIXME: This should hide some of the list entries if there are
951 * say more than four. Especially if a field is translated into 20
952 * languages, we don't want to show them all by default
957 // Display default, followed by ContLang,
958 // followed by the rest in no particular
961 // Todo: hide some items if really long list.
965 $priorityLanguages = $this->getPriorityLanguages();
966 $defaultItem = false;
967 $defaultLang = false;
969 // If default is set, save it for later,
970 // as we don't know if it's equal to
971 // one of the lang codes. (In xmp
972 // you specify the language for a
973 // default property by having both
974 // a default prop, and one in the language
975 // that are identical)
976 if ( isset( $vals['x-default'] ) ) {
977 $defaultItem = $vals['x-default'];
978 unset( $vals['x-default'] );
980 foreach ( $priorityLanguages as $pLang ) {
981 if ( isset( $vals[$pLang] ) ) {
983 if ( $vals[$pLang] === $defaultItem ) {
984 $defaultItem = false;
987 $content .= $this->langItem(
988 $vals[$pLang], $pLang,
989 $isDefault, $noHtml );
991 unset( $vals[$pLang] );
993 if ( $this->singleLang
) {
994 return Html
::rawElement( 'span',
995 array( 'lang' => $pLang ), $vals[$pLang] );
1001 foreach ( $vals as $lang => $item ) {
1002 if ( $item === $defaultItem ) {
1003 $defaultLang = $lang;
1006 $content .= $this->langItem( $item,
1007 $lang, false, $noHtml );
1008 if ( $this->singleLang
) {
1009 return Html
::rawElement( 'span',
1010 array( 'lang' => $lang ), $item );
1013 if ( $defaultItem !== false ) {
1014 $content = $this->langItem( $defaultItem,
1015 $defaultLang, true, $noHtml ) .
1017 if ( $this->singleLang
) {
1018 return $defaultItem;
1024 return '<ul class="metadata-langlist">' .
1029 return "\n#" . implode( "\n#", $vals );
1031 return "<ol><li>" . implode( "</li>\n<li>", $vals ) . '</li></ol>';
1035 return "\n*" . implode( "\n*", $vals );
1037 return "<ul><li>" . implode( "</li>\n<li>", $vals ) . '</li></ul>';
1042 /** Helper function for creating lists of translations.
1044 * @param string $value value (this is not escaped)
1045 * @param string $lang lang code of item or false
1046 * @param $default Boolean if it is default value.
1047 * @param $noHtml Boolean If to avoid html (for back-compat)
1048 * @throws MWException
1049 * @return string language item (Note: despite how this looks,
1050 * this is treated as wikitext not html).
1052 private function langItem( $value, $lang, $default = false, $noHtml = false ) {
1053 if ( $lang === false && $default === false ) {
1054 throw new MWException( '$lang and $default cannot both '
1059 $wrappedValue = $value;
1061 $wrappedValue = '<span class="mw-metadata-lang-value">'
1062 . $value . '</span>';
1065 if ( $lang === false ) {
1066 $msg = $this->msg( 'metadata-langitem-default', $wrappedValue );
1068 return $msg->text() . "\n\n";
1070 return '<li class="mw-metadata-lang-default">'
1075 $lowLang = strtolower( $lang );
1076 $langName = Language
::fetchLanguageName( $lowLang );
1077 if ( $langName === '' ) {
1078 //try just the base language name. (aka en-US -> en ).
1079 list( $langPrefix ) = explode( '-', $lowLang, 2 );
1080 $langName = Language
::fetchLanguageName( $langPrefix );
1081 if ( $langName === '' ) {
1086 // else we have a language specified
1088 $msg = $this->msg( 'metadata-langitem', $wrappedValue, $langName, $lang );
1090 return '*' . $msg->text();
1093 $item = '<li class="mw-metadata-lang-code-'
1096 $item .= ' mw-metadata-lang-default';
1098 $item .= '" lang="' . $lang . '">';
1099 $item .= $msg->text();
1105 * Convenience function for getFormattedData()
1109 * @param string $tag the tag name to pass on
1110 * @param string $val the value of the tag
1111 * @param string $arg an argument to pass ($1)
1112 * @param string $arg2 a 2nd argument to pass ($2)
1113 * @return string The text content of "exif-$tag-$val" message in lower case
1115 private function exifMsg( $tag, $val, $arg = null, $arg2 = null ) {
1118 if ( $val === '' ) {
1121 return $this->msg( $wgContLang->lc( "exif-$tag-$val" ), $arg, $arg2 )->text();
1125 * Format a number, convert numbers from fractions into floating point
1126 * numbers, joins arrays of numbers with commas.
1128 * @param $num Mixed: the value to format
1129 * @param $round float|int|bool digits to round to or false.
1130 * @return mixed A floating point number or whatever we were fed
1132 private function formatNum( $num, $round = false ) {
1134 if ( is_array( $num ) ) {
1136 foreach ( $num as $number ) {
1137 $out[] = $this->formatNum( $number );
1139 return $this->getLanguage()->commaList( $out );
1141 if ( preg_match( '/^(-?\d+)\/(\d+)$/', $num, $m ) ) {
1143 $newNum = $m[1] / $m[2];
1144 if ( $round !== false ) {
1145 $newNum = round( $newNum, $round );
1151 return $this->getLanguage()->formatNum( $newNum );
1153 if ( is_numeric( $num ) && $round !== false ) {
1154 $num = round( $num, $round );
1156 return $this->getLanguage()->formatNum( $num );
1161 * Format a rational number, reducing fractions
1165 * @param $num Mixed: the value to format
1166 * @return mixed A floating point number or whatever we were fed
1168 private function formatFraction( $num ) {
1170 if ( preg_match( '/^(-?\d+)\/(\d+)$/', $num, $m ) ) {
1171 $numerator = intval( $m[1] );
1172 $denominator = intval( $m[2] );
1173 $gcd = $this->gcd( abs( $numerator ), $denominator );
1175 // 0 shouldn't happen! ;)
1176 return $this->formatNum( $numerator / $gcd ) . '/' . $this->formatNum( $denominator / $gcd );
1179 return $this->formatNum( $num );
1183 * Calculate the greatest common divisor of two integers.
1185 * @param $a Integer: Numerator
1186 * @param $b Integer: Denominator
1190 private function gcd( $a, $b ) {
1192 // http://en.wikipedia.org/wiki/Euclidean_algorithm
1193 // Recursive form would be:
1197 return gcd( $b, $a % $b );
1200 $remainder = $a %
$b;
1202 // tail recursion...
1210 * Fetch the human readable version of a news code.
1211 * A news code is an 8 digit code. The first two
1212 * digits are a general classification, so we just
1215 * Note, leading 0's are significant, so this is
1216 * a string, not an int.
1218 * @param string $val The 8 digit news code.
1219 * @return string The human readable form
1221 private function convertNewsCode( $val ) {
1222 if ( !preg_match( '/^\d{8}$/D', $val ) ) {
1223 // Not a valid news code.
1227 switch ( substr( $val, 0, 2 ) ) {
1280 if ( $cat !== '' ) {
1281 $catMsg = $this->exifMsg( 'iimcategory', $cat );
1282 $val = $this->exifMsg( 'subjectnewscode', '', $val, $catMsg );
1288 * Format a coordinate value, convert numbers from floating point
1289 * into degree minute second representation.
1291 * @param int $coord degrees, minutes and seconds
1292 * @param string $type latitude or longitude (for if its a NWS or E)
1293 * @return mixed A floating point number or whatever we were fed
1295 private function formatCoords( $coord, $type ) {
1299 if ( $type === 'latitude' ) {
1301 } elseif ( $type === 'longitude' ) {
1306 if ( $type === 'latitude' ) {
1308 } elseif ( $type === 'longitude' ) {
1313 $deg = floor( $nCoord );
1314 $min = floor( ( $nCoord - $deg ) * 60.0 );
1315 $sec = round( ( ( $nCoord - $deg ) - $min / 60 ) * 3600, 2 );
1317 $deg = $this->formatNum( $deg );
1318 $min = $this->formatNum( $min );
1319 $sec = $this->formatNum( $sec );
1321 return $this->msg( 'exif-coordinate-format', $deg, $min, $sec, $ref, $coord )->text();
1325 * Format the contact info field into a single value.
1327 * @param array $vals array with fields of the ContactInfo
1328 * struct defined in the IPTC4XMP spec. Or potentially
1329 * an array with one element that is a free form text
1330 * value from the older iptc iim 1:118 prop.
1332 * This function might be called from
1333 * JpegHandler::convertMetadataVersion which is why it is
1336 * @return String of html-ish looking wikitext
1337 * @since 1.23 no longer static
1339 public function collapseContactInfo( $vals ) {
1340 if ( !( isset( $vals['CiAdrExtadr'] )
1341 ||
isset( $vals['CiAdrCity'] )
1342 ||
isset( $vals['CiAdrCtry'] )
1343 ||
isset( $vals['CiEmailWork'] )
1344 ||
isset( $vals['CiTelWork'] )
1345 ||
isset( $vals['CiAdrPcode'] )
1346 ||
isset( $vals['CiAdrRegion'] )
1347 ||
isset( $vals['CiUrlWork'] )
1349 // We don't have any sub-properties
1350 // This could happen if its using old
1351 // iptc that just had this as a free-form
1353 // Note: We run this through htmlspecialchars
1354 // partially to be consistent, and partially
1355 // because people often insert >, etc into
1356 // the metadata which should not be interpreted
1357 // but we still want to auto-link urls.
1358 foreach ( $vals as &$val ) {
1359 $val = htmlspecialchars( $val );
1361 return $this->flattenArrayReal( $vals );
1363 // We have a real ContactInfo field.
1364 // Its unclear if all these fields have to be
1365 // set, so assume they do not.
1366 $url = $tel = $street = $city = $country = '';
1367 $email = $postal = $region = '';
1369 // Also note, some of the class names this uses
1370 // are similar to those used by hCard. This is
1371 // mostly because they're sensible names. This
1372 // does not (and does not attempt to) output
1373 // stuff in the hCard microformat. However it
1374 // might output in the adr microformat.
1376 if ( isset( $vals['CiAdrExtadr'] ) ) {
1377 // Todo: This can potentially be multi-line.
1378 // Need to check how that works in XMP.
1379 $street = '<span class="extended-address">'
1381 $vals['CiAdrExtadr'] )
1384 if ( isset( $vals['CiAdrCity'] ) ) {
1385 $city = '<span class="locality">'
1386 . htmlspecialchars( $vals['CiAdrCity'] )
1389 if ( isset( $vals['CiAdrCtry'] ) ) {
1390 $country = '<span class="country-name">'
1391 . htmlspecialchars( $vals['CiAdrCtry'] )
1394 if ( isset( $vals['CiEmailWork'] ) ) {
1396 // Have to split multiple emails at commas/new lines.
1397 $splitEmails = explode( "\n", $vals['CiEmailWork'] );
1398 foreach ( $splitEmails as $e1 ) {
1399 // Also split on comma
1400 foreach ( explode( ',', $e1 ) as $e2 ) {
1401 $finalEmail = trim( $e2 );
1402 if ( $finalEmail == ',' ||
$finalEmail == '' ) {
1405 if ( strpos( $finalEmail, '<' ) !== false ) {
1406 // Don't do fancy formatting to
1407 // "My name" <foo@bar.com> style stuff
1408 $emails[] = $finalEmail;
1410 $emails[] = '[mailto:'
1412 . ' <span class="email">'
1418 $email = implode( ', ', $emails );
1420 if ( isset( $vals['CiTelWork'] ) ) {
1421 $tel = '<span class="tel">'
1422 . htmlspecialchars( $vals['CiTelWork'] )
1425 if ( isset( $vals['CiAdrPcode'] ) ) {
1426 $postal = '<span class="postal-code">'
1428 $vals['CiAdrPcode'] )
1431 if ( isset( $vals['CiAdrRegion'] ) ) {
1432 // Note this is province/state.
1433 $region = '<span class="region">'
1435 $vals['CiAdrRegion'] )
1438 if ( isset( $vals['CiUrlWork'] ) ) {
1439 $url = '<span class="url">'
1440 . htmlspecialchars( $vals['CiUrlWork'] )
1443 return $this->msg( 'exif-contact-value', $email, $url,
1444 $street, $city, $region, $postal, $country,
1450 * Get a list of fields that are visible by default.
1455 public static function getVisibleFields() {
1457 $lines = explode( "\n", wfMessage( 'metadata-fields' )->inContentLanguage()->text() );
1458 foreach ( $lines as $line ) {
1460 if ( preg_match( '/^\\*\s*(.*?)\s*$/', $line, $matches ) ) {
1461 $fields[] = $matches[1];
1464 $fields = array_map( 'strtolower', $fields );
1469 * Get an array of extended metadata. (See the imageinfo API for format.)
1471 * @param File $file File to use
1472 * @return array [<property name> => ['value' => <value>]], or [] on error
1475 public function fetchExtendedMetadata( File
$file ) {
1478 wfProfileIn( __METHOD__
);
1480 // If revision deleted, exit immediately
1481 if ( $file->isDeleted( File
::DELETED_FILE
) ) {
1485 $cacheKey = wfMemcKey(
1486 'getExtendedMetadata',
1487 $this->getLanguage()->getCode(),
1488 (int) $this->singleLang
,
1492 $cachedValue = $wgMemc->get( $cacheKey );
1495 && wfRunHooks( 'ValidateExtendedMetadataCache', array( $cachedValue['timestamp'], $file ) )
1497 $extendedMetadata = $cachedValue['data'];
1499 $maxCacheTime = ( $file instanceof ForeignAPIFile
) ?
60 * 60 * 12 : 60 * 60 * 24 * 30;
1500 $fileMetadata = $this->getExtendedMetadataFromFile( $file );
1501 $extendedMetadata = $this->getExtendedMetadataFromHook( $file, $fileMetadata, $maxCacheTime );
1502 if ( $this->singleLang
) {
1503 $this->resolveMultilangMetadata( $extendedMetadata );
1505 // Make sure the metadata won't break the API when an XML format is used.
1506 // This is an API-specific function so it would be cleaner to call it from
1507 // outside fetchExtendedMetadata, but this way we don't need to redo the
1508 // computation on a cache hit.
1509 $this->sanitizeArrayForXml( $extendedMetadata );
1510 $valueToCache = array( 'data' => $extendedMetadata, 'timestamp' => wfTimestampNow() );
1511 $wgMemc->set( $cacheKey, $valueToCache, $maxCacheTime );
1514 wfProfileOut( __METHOD__
);
1515 return $extendedMetadata;
1519 * Get file-based metadata in standardized format.
1521 * Note that for a remote file, this might return metadata supplied by extensions.
1523 * @param File $file File to use
1524 * @return array [<property name> => ['value' => <value>]], or [] on error
1527 protected function getExtendedMetadataFromFile( File
$file ) {
1528 // If this is a remote file accessed via an API request, we already
1529 // have remote metadata so we just ignore any local one
1530 if ( $file instanceof ForeignAPIFile
) {
1531 // in case of error we pretend no metadata - this will get cached. Might or might not be a good idea.
1532 return $file->getExtendedMetadata() ?
: array();
1535 wfProfileIn( __METHOD__
);
1537 $uploadDate = wfTimestamp( TS_ISO_8601
, $file->getTimestamp() );
1539 $fileMetadata = array(
1540 // This is modification time, which is close to "upload" time.
1541 'DateTime' => array(
1542 'value' => $uploadDate,
1543 'source' => 'mediawiki-metadata',
1547 $title = $file->getTitle();
1549 $text = $title->getText();
1550 $pos = strrpos( $text, '.' );
1553 $name = substr( $text, 0, $pos );
1558 $fileMetadata[ 'ObjectName' ] = array(
1560 'source' => 'mediawiki-metadata',
1564 $common = $file->getCommonMetaArray();
1566 if ( $common !== false ) {
1567 foreach ( $common as $key => $value ) {
1568 $fileMetadata[$key] = array(
1570 'source' => 'file-metadata',
1575 wfProfileOut( __METHOD__
);
1576 return $fileMetadata;
1580 * Get additional metadata from hooks in standardized format.
1582 * @param File $file File to use
1583 * @param array $extendedMetadata
1584 * @param int $maxCacheTime hook handlers might use this parameter to override cache time
1586 * @return array [<property name> => ['value' => <value>]], or [] on error
1589 protected function getExtendedMetadataFromHook( File
$file, array $extendedMetadata, &$maxCacheTime ) {
1590 wfProfileIn( __METHOD__
);
1592 wfRunHooks( 'GetExtendedMetadata', array(
1595 $this->getContext(),
1600 $visible = array_flip( self
::getVisibleFields() );
1601 foreach ( $extendedMetadata as $key => $value ) {
1602 if ( !isset( $visible[ strtolower( $key ) ] ) ) {
1603 $extendedMetadata[$key]['hidden'] = '';
1607 wfProfileOut( __METHOD__
);
1608 return $extendedMetadata;
1612 * Turns an XMP-style multilang array into a single value.
1613 * If the value is not a multilang array, it is returned unchanged.
1614 * See mediawiki.org/wiki/Manual:File_metadata_handling#Multi-language_array_format
1615 * @param mixed $value
1616 * @return mixed value in best language, null if there were no languages at all
1619 protected function resolveMultilangValue( $value )
1623 ||
!isset( $value['_type'] )
1624 ||
$value['_type'] != 'lang'
1626 return $value; // do nothing if not a multilang array
1629 // choose the language best matching user or site settings
1630 $priorityLanguages = $this->getPriorityLanguages();
1631 foreach ( $priorityLanguages as $lang ) {
1632 if ( isset( $value[$lang] ) ) {
1633 return $value[$lang];
1637 // otherwise go with the default language, if set
1638 if ( isset( $value['x-default'] ) ) {
1639 return $value['x-default'];
1642 // otherwise just return any one language
1643 unset( $value['_type'] );
1644 if ( !empty( $value ) ) {
1645 return reset( $value );
1648 // this should not happen; signal error
1653 * Takes an array returned by the getExtendedMetadata* functions,
1654 * and resolves multi-language values in it.
1655 * @param array $metadata
1658 protected function resolveMultilangMetadata( &$metadata ) {
1659 if ( !is_array( $metadata ) ) {
1662 foreach ( $metadata as &$field ) {
1663 if ( isset( $field['value'] ) ) {
1664 $field['value'] = $this->resolveMultilangValue( $field['value'] );
1670 * Makes sure the given array is a valid API response fragment
1671 * (can be transformed into XML)
1674 protected function sanitizeArrayForXml( &$arr ) {
1675 if ( !is_array( $arr ) ) {
1680 foreach ( $arr as $key => &$value ) {
1681 $sanitizedKey = $this->sanitizeKeyForXml( $key );
1682 if ( $sanitizedKey !== $key ) {
1683 if ( isset( $arr[$sanitizedKey] ) ) {
1684 // Make the sanitized keys hopefully unique.
1685 // To make it definitely unique would be too much effort, given that
1686 // sanitizing is only needed for misformatted metadata anyway, but
1687 // this at least covers the case when $arr is numeric.
1688 $sanitizedKey .= $counter;
1691 $arr[$sanitizedKey] = $arr[$key];
1692 unset( $arr[$key] );
1694 if ( is_array( $value ) ) {
1695 $this->sanitizeArrayForXml( $value );
1701 * Turns a string into a valid XML identifier.
1702 * Used to ensure that keys of an associative array in the
1703 * API response do not break the XML formatter.
1704 * @param string $key
1708 protected function sanitizeKeyForXml( $key ) {
1709 // drop all characters which are not valid in an XML tag name
1710 // a bunch of non-ASCII letters would be valid but probably won't
1711 // be used so we take the easy way
1712 $key = preg_replace( '/[^a-zA-z0-9_:.-]/', '', $key );
1713 // drop characters which are invalid at the first position
1714 $key = preg_replace( '/^[\d-.]+/', '', $key );
1720 // special case for an internal keyword
1721 if ( $key == '_element' ) {
1729 * Returns a list of languages (first is best) to use when formatting multilang fields,
1730 * based on user and site preferences.
1734 protected function getPriorityLanguages()
1736 $priorityLanguages = Language
::getFallbacksIncludingSiteLanguage( $this->getLanguage()->getCode() );
1737 $priorityLanguages = array_merge( (array) $this->getLanguage()->getCode(), $priorityLanguages[0], $priorityLanguages[1] );
1738 return $priorityLanguages;
1742 /** For compatability with old FormatExif class
1743 * which some extensions use.
1745 * @deprecated since 1.18
1752 * @param $meta array
1754 function FormatExif( $meta ) {
1755 wfDeprecated( __METHOD__
, '1.18' );
1756 $this->meta
= $meta;
1762 function getFormattedData() {
1763 return FormatMetadata
::getFormattedData( $this->meta
);