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