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