Update core usage of getLanguageName[s].
[lhc/web/wiklou.git] / includes / media / FormatMetadata.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @ingroup Media
19 * @author Ævar Arnfjörð Bjarmason <avarab@gmail.com>
20 * @copyright Copyright © 2005, Ævar Arnfjörð Bjarmason, 2009 Brent Garber, 2010 Brian Wolff
21 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
22 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 specification
23 * @file
24 */
25
26
27 /**
28 * Format Image metadata values into a human readable form.
29 *
30 * Note lots of these messages use the prefix 'exif' even though
31 * they may not be exif properties. For example 'exif-ImageDescription'
32 * can be the Exif ImageDescription, or it could be the iptc-iim caption
33 * property, or it could be the xmp dc:description property. This
34 * is because these messages should be independent of how the data is
35 * stored, sine the user doesn't care if the description is stored in xmp,
36 * exif, etc only that its a description. (Additionally many of these properties
37 * are merged together following the MWG standard, such that for example,
38 * exif properties override XMP properties that mean the same thing if
39 * there is a conflict).
40 *
41 * It should perhaps use a prefix like 'metadata' instead, but there
42 * is already a large number of messages using the 'exif' prefix.
43 *
44 * @ingroup Media
45 */
46 class FormatMetadata {
47
48 /**
49 * Numbers given by Exif user agents are often magical, that is they
50 * should be replaced by a detailed explanation depending on their
51 * value which most of the time are plain integers. This function
52 * formats Exif (and other metadata) values into human readable form.
53 *
54 * @param $tags Array: the Exif data to format ( as returned by
55 * Exif::getFilteredData() or BitmapMetadataHandler )
56 * @return array
57 */
58 public static function getFormattedData( $tags ) {
59 global $wgLang;
60
61 $resolutionunit = !isset( $tags['ResolutionUnit'] ) || $tags['ResolutionUnit'] == 2 ? 2 : 3;
62 unset( $tags['ResolutionUnit'] );
63
64 foreach ( $tags as $tag => &$vals ) {
65
66 // This seems ugly to wrap non-array's in an array just to unwrap again,
67 // especially when most of the time it is not an array
68 if ( !is_array( $tags[$tag] ) ) {
69 $vals = Array( $vals );
70 }
71
72 // _type is a special value to say what array type
73 if ( isset( $tags[$tag]['_type'] ) ) {
74 $type = $tags[$tag]['_type'];
75 unset( $vals['_type'] );
76 } else {
77 $type = 'ul'; // default unordered list.
78 }
79
80 //This is done differently as the tag is an array.
81 if ($tag == 'GPSTimeStamp' && count($vals) === 3) {
82 //hour min sec array
83
84 $h = explode('/', $vals[0]);
85 $m = explode('/', $vals[1]);
86 $s = explode('/', $vals[2]);
87
88 // this should already be validated
89 // when loaded from file, but it could
90 // come from a foreign repo, so be
91 // paranoid.
92 if ( !isset($h[1])
93 || !isset($m[1])
94 || !isset($s[1])
95 || $h[1] == 0
96 || $m[1] == 0
97 || $s[1] == 0
98 ) {
99 continue;
100 }
101 $tags[$tag] = intval( $h[0] / $h[1] )
102 . ':' . str_pad( intval( $m[0] / $m[1] ), 2, '0', STR_PAD_LEFT )
103 . ':' . str_pad( intval( $s[0] / $s[1] ), 2, '0', STR_PAD_LEFT );
104
105 $time = wfTimestamp( TS_MW, '1971:01:01 ' . $tags[$tag] );
106 // the 1971:01:01 is just a placeholder, and not shown to user.
107 if ( $time && intval( $time ) > 0 ) {
108 $tags[$tag] = $wgLang->time( $time );
109 }
110 continue;
111 }
112
113 // The contact info is a multi-valued field
114 // instead of the other props which are single
115 // valued (mostly) so handle as a special case.
116 if ( $tag === 'Contact' ) {
117 $vals = self::collapseContactInfo( $vals );
118 continue;
119 }
120
121 foreach ( $vals as &$val ) {
122
123 switch( $tag ) {
124 case 'Compression':
125 switch( $val ) {
126 case 1: case 2: case 3: case 4:
127 case 5: case 6: case 7: case 8:
128 case 32773: case 32946: case 34712:
129 $val = self::msg( $tag, $val );
130 break;
131 default:
132 /* If not recognized, display as is. */
133 break;
134 }
135 break;
136
137 case 'PhotometricInterpretation':
138 switch( $val ) {
139 case 2: case 6:
140 $val = self::msg( $tag, $val );
141 break;
142 default:
143 /* If not recognized, display as is. */
144 break;
145 }
146 break;
147
148 case 'Orientation':
149 switch( $val ) {
150 case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8:
151 $val = self::msg( $tag, $val );
152 break;
153 default:
154 /* If not recognized, display as is. */
155 break;
156 }
157 break;
158
159 case 'PlanarConfiguration':
160 switch( $val ) {
161 case 1: case 2:
162 $val = self::msg( $tag, $val );
163 break;
164 default:
165 /* If not recognized, display as is. */
166 break;
167 }
168 break;
169
170 // TODO: YCbCrSubSampling
171 case 'YCbCrPositioning':
172 switch ( $val ) {
173 case 1:
174 case 2:
175 $val = self::msg( $tag, $val );
176 break;
177 default:
178 /* If not recognized, display as is. */
179 break;
180 }
181 break;
182
183 case 'XResolution':
184 case 'YResolution':
185 switch( $resolutionunit ) {
186 case 2:
187 $val = self::msg( 'XYResolution', 'i', self::formatNum( $val ) );
188 break;
189 case 3:
190 $val = self::msg( 'XYResolution', 'c', self::formatNum( $val ) );
191 break;
192 default:
193 /* If not recognized, display as is. */
194 break;
195 }
196 break;
197
198 // TODO: YCbCrCoefficients #p27 (see annex E)
199 case 'ExifVersion': case 'FlashpixVersion':
200 $val = "$val" / 100;
201 break;
202
203 case 'ColorSpace':
204 switch( $val ) {
205 case 1: case 65535:
206 $val = self::msg( $tag, $val );
207 break;
208 default:
209 /* If not recognized, display as is. */
210 break;
211 }
212 break;
213
214 case 'ComponentsConfiguration':
215 switch( $val ) {
216 case 0: case 1: case 2: case 3: case 4: case 5: case 6:
217 $val = self::msg( $tag, $val );
218 break;
219 default:
220 /* If not recognized, display as is. */
221 break;
222 }
223 break;
224
225 case 'DateTime':
226 case 'DateTimeOriginal':
227 case 'DateTimeDigitized':
228 case 'DateTimeReleased':
229 case 'DateTimeExpires':
230 case 'GPSDateStamp':
231 case 'dc-date':
232 case 'DateTimeMetadata':
233 if ( $val == '0000:00:00 00:00:00' || $val == ' : : : : ' ) {
234 $val = wfMsg( 'exif-unknowndate' );
235 } elseif ( preg_match( '/^(?:\d{4}):(?:\d\d):(?:\d\d) (?:\d\d):(?:\d\d):(?:\d\d)$/D', $val ) ) {
236 // Full date.
237 $time = wfTimestamp( TS_MW, $val );
238 if ( $time && intval( $time ) > 0 ) {
239 $val = $wgLang->timeanddate( $time );
240 }
241 } elseif ( preg_match( '/^(?:\d{4}):(?:\d\d):(?:\d\d) (?:\d\d):(?:\d\d)$/D', $val ) ) {
242 // No second field. Still format the same
243 // since timeanddate doesn't include seconds anyways,
244 // but second still available in api
245 $time = wfTimestamp( TS_MW, $val . ':00' );
246 if ( $time && intval( $time ) > 0 ) {
247 $val = $wgLang->timeanddate( $time );
248 }
249 } elseif ( preg_match( '/^(?:\d{4}):(?:\d\d):(?:\d\d)$/D', $val ) ) {
250 // If only the date but not the time is filled in.
251 $time = wfTimestamp( TS_MW, substr( $val, 0, 4 )
252 . substr( $val, 5, 2 )
253 . substr( $val, 8, 2 )
254 . '000000' );
255 if ( $time && intval( $time ) > 0 ) {
256 $val = $wgLang->date( $time );
257 }
258 }
259 // else it will just output $val without formatting it.
260 break;
261
262 case 'ExposureProgram':
263 switch( $val ) {
264 case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8:
265 $val = self::msg( $tag, $val );
266 break;
267 default:
268 /* If not recognized, display as is. */
269 break;
270 }
271 break;
272
273 case 'SubjectDistance':
274 $val = self::msg( $tag, '', self::formatNum( $val ) );
275 break;
276
277 case 'MeteringMode':
278 switch( $val ) {
279 case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 255:
280 $val = self::msg( $tag, $val );
281 break;
282 default:
283 /* If not recognized, display as is. */
284 break;
285 }
286 break;
287
288 case 'LightSource':
289 switch( $val ) {
290 case 0: case 1: case 2: case 3: case 4: case 9: case 10: case 11:
291 case 12: case 13: case 14: case 15: case 17: case 18: case 19: case 20:
292 case 21: case 22: case 23: case 24: case 255:
293 $val = self::msg( $tag, $val );
294 break;
295 default:
296 /* If not recognized, display as is. */
297 break;
298 }
299 break;
300
301 case 'Flash':
302 $flashDecode = array(
303 'fired' => $val & bindec( '00000001' ),
304 'return' => ( $val & bindec( '00000110' ) ) >> 1,
305 'mode' => ( $val & bindec( '00011000' ) ) >> 3,
306 'function' => ( $val & bindec( '00100000' ) ) >> 5,
307 'redeye' => ( $val & bindec( '01000000' ) ) >> 6,
308 // 'reserved' => ($val & bindec( '10000000' )) >> 7,
309 );
310
311 # We do not need to handle unknown values since all are used.
312 foreach ( $flashDecode as $subTag => $subValue ) {
313 # We do not need any message for zeroed values.
314 if ( $subTag != 'fired' && $subValue == 0 ) {
315 continue;
316 }
317 $fullTag = $tag . '-' . $subTag ;
318 $flashMsgs[] = self::msg( $fullTag, $subValue );
319 }
320 $val = $wgLang->commaList( $flashMsgs );
321 break;
322
323 case 'FocalPlaneResolutionUnit':
324 switch( $val ) {
325 case 2:
326 $val = self::msg( $tag, $val );
327 break;
328 default:
329 /* If not recognized, display as is. */
330 break;
331 }
332 break;
333
334 case 'SensingMethod':
335 switch( $val ) {
336 case 1: case 2: case 3: case 4: case 5: case 7: case 8:
337 $val = self::msg( $tag, $val );
338 break;
339 default:
340 /* If not recognized, display as is. */
341 break;
342 }
343 break;
344
345 case 'FileSource':
346 switch( $val ) {
347 case 3:
348 $val = self::msg( $tag, $val );
349 break;
350 default:
351 /* If not recognized, display as is. */
352 break;
353 }
354 break;
355
356 case 'SceneType':
357 switch( $val ) {
358 case 1:
359 $val = self::msg( $tag, $val );
360 break;
361 default:
362 /* If not recognized, display as is. */
363 break;
364 }
365 break;
366
367 case 'CustomRendered':
368 switch( $val ) {
369 case 0: case 1:
370 $val = self::msg( $tag, $val );
371 break;
372 default:
373 /* If not recognized, display as is. */
374 break;
375 }
376 break;
377
378 case 'ExposureMode':
379 switch( $val ) {
380 case 0: case 1: case 2:
381 $val = self::msg( $tag, $val );
382 break;
383 default:
384 /* If not recognized, display as is. */
385 break;
386 }
387 break;
388
389 case 'WhiteBalance':
390 switch( $val ) {
391 case 0: case 1:
392 $val = self::msg( $tag, $val );
393 break;
394 default:
395 /* If not recognized, display as is. */
396 break;
397 }
398 break;
399
400 case 'SceneCaptureType':
401 switch( $val ) {
402 case 0: case 1: case 2: case 3:
403 $val = self::msg( $tag, $val );
404 break;
405 default:
406 /* If not recognized, display as is. */
407 break;
408 }
409 break;
410
411 case 'GainControl':
412 switch( $val ) {
413 case 0: case 1: case 2: case 3: case 4:
414 $val = self::msg( $tag, $val );
415 break;
416 default:
417 /* If not recognized, display as is. */
418 break;
419 }
420 break;
421
422 case 'Contrast':
423 switch( $val ) {
424 case 0: case 1: case 2:
425 $val = self::msg( $tag, $val );
426 break;
427 default:
428 /* If not recognized, display as is. */
429 break;
430 }
431 break;
432
433 case 'Saturation':
434 switch( $val ) {
435 case 0: case 1: case 2:
436 $val = self::msg( $tag, $val );
437 break;
438 default:
439 /* If not recognized, display as is. */
440 break;
441 }
442 break;
443
444 case 'Sharpness':
445 switch( $val ) {
446 case 0: case 1: case 2:
447 $val = self::msg( $tag, $val );
448 break;
449 default:
450 /* If not recognized, display as is. */
451 break;
452 }
453 break;
454
455 case 'SubjectDistanceRange':
456 switch( $val ) {
457 case 0: case 1: case 2: case 3:
458 $val = self::msg( $tag, $val );
459 break;
460 default:
461 /* If not recognized, display as is. */
462 break;
463 }
464 break;
465
466 //The GPS...Ref values are kept for compatibility, probably won't be reached.
467 case 'GPSLatitudeRef':
468 case 'GPSDestLatitudeRef':
469 switch( $val ) {
470 case 'N': case 'S':
471 $val = self::msg( 'GPSLatitude', $val );
472 break;
473 default:
474 /* If not recognized, display as is. */
475 break;
476 }
477 break;
478
479 case 'GPSLongitudeRef':
480 case 'GPSDestLongitudeRef':
481 switch( $val ) {
482 case 'E': case 'W':
483 $val = self::msg( 'GPSLongitude', $val );
484 break;
485 default:
486 /* If not recognized, display as is. */
487 break;
488 }
489 break;
490
491 case 'GPSAltitude':
492 if ( $val < 0 ) {
493 $val = self::msg( 'GPSAltitude', 'below-sealevel', self::formatNum( -$val, 3 ) );
494 } else {
495 $val = self::msg( 'GPSAltitude', 'above-sealevel', self::formatNum( $val, 3 ) );
496 }
497 break;
498
499 case 'GPSStatus':
500 switch( $val ) {
501 case 'A': case 'V':
502 $val = self::msg( $tag, $val );
503 break;
504 default:
505 /* If not recognized, display as is. */
506 break;
507 }
508 break;
509
510 case 'GPSMeasureMode':
511 switch( $val ) {
512 case 2: case 3:
513 $val = self::msg( $tag, $val );
514 break;
515 default:
516 /* If not recognized, display as is. */
517 break;
518 }
519 break;
520
521
522 case 'GPSTrackRef':
523 case 'GPSImgDirectionRef':
524 case 'GPSDestBearingRef':
525 switch( $val ) {
526 case 'T': case 'M':
527 $val = self::msg( 'GPSDirection', $val );
528 break;
529 default:
530 /* If not recognized, display as is. */
531 break;
532 }
533 break;
534
535 case 'GPSLatitude':
536 case 'GPSDestLatitude':
537 $val = self::formatCoords( $val, 'latitude' );
538 break;
539 case 'GPSLongitude':
540 case 'GPSDestLongitude':
541 $val = self::formatCoords( $val, 'longitude' );
542 break;
543
544 case 'GPSSpeedRef':
545 switch( $val ) {
546 case 'K': case 'M': case 'N':
547 $val = self::msg( 'GPSSpeed', $val );
548 break;
549 default:
550 /* If not recognized, display as is. */
551 break;
552 }
553 break;
554
555 case 'GPSDestDistanceRef':
556 switch( $val ) {
557 case 'K': case 'M': case 'N':
558 $val = self::msg( 'GPSDestDistance', $val );
559 break;
560 default:
561 /* If not recognized, display as is. */
562 break;
563 }
564 break;
565
566 case 'GPSDOP':
567 // See http://en.wikipedia.org/wiki/Dilution_of_precision_(GPS)
568 if ( $val <= 2 ) {
569 $val = self::msg( $tag, 'excellent', self::formatNum( $val ) );
570 } elseif ( $val <= 5 ) {
571 $val = self::msg( $tag, 'good', self::formatNum( $val ) );
572 } elseif ( $val <= 10 ) {
573 $val = self::msg( $tag, 'moderate', self::formatNum( $val ) );
574 } elseif ( $val <= 20 ) {
575 $val = self::msg( $tag, 'fair', self::formatNum( $val ) );
576 } else {
577 $val = self::msg( $tag, 'poor', self::formatNum( $val ) );
578 }
579 break;
580
581 // This is not in the Exif standard, just a special
582 // case for our purposes which enables wikis to wikify
583 // the make, model and software name to link to their articles.
584 case 'Make':
585 case 'Model':
586 $val = self::msg( $tag, '', $val );
587 break;
588
589 case 'Software':
590 if ( is_array( $val ) ) {
591 //if its a software, version array.
592 $val = wfMsg( 'exif-software-version-value', $val[0], $val[1] );
593 } else {
594 $val = self::msg( $tag, '', $val );
595 }
596 break;
597
598 case 'ExposureTime':
599 // Show the pretty fraction as well as decimal version
600 $val = wfMsg( 'exif-exposuretime-format',
601 self::formatFraction( $val ), self::formatNum( $val ) );
602 break;
603 case 'ISOSpeedRatings':
604 // If its = 65535 that means its at the
605 // limit of the size of Exif::short and
606 // is really higher.
607 if ( $val == '65535' ) {
608 $val = self::msg( $tag, 'overflow' );
609 } else {
610 $val = self::formatNum( $val );
611 }
612 break;
613 case 'FNumber':
614 $val = wfMsg( 'exif-fnumber-format',
615 self::formatNum( $val ) );
616 break;
617
618 case 'FocalLength': case 'FocalLengthIn35mmFilm':
619 $val = wfMsg( 'exif-focallength-format',
620 self::formatNum( $val ) );
621 break;
622
623 case 'MaxApertureValue':
624 if ( strpos( $val, '/' ) !== false ) {
625 // need to expand this earlier to calculate fNumber
626 list($n, $d) = explode('/', $val);
627 if ( is_numeric( $n ) && is_numeric( $d ) ) {
628 $val = $n / $d;
629 }
630 }
631 if ( is_numeric( $val ) ) {
632 $fNumber = pow( 2, $val / 2 );
633 if ( $fNumber !== false ) {
634 $val = wfMsg( 'exif-maxaperturevalue-value',
635 self::formatNum( $val ),
636 self::formatNum( $fNumber, 2 )
637 );
638 }
639 }
640 break;
641
642 case 'iimCategory':
643 switch( strtolower( $val ) ) {
644 // See pg 29 of IPTC photo
645 // metadata standard.
646 case 'ace': case 'clj':
647 case 'dis': case 'fin':
648 case 'edu': case 'evn':
649 case 'hth': case 'hum':
650 case 'lab': case 'lif':
651 case 'pol': case 'rel':
652 case 'sci': case 'soi':
653 case 'spo': case 'war':
654 case 'wea':
655 $val = self::msg(
656 'iimcategory',
657 $val
658 );
659 }
660 break;
661 case 'SubjectNewsCode':
662 // Essentially like iimCategory.
663 // 8 (numeric) digit hierarchical
664 // classification. We decode the
665 // first 2 digits, which provide
666 // a broad category.
667 $val = self::convertNewsCode( $val );
668 break;
669 case 'Urgency':
670 // 1-8 with 1 being highest, 5 normal
671 // 0 is reserved, and 9 is 'user-defined'.
672 $urgency = '';
673 if ( $val == 0 || $val == 9 ) {
674 $urgency = 'other';
675 } elseif ( $val < 5 && $val > 1 ) {
676 $urgency = 'high';
677 } elseif ( $val == 5 ) {
678 $urgency = 'normal';
679 } elseif ( $val <= 8 && $val > 5) {
680 $urgency = 'low';
681 }
682
683 if ( $urgency !== '' ) {
684 $val = self::msg( 'urgency',
685 $urgency, $val
686 );
687 }
688 break;
689
690 // Things that have a unit of pixels.
691 case 'OriginalImageHeight':
692 case 'OriginalImageWidth':
693 case 'PixelXDimension':
694 case 'PixelYDimension':
695 case 'ImageWidth':
696 case 'ImageLength':
697 $val = self::formatNum( $val ) . ' ' . wfMsg( 'unit-pixel' );
698 break;
699
700 // Do not transform fields with pure text.
701 // For some languages the formatNum()
702 // conversion results to wrong output like
703 // foo,bar@example,com or foo٫bar@example٫com.
704 // Also some 'numeric' things like Scene codes
705 // are included here as we really don't want
706 // commas inserted.
707 case 'ImageDescription':
708 case 'Artist':
709 case 'Copyright':
710 case 'RelatedSoundFile':
711 case 'ImageUniqueID':
712 case 'SpectralSensitivity':
713 case 'GPSSatellites':
714 case 'GPSVersionID':
715 case 'GPSMapDatum':
716 case 'Keywords':
717 case 'WorldRegionDest':
718 case 'CountryDest':
719 case 'CountryCodeDest':
720 case 'ProvinceOrStateDest':
721 case 'CityDest':
722 case 'SublocationDest':
723 case 'WorldRegionCreated':
724 case 'CountryCreated':
725 case 'CountryCodeCreated':
726 case 'ProvinceOrStateCreated':
727 case 'CityCreated':
728 case 'SublocationCreated':
729 case 'ObjectName':
730 case 'SpecialInstructions':
731 case 'Headline':
732 case 'Credit':
733 case 'Source':
734 case 'EditStatus':
735 case 'FixtureIdentifier':
736 case 'LocationDest':
737 case 'LocationDestCode':
738 case 'Writer':
739 case 'JPEGFileComment':
740 case 'iimSupplementalCategory':
741 case 'OriginalTransmissionRef':
742 case 'Identifier':
743 case 'dc-contributor':
744 case 'dc-coverage':
745 case 'dc-publisher':
746 case 'dc-relation':
747 case 'dc-rights':
748 case 'dc-source':
749 case 'dc-type':
750 case 'Lens':
751 case 'SerialNumber':
752 case 'CameraOwnerName':
753 case 'Label':
754 case 'Nickname':
755 case 'RightsCertificate':
756 case 'CopyrightOwner':
757 case 'UsageTerms':
758 case 'WebStatement':
759 case 'OriginalDocumentID':
760 case 'LicenseUrl':
761 case 'MorePermissionsUrl':
762 case 'AttributionUrl':
763 case 'PreferredAttributionName':
764 case 'PNGFileComment':
765 case 'Disclaimer':
766 case 'ContentWarning':
767 case 'GIFFileComment':
768 case 'SceneCode':
769 case 'IntellectualGenre':
770 case 'Event':
771 case 'OrginisationInImage':
772 case 'PersonInImage':
773
774 $val = htmlspecialchars( $val );
775 break;
776
777 case 'ObjectCycle':
778 switch ( $val ) {
779 case 'a': case 'p': case 'b':
780 $val = self::msg( $tag, $val );
781 break;
782 default:
783 $val = htmlspecialchars( $val );
784 break;
785 }
786 break;
787 case 'Copyrighted':
788 switch( $val ) {
789 case 'True': case 'False':
790 $val = self::msg( $tag, $val );
791 break;
792 }
793 break;
794 case 'Rating':
795 if ( $val == '-1' ) {
796 $val = self::msg( $tag, 'rejected' );
797 } else {
798 $val = self::formatNum( $val );
799 }
800 break;
801
802 case 'LanguageCode':
803 $lang = Language::fetchLanguageName( strtolower( $val ), $wgLang );
804 if ($lang) {
805 $val = htmlspecialchars( $lang );
806 } else {
807 $val = htmlspecialchars( $val );
808 }
809 break;
810
811 default:
812 $val = self::formatNum( $val );
813 break;
814 }
815 }
816 // End formatting values, start flattening arrays.
817 $vals = self::flattenArray( $vals, $type );
818
819 }
820 return $tags;
821 }
822
823 /**
824 * A function to collapse multivalued tags into a single value.
825 * This turns an array of (for example) authors into a bulleted list.
826 *
827 * This is public on the basis it might be useful outside of this class.
828 *
829 * @param $vals Array array of values
830 * @param $type String Type of array (either lang, ul, ol).
831 * lang = language assoc array with keys being the lang code
832 * ul = unordered list, ol = ordered list
833 * type can also come from the '_type' member of $vals.
834 * @param $noHtml Boolean If to avoid returning anything resembling
835 * html. (Ugly hack for backwards compatibility with old mediawiki).
836 * @return String single value (in wiki-syntax).
837 */
838 public static function flattenArray( $vals, $type = 'ul', $noHtml = false ) {
839 if ( isset( $vals['_type'] ) ) {
840 $type = $vals['_type'];
841 unset( $vals['_type'] );
842 }
843
844 if ( !is_array( $vals ) ) {
845 return $vals; // do nothing if not an array;
846 }
847 elseif ( count( $vals ) === 1 && $type !== 'lang' ) {
848 return $vals[0];
849 }
850 elseif ( count( $vals ) === 0 ) {
851 wfDebug( __METHOD__ . ' metadata array with 0 elements!' );
852 return ""; // paranoia. This should never happen
853 }
854 /* @todo FIXME: This should hide some of the list entries if there are
855 * say more than four. Especially if a field is translated into 20
856 * languages, we don't want to show them all by default
857 */
858 else {
859 global $wgContLang;
860 switch( $type ) {
861 case 'lang':
862 // Display default, followed by ContLang,
863 // followed by the rest in no particular
864 // order.
865
866 // Todo: hide some items if really long list.
867
868 $content = '';
869
870 $cLang = $wgContLang->getCode();
871 $defaultItem = false;
872 $defaultLang = false;
873
874 // If default is set, save it for later,
875 // as we don't know if it's equal to
876 // one of the lang codes. (In xmp
877 // you specify the language for a
878 // default property by having both
879 // a default prop, and one in the language
880 // that are identical)
881 if ( isset( $vals['x-default'] ) ) {
882 $defaultItem = $vals['x-default'];
883 unset( $vals['x-default'] );
884 }
885 // Do contentLanguage.
886 if ( isset( $vals[$cLang] ) ) {
887 $isDefault = false;
888 if ( $vals[$cLang] === $defaultItem ) {
889 $defaultItem = false;
890 $isDefault = true;
891 }
892 $content .= self::langItem(
893 $vals[$cLang], $cLang,
894 $isDefault, $noHtml );
895
896 unset( $vals[$cLang] );
897 }
898
899 // Now do the rest.
900 foreach ( $vals as $lang => $item ) {
901 if ( $item === $defaultItem ) {
902 $defaultLang = $lang;
903 continue;
904 }
905 $content .= self::langItem( $item,
906 $lang, false, $noHtml );
907 }
908 if ( $defaultItem !== false ) {
909 $content = self::langItem( $defaultItem,
910 $defaultLang, true, $noHtml )
911 . $content;
912 }
913 if ( $noHtml ) {
914 return $content;
915 }
916 return '<ul class="metadata-langlist">' .
917 $content .
918 '</ul>';
919 case 'ol':
920 if ( $noHtml ) {
921 return "\n#" . implode( "\n#", $vals );
922 }
923 return "<ol><li>" . implode( "</li>\n<li>", $vals ) . '</li></ol>';
924 case 'ul':
925 default:
926 if ( $noHtml ) {
927 return "\n*" . implode( "\n*", $vals );
928 }
929 return "<ul><li>" . implode( "</li>\n<li>", $vals ) . '</li></ul>';
930 }
931 }
932 }
933
934 /** Helper function for creating lists of translations.
935 *
936 * @param $value String value (this is not escaped)
937 * @param $lang String lang code of item or false
938 * @param $default Boolean if it is default value.
939 * @param $noHtml Boolean If to avoid html (for back-compat)
940 * @return language item (Note: despite how this looks,
941 * this is treated as wikitext not html).
942 */
943 private static function langItem( $value, $lang, $default = false, $noHtml = false ) {
944 if ( $lang === false && $default === false) {
945 throw new MWException('$lang and $default cannot both '
946 . 'be false.');
947 }
948
949 if ( $noHtml ) {
950 $wrappedValue = $value;
951 } else {
952 $wrappedValue = '<span class="mw-metadata-lang-value">'
953 . $value . '</span>';
954 }
955
956 if ( $lang === false ) {
957 if ( $noHtml ) {
958 return wfMsg( 'metadata-langitem-default',
959 $wrappedValue ) . "\n\n";
960 } /* else */
961 return '<li class="mw-metadata-lang-default">'
962 . wfMsg( 'metadata-langitem-default',
963 $wrappedValue )
964 . "</li>\n";
965 }
966
967 $lowLang = strtolower( $lang );
968 $langName = Language::fetchLanguageName( $lowLang );
969 if ( $langName === '' ) {
970 //try just the base language name. (aka en-US -> en ).
971 list( $langPrefix ) = explode( '-', $lowLang, 2 );
972 $langName = Language::fetchLanguageName( $langPrefix );
973 if ( $langName === '' ) {
974 // give up.
975 $langName = $lang;
976 }
977 }
978 // else we have a language specified
979
980 if ( $noHtml ) {
981 return '*' . wfMsg( 'metadata-langitem',
982 $wrappedValue, $langName, $lang );
983 } /* else: */
984
985 $item = '<li class="mw-metadata-lang-code-'
986 . $lang;
987 if ( $default ) {
988 $item .= ' mw-metadata-lang-default';
989 }
990 $item .= '" lang="' . $lang . '">';
991 $item .= wfMsg( 'metadata-langitem',
992 $wrappedValue, $langName, $lang );
993 $item .= "</li>\n";
994 return $item;
995 }
996
997 /**
998 * Convenience function for getFormattedData()
999 *
1000 * @private
1001 *
1002 * @param $tag String: the tag name to pass on
1003 * @param $val String: the value of the tag
1004 * @param $arg String: an argument to pass ($1)
1005 * @param $arg2 String: a 2nd argument to pass ($2)
1006 * @return string A wfMsg of "exif-$tag-$val" in lower case
1007 */
1008 static function msg( $tag, $val, $arg = null, $arg2 = null ) {
1009 global $wgContLang;
1010
1011 if ($val === '')
1012 $val = 'value';
1013 return wfMsg( $wgContLang->lc( "exif-$tag-$val" ), $arg, $arg2 );
1014 }
1015
1016 /**
1017 * Format a number, convert numbers from fractions into floating point
1018 * numbers, joins arrays of numbers with commas.
1019 *
1020 * @private
1021 *
1022 * @param $num Mixed: the value to format
1023 * @param $round float|int digits to round to or false.
1024 * @return mixed A floating point number or whatever we were fed
1025 */
1026 static function formatNum( $num, $round = false ) {
1027 global $wgLang;
1028 $m = array();
1029 if( is_array($num) ) {
1030 $out = array();
1031 foreach( $num as $number ) {
1032 $out[] = self::formatNum($number);
1033 }
1034 return $wgLang->commaList( $out );
1035 }
1036 if ( preg_match( '/^(-?\d+)\/(\d+)$/', $num, $m ) ) {
1037 if ( $m[2] != 0 ) {
1038 $newNum = $m[1] / $m[2];
1039 if ( $round !== false ) {
1040 $newNum = round( $newNum, $round );
1041 }
1042 } else {
1043 $newNum = $num;
1044 }
1045
1046 return $wgLang->formatNum( $newNum );
1047 } else {
1048 if ( is_numeric( $num ) && $round !== false ) {
1049 $num = round( $num, $round );
1050 }
1051 return $wgLang->formatNum( $num );
1052 }
1053 }
1054
1055 /**
1056 * Format a rational number, reducing fractions
1057 *
1058 * @private
1059 *
1060 * @param $num Mixed: the value to format
1061 * @return mixed A floating point number or whatever we were fed
1062 */
1063 static function formatFraction( $num ) {
1064 $m = array();
1065 if ( preg_match( '/^(-?\d+)\/(\d+)$/', $num, $m ) ) {
1066 $numerator = intval( $m[1] );
1067 $denominator = intval( $m[2] );
1068 $gcd = self::gcd( abs( $numerator ), $denominator );
1069 if( $gcd != 0 ) {
1070 // 0 shouldn't happen! ;)
1071 return self::formatNum( $numerator / $gcd ) . '/' . self::formatNum( $denominator / $gcd );
1072 }
1073 }
1074 return self::formatNum( $num );
1075 }
1076
1077 /**
1078 * Calculate the greatest common divisor of two integers.
1079 *
1080 * @param $a Integer: Numerator
1081 * @param $b Integer: Denominator
1082 * @return int
1083 * @private
1084 */
1085 static function gcd( $a, $b ) {
1086 /*
1087 // http://en.wikipedia.org/wiki/Euclidean_algorithm
1088 // Recursive form would be:
1089 if( $b == 0 )
1090 return $a;
1091 else
1092 return gcd( $b, $a % $b );
1093 */
1094 while( $b != 0 ) {
1095 $remainder = $a % $b;
1096
1097 // tail recursion...
1098 $a = $b;
1099 $b = $remainder;
1100 }
1101 return $a;
1102 }
1103
1104 /**
1105 * Fetch the human readable version of a news code.
1106 * A news code is an 8 digit code. The first two
1107 * digits are a general classification, so we just
1108 * translate that.
1109 *
1110 * Note, leading 0's are significant, so this is
1111 * a string, not an int.
1112 *
1113 * @param $val String: The 8 digit news code.
1114 * @return srting The human readable form
1115 */
1116 static private function convertNewsCode( $val ) {
1117 if ( !preg_match( '/^\d{8}$/D', $val ) ) {
1118 // Not a valid news code.
1119 return $val;
1120 }
1121 $cat = '';
1122 switch( substr( $val , 0, 2 ) ) {
1123 case '01':
1124 $cat = 'ace';
1125 break;
1126 case '02':
1127 $cat = 'clj';
1128 break;
1129 case '03':
1130 $cat = 'dis';
1131 break;
1132 case '04':
1133 $cat = 'fin';
1134 break;
1135 case '05':
1136 $cat = 'edu';
1137 break;
1138 case '06':
1139 $cat = 'evn';
1140 break;
1141 case '07':
1142 $cat = 'hth';
1143 break;
1144 case '08':
1145 $cat = 'hum';
1146 break;
1147 case '09':
1148 $cat = 'lab';
1149 break;
1150 case '10':
1151 $cat = 'lif';
1152 break;
1153 case '11':
1154 $cat = 'pol';
1155 break;
1156 case '12':
1157 $cat = 'rel';
1158 break;
1159 case '13':
1160 $cat = 'sci';
1161 break;
1162 case '14':
1163 $cat = 'soi';
1164 break;
1165 case '15':
1166 $cat = 'spo';
1167 break;
1168 case '16':
1169 $cat = 'war';
1170 break;
1171 case '17':
1172 $cat = 'wea';
1173 break;
1174 }
1175 if ( $cat !== '' ) {
1176 $catMsg = self::msg( 'iimcategory', $cat );
1177 $val = self::msg( 'subjectnewscode', '', $val, $catMsg );
1178 }
1179 return $val;
1180 }
1181
1182 /**
1183 * Format a coordinate value, convert numbers from floating point
1184 * into degree minute second representation.
1185 *
1186 * @param $coord Array: degrees, minutes and seconds
1187 * @param $type String: latitude or longitude (for if its a NWS or E)
1188 * @return mixed A floating point number or whatever we were fed
1189 */
1190 static function formatCoords( $coord, $type ) {
1191 $ref = '';
1192 if ( $coord < 0 ) {
1193 $nCoord = -$coord;
1194 if ( $type === 'latitude' ) {
1195 $ref = 'S';
1196 }
1197 elseif ( $type === 'longitude' ) {
1198 $ref = 'W';
1199 }
1200 }
1201 else {
1202 $nCoord = $coord;
1203 if ( $type === 'latitude' ) {
1204 $ref = 'N';
1205 }
1206 elseif ( $type === 'longitude' ) {
1207 $ref = 'E';
1208 }
1209 }
1210
1211 $deg = floor( $nCoord );
1212 $min = floor( ( $nCoord - $deg ) * 60.0 );
1213 $sec = round( ( ( $nCoord - $deg ) - $min / 60 ) * 3600, 2 );
1214
1215 $deg = self::formatNum( $deg );
1216 $min = self::formatNum( $min );
1217 $sec = self::formatNum( $sec );
1218
1219 return wfMsg( 'exif-coordinate-format', $deg, $min, $sec, $ref, $coord );
1220 }
1221
1222 /**
1223 * Format the contact info field into a single value.
1224 *
1225 * @param $vals Array array with fields of the ContactInfo
1226 * struct defined in the IPTC4XMP spec. Or potentially
1227 * an array with one element that is a free form text
1228 * value from the older iptc iim 1:118 prop.
1229 *
1230 * This function might be called from
1231 * JpegHandler::convertMetadataVersion which is why it is
1232 * public.
1233 *
1234 * @return String of html-ish looking wikitext
1235 */
1236 public static function collapseContactInfo( $vals ) {
1237 if( ! ( isset( $vals['CiAdrExtadr'] )
1238 || isset( $vals['CiAdrCity'] )
1239 || isset( $vals['CiAdrCtry'] )
1240 || isset( $vals['CiEmailWork'] )
1241 || isset( $vals['CiTelWork'] )
1242 || isset( $vals['CiAdrPcode'] )
1243 || isset( $vals['CiAdrRegion'] )
1244 || isset( $vals['CiUrlWork'] )
1245 ) ) {
1246 // We don't have any sub-properties
1247 // This could happen if its using old
1248 // iptc that just had this as a free-form
1249 // text value.
1250 // Note: We run this through htmlspecialchars
1251 // partially to be consistent, and partially
1252 // because people often insert >, etc into
1253 // the metadata which should not be interpreted
1254 // but we still want to auto-link urls.
1255 foreach( $vals as &$val ) {
1256 $val = htmlspecialchars( $val );
1257 }
1258 return self::flattenArray( $vals );
1259 } else {
1260 // We have a real ContactInfo field.
1261 // Its unclear if all these fields have to be
1262 // set, so assume they do not.
1263 $url = $tel = $street = $city = $country = '';
1264 $email = $postal = $region = '';
1265
1266 // Also note, some of the class names this uses
1267 // are similar to those used by hCard. This is
1268 // mostly because they're sensible names. This
1269 // does not (and does not attempt to) output
1270 // stuff in the hCard microformat. However it
1271 // might output in the adr microformat.
1272
1273 if ( isset( $vals['CiAdrExtadr'] ) ) {
1274 // Todo: This can potentially be multi-line.
1275 // Need to check how that works in XMP.
1276 $street = '<span class="extended-address">'
1277 . htmlspecialchars(
1278 $vals['CiAdrExtadr'] )
1279 . '</span>';
1280 }
1281 if ( isset( $vals['CiAdrCity'] ) ) {
1282 $city = '<span class="locality">'
1283 . htmlspecialchars( $vals['CiAdrCity'] )
1284 . '</span>';
1285 }
1286 if ( isset( $vals['CiAdrCtry'] ) ) {
1287 $country = '<span class="country-name">'
1288 . htmlspecialchars( $vals['CiAdrCtry'] )
1289 . '</span>';
1290 }
1291 if ( isset( $vals['CiEmailWork'] ) ) {
1292 $emails = array();
1293 // Have to split multiple emails at commas/new lines.
1294 $splitEmails = explode( "\n", $vals['CiEmailWork'] );
1295 foreach ( $splitEmails as $e1 ) {
1296 // Also split on comma
1297 foreach ( explode( ',', $e1 ) as $e2 ) {
1298 $finalEmail = trim( $e2 );
1299 if ( $finalEmail == ',' || $finalEmail == '' ) {
1300 continue;
1301 }
1302 if ( strpos( $finalEmail, '<' ) !== false ) {
1303 // Don't do fancy formatting to
1304 // "My name" <foo@bar.com> style stuff
1305 $emails[] = $finalEmail;
1306 } else {
1307 $emails[] = '[mailto:'
1308 . $finalEmail
1309 . ' <span class="email">'
1310 . $finalEmail
1311 . '</span>]';
1312 }
1313 }
1314 }
1315 $email = implode( ', ', $emails );
1316 }
1317 if ( isset( $vals['CiTelWork'] ) ) {
1318 $tel = '<span class="tel">'
1319 . htmlspecialchars( $vals['CiTelWork'] )
1320 . '</span>';
1321 }
1322 if ( isset( $vals['CiAdrPcode'] ) ) {
1323 $postal = '<span class="postal-code">'
1324 . htmlspecialchars(
1325 $vals['CiAdrPcode'] )
1326 . '</span>';
1327 }
1328 if ( isset( $vals['CiAdrRegion'] ) ) {
1329 // Note this is province/state.
1330 $region = '<span class="region">'
1331 . htmlspecialchars(
1332 $vals['CiAdrRegion'] )
1333 . '</span>';
1334 }
1335 if ( isset( $vals['CiUrlWork'] ) ) {
1336 $url = '<span class="url">'
1337 . htmlspecialchars( $vals['CiUrlWork'] )
1338 . '</span>';
1339 }
1340 return wfMsg( 'exif-contact-value', $email, $url,
1341 $street, $city, $region, $postal, $country,
1342 $tel );
1343 }
1344 }
1345 }
1346
1347 /** For compatability with old FormatExif class
1348 * which some extensions use.
1349 *
1350 * @deprecated since 1.18
1351 *
1352 **/
1353 class FormatExif {
1354 var $meta;
1355 function FormatExif ( $meta ) {
1356 wfDeprecated(__METHOD__);
1357 $this->meta = $meta;
1358 }
1359
1360 function getFormattedData ( ) {
1361 return FormatMetadata::getFormattedData( $this->meta );
1362 }
1363 }