MediaWiki master
FormatMetadata.php
Go to the documentation of this file.
1<?php
14namespace MediaWiki\Media;
15
16use InvalidArgumentException;
22use MediaWiki\HookContainer\ProtectedHookAccessorTrait;
26use Wikimedia\Timestamp\TimestampFormat as TS;
27
50 use ProtectedHookAccessorTrait;
51
57 protected $singleLang = false;
58
65 public function setSingleLanguage( $val ) {
66 $this->singleLang = $val;
67 }
68
82 public static function getFormattedData( $tags, $context = false ) {
83 $obj = new self;
84 if ( $context ) {
85 $obj->setContext( $context );
86 }
87
88 return $obj->makeFormattedData( $tags );
89 }
90
102 public function makeFormattedData( $tags ) {
103 $resolutionunit = !isset( $tags['ResolutionUnit'] ) || $tags['ResolutionUnit'] == 2 ? 2 : 3;
104 unset( $tags['ResolutionUnit'] );
105
106 // Ignore these complex values
107 unset( $tags['HasExtendedXMP'] );
108 unset( $tags['AuthorsPosition'] );
109 unset( $tags['LocationCreated'] );
110 unset( $tags['LocationShown'] );
111 unset( $tags['GPSAltitudeRef'] );
112
113 foreach ( $tags as $tag => &$vals ) {
114 // This seems ugly to wrap non-array's in an array just to unwrap again,
115 // especially when most of the time it is not an array
116 if ( !is_array( $vals ) ) {
117 $vals = [ $vals ];
118 }
119
120 // _type is a special value to say what array type
121 if ( isset( $vals['_type'] ) ) {
122 $type = $vals['_type'];
123 unset( $vals['_type'] );
124 } else {
125 $type = 'ul'; // default unordered list.
126 }
127
128 // _formatted is a special value to indicate the subclass
129 // already handled & formatted this tag as wikitext
130 if ( isset( $tags[$tag]['_formatted'] ) ) {
131 $tags[$tag] = $this->flattenArrayReal(
132 $tags[$tag]['_formatted'], $type
133 );
134 continue;
135 }
136
137 // This is done differently as the tag is an array.
138 if ( $tag === 'GPSTimeStamp' && count( $vals ) === 3 ) {
139 // hour min sec array
140
141 $h = explode( '/', $vals[0], 2 );
142 $m = explode( '/', $vals[1], 2 );
143 $s = explode( '/', $vals[2], 2 );
144
145 // this should already be validated
146 // when loaded from file, but it could
147 // come from a foreign repo, so be
148 // paranoid.
149 if ( !isset( $h[1] )
150 || !isset( $m[1] )
151 || !isset( $s[1] )
152 || $h[1] == 0
153 || $m[1] == 0
154 || $s[1] == 0
155 ) {
156 continue;
157 }
158 $vals = str_pad( (string)( (int)$h[0] / (int)$h[1] ), 2, '0', STR_PAD_LEFT )
159 . ':' . str_pad( (string)( (int)$m[0] / (int)$m[1] ), 2, '0', STR_PAD_LEFT )
160 . ':' . str_pad( (string)( (int)$s[0] / (int)$s[1] ), 2, '0', STR_PAD_LEFT );
161
162 $time = wfTimestamp( TS::MW, '1971:01:01 ' . $vals );
163 // the 1971:01:01 is just a placeholder, and not shown to user.
164 if ( $time && (int)$time > 0 ) {
165 $vals = $this->getLanguage()->time( $time );
166 }
167 continue;
168 }
169
170 // The contact info is a multi-valued field
171 // instead of the other props which are single
172 // valued (mostly) so handle as a special case.
173 if ( $tag === 'Contact' || $tag === 'CreatorContactInfo' ) {
174 $vals = $this->collapseContactInfo( $vals );
175 continue;
176 }
177
178 foreach ( $vals as &$val ) {
179 switch ( $tag ) {
180 case 'Compression':
181 $val = match ( $val ) {
182 1, 2, 3, 4, 5, 6, 7, 8,
183 32773,
184 32946,
185 34712 => $this->exifMsg( $tag, $val ),
186 /* If not recognized, display as is. */
187 default => $this->literal( $val )
188 };
189 break;
190
191 case 'PhotometricInterpretation':
192 $val = match ( $val ) {
193 0, 1, 2, 3, 4, 5, 6, 8, 9, 10,
194 32803,
195 34892 => $this->exifMsg( $tag, $val ),
196 /* If not recognized, display as is. */
197 default => $this->literal( $val )
198 };
199 break;
200
201 case 'Orientation':
202 $val = match ( $val ) {
203 1, 2, 3, 4, 5, 6, 7, 8 => $this->exifMsg( $tag, $val ),
204 /* If not recognized, display as is. */
205 default => $this->literal( $val )
206 };
207 break;
208
209 case 'PlanarConfiguration':
210 // TODO: YCbCrSubSampling
211 case 'YCbCrPositioning':
212 $val = match ( $val ) {
213 1, 2 => $this->exifMsg( $tag, $val ),
214 /* If not recognized, display as is. */
215 default => $this->literal( $val )
216 };
217 break;
218
219 case 'XResolution':
220 case 'YResolution':
221 $val = match ( $resolutionunit ) {
222 2 => $this->exifMsg( 'XYResolution', 'i', $this->formatNum( $val ) ),
223 3 => $this->exifMsg( 'XYResolution', 'c', $this->formatNum( $val ) ),
224 /* If not recognized, display as is. */
225 default => $this->literal( $val )
226 };
227 break;
228
229 // TODO: YCbCrCoefficients #p27 (see annex E)
230 case 'ExifVersion':
231 // PHP likes to be the odd one out with casing of FlashPixVersion;
232 // https://www.exif.org/Exif2-2.PDF#page=32 and
233 // https://www.digitalgalen.net/Documents/External/XMP/XMPSpecificationPart2.pdf#page=51
234 // both use FlashpixVersion. However, since at least 2002, PHP has used FlashPixVersion at
235 // https://github.com/php/php-src/blame/master/ext/exif/exif.c#L725
236 case 'FlashPixVersion':
237 // But we can still get the correct casing from
238 // Wikimedia\XMPReader on PDFs
239 case 'FlashpixVersion':
240 $val = $this->literal( (int)$val / 100 );
241 break;
242
243 case 'ColorSpace':
244 $val = match ( $val ) {
245 1, 65535 => $this->exifMsg( $tag, $val ),
246 /* If not recognized, display as is. */
247 default => $this->literal( $val )
248 };
249 break;
250
251 case 'ComponentsConfiguration':
252 $val = match ( $val ) {
253 0, 1, 2, 3, 4, 5, 6 => $this->exifMsg( $tag, $val ),
254 /* If not recognized, display as is. */
255 default => $this->literal( $val )
256 };
257 break;
258
259 case 'DateTime':
260 case 'DateTimeOriginal':
261 case 'DateTimeDigitized':
262 case 'DateTimeReleased':
263 case 'DateTimeExpires':
264 case 'GPSDateStamp':
265 case 'dc-date':
266 case 'DateTimeMetadata':
267 case 'FirstPhotoDate':
268 case 'LastPhotoDate':
269 if ( $val === null ) {
270 // T384879 - we don't need to call literal to turn this into a string, but
271 // we might as well call it for consistency and future proofing of the default value
272 $val = $this->literal( $val );
273 break;
274 }
275
276 if ( $val === '0000:00:00 00:00:00' || $val === ' : : : : ' ) {
277 $val = $this->msg( 'exif-unknowndate' )->text();
278 break;
279 }
280 if ( preg_match(
281 '/^(?:\d{4}):(?:\d\d):(?:\d\d) (?:\d\d):(?:\d\d):(?:\d\d)$/D',
282 $val
283 ) ) {
284 // Full date.
285 $time = wfTimestamp( TS::MW, $val );
286 if ( $time && (int)$time > 0 ) {
287 $val = $this->getLanguage()->timeanddate( $time );
288 break;
289 }
290 } elseif ( preg_match( '/^(?:\d{4}):(?:\d\d):(?:\d\d) (?:\d\d):(?:\d\d)$/D', $val ) ) {
291 // No second field. Still format the same
292 // since timeanddate doesn't include seconds anyways,
293 // but second still available in api
294 $time = wfTimestamp( TS::MW, $val . ':00' );
295 if ( $time && (int)$time > 0 ) {
296 $val = $this->getLanguage()->timeanddate( $time );
297 break;
298 }
299 } elseif ( preg_match( '/^(?:\d{4}):(?:\d\d):(?:\d\d)$/D', $val ) ) {
300 // If only the date but not the time is filled in.
301 $time = wfTimestamp( TS::MW, substr( $val, 0, 4 )
302 . substr( $val, 5, 2 )
303 . substr( $val, 8, 2 )
304 . '000000' );
305 if ( $time && (int)$time > 0 ) {
306 $val = $this->getLanguage()->date( $time );
307 break;
308 }
309 }
310 // else it will just output $val without formatting it.
311 $val = $this->literal( $val );
312 break;
313
314 case 'ExposureProgram':
315 $val = match ( $val ) {
316 0, 1, 2, 3, 4, 5, 6, 7, 8 => $this->exifMsg( $tag, $val ),
317 /* If not recognized, display as is. */
318 default => $this->literal( $val )
319 };
320 break;
321
322 case 'SubjectDistance':
323 $val = $this->exifMsg( $tag, '', $this->formatNum( $val ) );
324 break;
325
326 case 'MeteringMode':
327 $val = match ( $val ) {
328 0, 1, 2, 3, 4, 5, 6, 7, 255 => $this->exifMsg( $tag, $val ),
329 /* If not recognized, display as is. */
330 default => $this->literal( $val )
331 };
332 break;
333
334 case 'LightSource':
335 $val = match ( $val ) {
336 0, 1, 2, 3, 4, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 24,
337 255 => $this->exifMsg( $tag, $val ),
338 /* If not recognized, display as is. */
339 default => $this->literal( $val )
340 };
341 break;
342
343 case 'Flash':
344 if ( !is_int( $val ) ) {
345 $val = 0;
346 }
347 $flashDecode = [
348 'fired' => $val & 0b00000001,
349 'return' => ( $val & 0b00000110 ) >> 1,
350 'mode' => ( $val & 0b00011000 ) >> 3,
351 'function' => ( $val & 0b00100000 ) >> 5,
352 'redeye' => ( $val & 0b01000000 ) >> 6,
353 // 'reserved' => ( $val & 0b10000000 ) >> 7,
354 ];
355 $flashMsgs = [];
356 # We do not need to handle unknown values since all are used.
357 foreach ( $flashDecode as $subTag => $subValue ) {
358 # We do not need any message for zeroed values.
359 if ( $subTag !== 'fired' && $subValue === 0 ) {
360 continue;
361 }
362 $fullTag = $tag . '-' . $subTag;
363 $flashMsgs[] = $this->exifMsg( $fullTag, $subValue );
364 }
365 $val = $this->getLanguage()->commaList( $flashMsgs );
366 break;
367
368 case 'FocalPlaneResolutionUnit':
369 $val = match ( $val ) {
370 2 => $this->exifMsg( $tag, $val ),
371 /* If not recognized, display as is. */
372 default => $this->literal( $val )
373 };
374 break;
375
376 case 'SensingMethod':
377 $val = match ( $val ) {
378 1, 2, 3, 4, 5, 7, 8 => $this->exifMsg( $tag, $val ),
379 /* If not recognized, display as is. */
380 default => $this->literal( $val )
381 };
382 break;
383
384 case 'FileSource':
385 $val = match ( $val ) {
386 3 => $this->exifMsg( $tag, $val ),
387 /* If not recognized, display as is. */
388 default => $this->literal( $val )
389 };
390 break;
391
392 case 'SceneType':
393 $val = match ( $val ) {
394 1 => $this->exifMsg( $tag, $val ),
395 /* If not recognized, display as is. */
396 default => $this->literal( $val )
397 };
398 break;
399
400 case 'CustomRendered':
401 $val = match ( $val ) {
402 0, /* normal */
403 1, /* custom */
404 /* The following are unofficial Apple additions */
405 2, /* HDR (no original saved) */
406 3, /* HDR (original saved) */
407 4, /* Original (for HDR) */
408 6, /* Panorama */
409 7, /* Portrait HDR */
410 8 /* Portrait */ => $this->exifMsg( $tag, $val ),
411 /* If not recognized, display as is. */
412 default => $this->literal( $val )
413 };
414 break;
415
416 case 'ExposureMode':
417 case 'Contrast':
418 case 'Saturation':
419 case 'Sharpness':
420 $val = match ( $val ) {
421 0, 1, 2 => $this->exifMsg( $tag, $val ),
422 /* If not recognized, display as is. */
423 default => $this->literal( $val )
424 };
425 break;
426
427 case 'WhiteBalance':
428 $val = match ( $val ) {
429 0, 1 => $this->exifMsg( $tag, $val ),
430 /* If not recognized, display as is. */
431 default => $this->literal( $val )
432 };
433 break;
434
435 case 'SceneCaptureType':
436 case 'SubjectDistanceRange':
437 $val = match ( $val ) {
438 0, 1, 2, 3 => $this->exifMsg( $tag, $val ),
439 /* If not recognized, display as is. */
440 default => $this->literal( $val )
441 };
442 break;
443
444 case 'GainControl':
445 $val = match ( $val ) {
446 0, 1, 2, 3, 4 => $this->exifMsg( $tag, $val ),
447 /* If not recognized, display as is. */
448 default => $this->literal( $val )
449 };
450 break;
451
452 // The GPS...Ref values are kept for compatibility, probably won't be reached.
453 case 'GPSLatitudeRef':
454 case 'GPSDestLatitudeRef':
455 $val = match ( $val ) {
456 'N', 'S' => $this->exifMsg( 'GPSLatitude', $val ),
457 /* If not recognized, display as is. */
458 default => $this->literal( $val )
459 };
460 break;
461
462 case 'GPSLongitudeRef':
463 case 'GPSDestLongitudeRef':
464 $val = match ( $val ) {
465 'E', 'W' => $this->exifMsg( 'GPSLongitude', $val ),
466 /* If not recognized, display as is. */
467 default => $this->literal( $val )
468 };
469 break;
470
471 case 'GPSAltitude':
472 if ( $val < 0 ) {
473 $val = $this->exifMsg( 'GPSAltitude', 'below-sealevel', $this->formatNum( -$val, 3 ) );
474 } else {
475 $val = $this->exifMsg( 'GPSAltitude', 'above-sealevel', $this->formatNum( $val, 3 ) );
476 }
477 break;
478
479 case 'GPSStatus':
480 $val = match ( $val ) {
481 'A', 'V' => $this->exifMsg( $tag, $val ),
482 /* If not recognized, display as is. */
483 default => $this->literal( $val )
484 };
485 break;
486
487 case 'GPSMeasureMode':
488 $val = match ( $val ) {
489 2, 3 => $this->exifMsg( $tag, $val ),
490 /* If not recognized, display as is. */
491 default => $this->literal( $val )
492 };
493 break;
494
495 case 'GPSTrackRef':
496 case 'GPSImgDirectionRef':
497 case 'GPSDestBearingRef':
498 $val = match ( $val ) {
499 'T', 'M' => $this->exifMsg( 'GPSDirection', $val ),
500 /* If not recognized, display as is. */
501 default => $this->literal( $val )
502 };
503 break;
504
505 case 'GPSLatitude':
506 case 'GPSDestLatitude':
507 $val = $this->formatCoords( $val, 'latitude' );
508 break;
509 case 'GPSLongitude':
510 case 'GPSDestLongitude':
511 $val = $this->formatCoords( $val, 'longitude' );
512 break;
513
514 case 'GPSSpeedRef':
515 $val = match ( $val ) {
516 'K', 'M', 'N' => $this->exifMsg( 'GPSSpeed', $val ),
517 /* If not recognized, display as is. */
518 default => $this->literal( $val )
519 };
520 break;
521
522 case 'GPSDestDistanceRef':
523 $val = match ( $val ) {
524 'K', 'M', 'N' => $this->exifMsg( 'GPSDestDistance', $val ),
525 /* If not recognized, display as is. */
526 default => $this->literal( $val )
527 };
528 break;
529
530 case 'GPSDOP':
531 // See https://en.wikipedia.org/wiki/Dilution_of_precision_(GPS)
532 if ( $val <= 2 ) {
533 $val = $this->exifMsg( $tag, 'excellent', $this->formatNum( $val ) );
534 } elseif ( $val <= 5 ) {
535 $val = $this->exifMsg( $tag, 'good', $this->formatNum( $val ) );
536 } elseif ( $val <= 10 ) {
537 $val = $this->exifMsg( $tag, 'moderate', $this->formatNum( $val ) );
538 } elseif ( $val <= 20 ) {
539 $val = $this->exifMsg( $tag, 'fair', $this->formatNum( $val ) );
540 } else {
541 $val = $this->exifMsg( $tag, 'poor', $this->formatNum( $val ) );
542 }
543 break;
544
545 // This is not in the Exif standard, just a special
546 // case for our purposes which enables wikis to wikify
547 // the make, model and software name to link to their articles.
548 case 'Make':
549 case 'Model':
550 $val = $this->exifMsg( $tag, '', $this->literal( $val ) );
551 break;
552
553 case 'Software':
554 if ( is_array( $val ) ) {
555 if ( count( $val ) > 1 ) {
556 // if its a software, version array.
557 $val = $this->msg(
558 'exif-software-version-value',
559 $this->literal( $val[0] ),
560 $this->literal( $val[1] )
561 )->text();
562 } else {
563 // https://phabricator.wikimedia.org/T178130
564 $val = $this->exifMsg( $tag, '', $this->literal( $val[0] ) );
565 }
566 } else {
567 $val = $this->exifMsg( $tag, '', $this->literal( $val ) );
568 }
569 break;
570
571 case 'ExposureTime':
572 // Show the pretty fraction as well as decimal version
573 $val = $this->msg( 'exif-exposuretime-format',
574 $this->formatFraction( $val ), $this->formatNum( $val ) )->text();
575 break;
576 case 'ISOSpeedRatings':
577 // If it's 65535 that means it's at the
578 // limit of the size of Exif::short and
579 // is really higher.
580 if ( $val === '65535' ) {
581 $val = $this->exifMsg( $tag, 'overflow' );
582 } else {
583 $val = $this->formatNum( $val );
584 }
585 break;
586 case 'FNumber':
587 $val = $this->msg( 'exif-fnumber-format',
588 $this->formatNum( $val ) )->text();
589 break;
590
591 case 'FocalLength':
592 case 'FocalLengthIn35mmFilm':
593 $val = $this->msg( 'exif-focallength-format',
594 $this->formatNum( $val ) )->text();
595 break;
596
597 case 'MaxApertureValue':
598 if ( str_contains( $val, '/' ) ) {
599 // need to expand this earlier to calculate fNumber
600 [ $n, $d ] = explode( '/', $val, 2 );
601 if ( is_numeric( $n ) && is_numeric( $d ) ) {
602 $val = (int)$n / (int)$d;
603 }
604 }
605 if ( is_numeric( $val ) ) {
606 $fNumber = 2 ** ( $val / 2 );
607 if ( is_finite( $fNumber ) ) {
608 $val = $this->msg( 'exif-maxaperturevalue-value',
609 $this->formatNum( $val ),
610 $this->formatNum( $fNumber, 2 )
611 )->text();
612 break;
613 }
614 }
615 $val = $this->literal( $val );
616 break;
617
618 case 'iimCategory':
619 $val = match ( strtolower( $val ) ) {
620 // See pg 29 of IPTC photo
621 // metadata standard.
622 'ace', 'clj', 'dis', 'fin', 'edu', 'evn', 'hth', 'hum', 'lab', 'lif',
623 'pol', 'rel', 'sci', 'soi', 'spo', 'war',
624 'wea' => $this->exifMsg( 'iimcategory', $val ),
625 default => $this->literal( $val )
626 };
627 break;
628 case 'SubjectNewsCode':
629 // Essentially like iimCategory.
630 // 8 (numeric) digit hierarchical
631 // classification. We decode the
632 // first 2 digits, which provide
633 // a broad category.
634 $val = $this->convertNewsCode( $val );
635 break;
636 case 'Urgency':
637 // 1-8 with 1 being highest, 5 normal
638 // 0 is reserved, and 9 is 'user-defined'.
639 $ival = (int)$val;
640 if ( (string)$ival !== (string)$val ) {
641 $urgency = '';
642 } elseif ( $ival < 1 ) {
643 $urgency = 'other';
644 } elseif ( $ival < 5 ) {
645 $urgency = 'high';
646 } elseif ( $ival === 5 ) {
647 $urgency = 'normal';
648 } elseif ( $ival < 9 ) {
649 $urgency = 'low';
650 } else {
651 $urgency = 'other';
652 }
653
654 if ( $urgency !== '' ) {
655 $val = $this->exifMsg( 'urgency',
656 $urgency, $this->literal( $val )
657 );
658 } else {
659 $val = $this->literal( $val );
660 }
661 break;
662 case 'DigitalSourceType':
663 // Should be a url starting with
664 // http://cv.iptc.org/newscodes/digitalsourcetype/
665 if ( str_starts_with( $val, 'http://cv.iptc.org/newscodes/digitalsourcetype/' ) ) {
666 $code = substr( $val, 47 );
667 $msg = $this->msg( 'exif-digitalsourcetype-' . strtolower( $code ) );
668 if ( !$msg->isDisabled() ) {
669 $val = $msg->text();
670 break;
671 }
672 }
673 $val = $this->literal( $val );
674 break;
675 // Things that have a unit of pixels.
676 case 'OriginalImageHeight':
677 case 'OriginalImageWidth':
678 case 'PixelXDimension':
679 case 'PixelYDimension':
680 case 'ImageWidth':
681 case 'ImageLength':
682 $val = $this->formatNum( $val ) . ' ' . $this->msg( 'unit-pixel' )->text();
683 break;
684
685 // Do not transform fields with pure text.
686 // For some languages the formatNum()
687 // conversion results to wrong output like
688 // foo,bar@example,com or fooÙ«bar@exampleÙ«com.
689 // Also some 'numeric' things like Scene codes
690 // are included here as we really don't want
691 // commas inserted.
692 case 'ImageDescription':
693 case 'UserComment':
694 case 'Artist':
695 case 'Copyright':
696 case 'RelatedSoundFile':
697 case 'ImageUniqueID':
698 case 'SpectralSensitivity':
699 case 'GPSSatellites':
700 case 'GPSVersionID':
701 case 'GPSMapDatum':
702 case 'Keywords':
703 case 'WorldRegionDest':
704 case 'CountryDest':
705 case 'CountryCodeDest':
706 case 'ProvinceOrStateDest':
707 case 'CityDest':
708 case 'SublocationDest':
709 case 'WorldRegionCreated':
710 case 'CountryCreated':
711 case 'CountryCodeCreated':
712 case 'ProvinceOrStateCreated':
713 case 'CityCreated':
714 case 'SublocationCreated':
715 case 'ObjectName':
716 case 'SpecialInstructions':
717 case 'Headline':
718 case 'Credit':
719 case 'Source':
720 case 'EditStatus':
721 case 'FixtureIdentifier':
722 case 'LocationDest':
723 case 'LocationDestCode':
724 case 'Writer':
725 case 'JPEGFileComment':
726 case 'iimSupplementalCategory':
727 case 'OriginalTransmissionRef':
728 case 'Identifier':
729 case 'dc-contributor':
730 case 'dc-coverage':
731 case 'dc-publisher':
732 case 'dc-relation':
733 case 'dc-rights':
734 case 'dc-source':
735 case 'dc-type':
736 case 'Lens':
737 case 'SerialNumber':
738 case 'CameraOwnerName':
739 case 'Label':
740 case 'Nickname':
741 case 'RightsCertificate':
742 case 'CopyrightOwner':
743 case 'UsageTerms':
744 case 'WebStatement':
745 case 'OriginalDocumentID':
746 case 'LicenseUrl':
747 case 'MorePermissionsUrl':
748 case 'AttributionUrl':
749 case 'PreferredAttributionName':
750 case 'PNGFileComment':
751 case 'Disclaimer':
752 case 'ContentWarning':
753 case 'GIFFileComment':
754 case 'SceneCode':
755 case 'IntellectualGenre':
756 case 'Event':
757 case 'OrganisationInImage':
758 case 'PersonInImage':
759 case 'CaptureSoftware':
760 case 'GPSAreaInformation':
761 case 'GPSProcessingMethod':
762 case 'StitchingSoftware':
763 case 'SubSecTime':
764 case 'SubSecTimeOriginal':
765 case 'SubSecTimeDigitized':
766 $val = $this->literal( $val );
767 break;
768
769 case 'ProjectionType':
770 $val = match ( $val ) {
771 'equirectangular' => $this->exifMsg( $tag, $val ),
772 default => $this->literal( $val )
773 };
774 break;
775 case 'ObjectCycle':
776 $val = match ( $val ) {
777 'a', 'p', 'b' => $this->exifMsg( $tag, $val ),
778 default => $this->literal( $val )
779 };
780 break;
781 case 'Copyrighted':
782 case 'UsePanoramaViewer':
783 case 'ExposureLockUsed':
784 $val = match ( $val ) {
785 'True', 'False' => $this->exifMsg( $tag, $val ),
786 default => $this->literal( $val )
787 };
788 break;
789 case 'Rating':
790 if ( $val === '-1' ) {
791 $val = $this->exifMsg( $tag, 'rejected' );
792 } else {
793 $val = $this->formatNum( $val );
794 }
795 break;
796
797 case 'LanguageCode':
799 ->getLanguageNameUtils()
800 ->getLanguageName( strtolower( $val ), $this->getLanguage()->getCode() );
801 $val = $this->literal( $lang ?: $val );
802 break;
803
804 default:
805 $val = $this->formatNum( $val, false, $tag );
806 break;
807 }
808 }
809 // End formatting values, start flattening arrays.
810 $vals = $this->flattenArrayReal( $vals, $type );
811 }
812
813 return $tags;
814 }
815
833 public function flattenArrayReal( $vals, $type = 'ul', $noHtml = false ) {
834 if ( !is_array( $vals ) ) {
835 return $vals; // do nothing if not an array;
836 }
837
838 if ( isset( $vals['_type'] ) ) {
839 $type = $vals['_type'];
840 unset( $vals['_type'] );
841 }
842
843 if ( count( $vals ) === 1 && $type !== 'lang' && isset( $vals[0] ) ) {
844 return $vals[0];
845 }
846 if ( count( $vals ) === 0 ) {
847 wfDebug( __METHOD__ . " metadata array with 0 elements!" );
848
849 return ""; // paranoia. This should never happen
850 }
851 // Check if $vals contains nested arrays
852 $containsNestedArrays = in_array( true, array_map( 'is_array', $vals ), true );
853 if ( $containsNestedArrays ) {
854 wfLogWarning( __METHOD__ . ': Invalid $vals, contains nested arrays: ' . json_encode( $vals ) );
855 }
856
857 /* @todo FIXME: This should hide some of the list entries if there are
858 * say more than four. Especially if a field is translated into 20
859 * languages, we don't want to show them all by default
860 */
861 switch ( $type ) {
862 case 'lang':
863 // Display default, followed by ContentLanguage,
864 // followed by the rest in no particular order.
865
866 // Todo: hide some items if really long list.
867
868 $content = '';
869
870 $priorityLanguages = $this->getPriorityLanguages();
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 one of the lang codes.
876 // (In xmp you specify the language for a default property by having
877 // both a default prop, and one in the language that are identical)
878 if ( isset( $vals['x-default'] ) ) {
879 $defaultItem = $vals['x-default'];
880 unset( $vals['x-default'] );
881 }
882 foreach ( $priorityLanguages as $pLang ) {
883 if ( isset( $vals[$pLang] ) ) {
884 $isDefault = false;
885 if ( $vals[$pLang] === $defaultItem ) {
886 $defaultItem = false;
887 $isDefault = true;
888 }
889 $content .= $this->langItem( $vals[$pLang], $pLang, $isDefault, $noHtml );
890
891 unset( $vals[$pLang] );
892
893 if ( $this->singleLang ) {
894 return Html::rawElement( 'span', [ 'lang' => $pLang ], $vals[$pLang] );
895 }
896 }
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 .= $this->langItem( $item, $lang, false, $noHtml );
906 if ( $this->singleLang ) {
907 return Html::rawElement( 'span', [ 'lang' => $lang ], $item );
908 }
909 }
910 if ( $defaultItem !== false ) {
911 $content = $this->langItem( $defaultItem, $defaultLang, true, $noHtml ) . $content;
912 if ( $this->singleLang ) {
913 return $defaultItem;
914 }
915 }
916 if ( $noHtml ) {
917 return $content;
918 }
919
920 return '<ul class="metadata-langlist">' . $content . '</ul>';
921 case 'ol':
922 if ( $noHtml ) {
923 return "\n#" . implode( "\n#", $vals );
924 }
925
926 return "<ol><li>" . implode( "</li>\n<li>", $vals ) . '</li></ol>';
927 case 'ul':
928 default:
929 if ( $noHtml ) {
930 return "\n*" . implode( "\n*", $vals );
931 }
932
933 return "<ul><li>" . implode( "</li>\n<li>", $vals ) . '</li></ul>';
934 }
935 }
936
946 private function langItem( $value, $lang, $default = false, $noHtml = false ) {
947 if ( $lang === false && $default === false ) {
948 throw new InvalidArgumentException( '$lang and $default cannot both be false.' );
949 }
950
951 if ( $noHtml ) {
952 $wrappedValue = $value;
953 } else {
954 $wrappedValue = '<span class="mw-metadata-lang-value">' . $value . '</span>';
955 }
956
957 if ( $lang === false ) {
958 $msg = $this->msg( 'metadata-langitem-default', $wrappedValue );
959 if ( $noHtml ) {
960 return $msg->text() . "\n\n";
961 } /* else */
962
963 return '<li class="mw-metadata-lang-default">' . $msg->text() . "</li>\n";
964 }
965
966 $lowLang = strtolower( $lang );
967 $languageNameUtils = MediaWikiServices::getInstance()->getLanguageNameUtils();
968 $langName = $languageNameUtils->getLanguageName( $lowLang );
969 if ( $langName === '' ) {
970 // try just the base language name. (aka en-US -> en ).
971 $langPrefix = explode( '-', $lowLang, 2 )[0];
972 $langName = $languageNameUtils->getLanguageName( $langPrefix );
973 if ( $langName === '' ) {
974 // give up.
975 $langName = $lang;
976 }
977 }
978 // else we have a language specified
979
980 $msg = $this->msg( 'metadata-langitem', $wrappedValue, $langName, $lang );
981 if ( $noHtml ) {
982 return '*' . $msg->text();
983 } /* else: */
984
985 $item = '<li class="mw-metadata-lang-code-' . $lang;
986 if ( $default ) {
987 $item .= ' mw-metadata-lang-default';
988 }
989 $item .= '" lang="' . $lang . '">';
990 $item .= $msg->text();
991 $item .= "</li>\n";
992
993 return $item;
994 }
995
1003 protected function literal( $val ): string {
1004 if ( $val === null ) {
1005 return '';
1006 }
1007 // T266707: historically this has used htmlspecialchars to protect
1008 // the string contents, but it should probably be changed to use
1009 // wfEscapeWikitext() instead -- however, "we still want to auto-link
1010 // urls" so wfEscapeWikitext isn't *quite* right...
1011 return htmlspecialchars( $val );
1012 }
1013
1023 private function exifMsg( $tag, $val, $arg = null, $arg2 = null ) {
1024 if ( $val === '' ) {
1025 $val = 'value';
1026 }
1027
1028 return $this->msg(
1029 MediaWikiServices::getInstance()->getContentLanguage()->lc( "exif-$tag-$val" ),
1030 $arg,
1031 $arg2
1032 )->text();
1033 }
1034
1044 private function formatNum( $num, $round = false, $tagName = null ) {
1045 $m = [];
1046 if ( is_array( $num ) ) {
1047 $out = [];
1048 foreach ( $num as $number ) {
1049 $out[] = $this->formatNum( $number, $round, $tagName );
1050 }
1051
1052 return $this->getLanguage()->commaList( $out );
1053 }
1054 if ( is_numeric( $num ) ) {
1055 if ( $round !== false ) {
1056 $num = round( $num, $round );
1057 }
1058 return $this->getLanguage()->formatNum( $num );
1059 }
1060 $num ??= '';
1061 if ( preg_match( '/^(-?\d+)\/(\d+)$/', $num, $m ) ) {
1062 if ( (int)$m[2] !== 0 ) {
1063 $newNum = (int)$m[1] / (int)$m[2];
1064 if ( $round !== false ) {
1065 $newNum = round( $newNum, $round );
1066 }
1067 } else {
1068 $newNum = $num;
1069 }
1070
1071 return $this->getLanguage()->formatNum( $newNum );
1072 }
1073 # T267370: there are a lot of strange EXIF tags floating around.
1074 LoggerFactory::getInstance( 'formatnum' )->warning(
1075 'FormatMetadata::formatNum with non-numeric value',
1076 [
1077 'tag' => $tagName,
1078 'value' => $num,
1079 ]
1080 );
1081 return $this->literal( $num );
1082 }
1083
1090 private function formatFraction( $num ) {
1091 $m = [];
1092 $num ??= '';
1093 if ( preg_match( '/^(-?\d+)\/(\d+)$/', $num, $m ) ) {
1094 $numerator = (int)$m[1];
1095 $denominator = (int)$m[2];
1096 $gcd = $this->gcd( abs( $numerator ), $denominator );
1097 if ( $gcd !== 0 ) {
1098 // 0 shouldn't happen! ;)
1099 return $this->formatNum( $numerator / $gcd ) . '/' . $this->formatNum( $denominator / $gcd );
1100 }
1101 }
1102
1103 return $this->formatNum( $num );
1104 }
1105
1113 private function gcd( $a, $b ) {
1114 /*
1115 // https://en.wikipedia.org/wiki/Euclidean_algorithm
1116 // Recursive form would be:
1117 if ( $b == 0 )
1118 return $a;
1119 else
1120 return gcd( $b, $a % $b );
1121 */
1122 while ( $b != 0 ) {
1123 $remainder = $a % $b;
1124
1125 // tail recursion...
1126 $a = $b;
1127 $b = $remainder;
1128 }
1129
1130 return $a;
1131 }
1132
1145 private function convertNewsCode( $val ) {
1146 if ( !preg_match( '/^\d{8}$/D', $val ) ) {
1147 // Not a valid news code.
1148 return $val;
1149 }
1150 $cat = match ( substr( $val, 0, 2 ) ) {
1151 '01' => 'ace',
1152 '02' => 'clj',
1153 '03' => 'dis',
1154 '04' => 'fin',
1155 '05' => 'edu',
1156 '06' => 'evn',
1157 '07' => 'hth',
1158 '08' => 'hum',
1159 '09' => 'lab',
1160 '10' => 'lif',
1161 '11' => 'pol',
1162 '12' => 'rel',
1163 '13' => 'sci',
1164 '14' => 'soi',
1165 '15' => 'spo',
1166 '16' => 'war',
1167 '17' => 'wea',
1168 default => '',
1169 };
1170 if ( $cat !== '' ) {
1171 $catMsg = $this->exifMsg( 'iimcategory', $cat );
1172 $val = $this->exifMsg( 'subjectnewscode', '', $this->literal( $val ), $catMsg );
1173 }
1174
1175 return $val;
1176 }
1177
1186 private function formatCoords( $coord, string $type ) {
1187 if ( !is_numeric( $coord ) ) {
1188 wfDebugLog( 'exif', __METHOD__ . ": \"$coord\" is not a number" );
1189 return $this->literal( (string)$coord );
1190 }
1191
1192 $ref = '';
1193 if ( $coord < 0 ) {
1194 $nCoord = -$coord;
1195 if ( $type === 'latitude' ) {
1196 $ref = 'S';
1197 } elseif ( $type === 'longitude' ) {
1198 $ref = 'W';
1199 }
1200 } else {
1201 $nCoord = (float)$coord;
1202 if ( $type === 'latitude' ) {
1203 $ref = 'N';
1204 } elseif ( $type === 'longitude' ) {
1205 $ref = 'E';
1206 }
1207 }
1208
1209 $deg = floor( $nCoord );
1210 $min = floor( ( $nCoord - $deg ) * 60 );
1211 $sec = round( ( ( $nCoord - $deg ) * 60 - $min ) * 60, 2 );
1212
1213 $deg = $this->formatNum( $deg );
1214 $min = $this->formatNum( $min );
1215 $sec = $this->formatNum( $sec );
1216
1217 // Note the default message "$1° $2′ $3″ $4" ignores the 5th parameter
1218 return $this->msg( 'exif-coordinate-format', $deg, $min, $sec, $ref, $this->literal( $coord ) )->text();
1219 }
1220
1235 public function collapseContactInfo( array $vals ) {
1236 if ( !( isset( $vals['CiAdrExtadr'] )
1237 || isset( $vals['CiAdrCity'] )
1238 || isset( $vals['CiAdrCtry'] )
1239 || isset( $vals['CiEmailWork'] )
1240 || isset( $vals['CiTelWork'] )
1241 || isset( $vals['CiAdrPcode'] )
1242 || isset( $vals['CiAdrRegion'] )
1243 || isset( $vals['CiUrlWork'] )
1244 ) ) {
1245 // We don't have any sub-properties
1246 // This could happen if its using old
1247 // iptc that just had this as a free-form
1248 // text value.
1249 // Note: people often insert >, etc into
1250 // the metadata which should not be interpreted
1251 // but we still want to auto-link urls.
1252 foreach ( $vals as &$val ) {
1253 $val = $this->literal( $val );
1254 }
1255
1256 return $this->flattenArrayReal( $vals );
1257 }
1258
1259 // We have a real ContactInfo field.
1260 // Its unclear if all these fields have to be
1261 // set, so assume they do not.
1262 $url = $tel = $street = $city = $country = '';
1263 $email = $postal = $region = '';
1264
1265 // Also note, some of the class names this uses
1266 // are similar to those used by hCard. This is
1267 // mostly because they're sensible names. This
1268 // does not (and does not attempt to) output
1269 // stuff in the hCard microformat. However it
1270 // might output in the adr microformat.
1271
1272 if ( isset( $vals['CiAdrExtadr'] ) ) {
1273 // Todo: This can potentially be multi-line.
1274 // Need to check how that works in XMP.
1275 $street = '<span class="extended-address">'
1276 . $this->literal(
1277 $vals['CiAdrExtadr'] )
1278 . '</span>';
1279 }
1280 if ( isset( $vals['CiAdrCity'] ) ) {
1281 $city = '<span class="locality">'
1282 . $this->literal( $vals['CiAdrCity'] )
1283 . '</span>';
1284 }
1285 if ( isset( $vals['CiAdrCtry'] ) ) {
1286 $country = '<span class="country-name">'
1287 . $this->literal( $vals['CiAdrCtry'] )
1288 . '</span>';
1289 }
1290 if ( isset( $vals['CiEmailWork'] ) ) {
1291 $emails = [];
1292 // Have to split multiple emails at commas/new lines.
1293 $splitEmails = explode( "\n", $vals['CiEmailWork'] );
1294 foreach ( $splitEmails as $e1 ) {
1295 // Also split on comma
1296 foreach ( explode( ',', $e1 ) as $e2 ) {
1297 $finalEmail = trim( $e2 );
1298 if ( $finalEmail === ',' || $finalEmail === '' ) {
1299 continue;
1300 }
1301 if ( str_contains( $finalEmail, '<' ) ) {
1302 // Don't do fancy formatting to
1303 // "My name" <foo@bar.com> style stuff
1304 $emails[] = $this->literal( $finalEmail );
1305 } else {
1306 $emails[] = '[mailto:'
1307 . $finalEmail
1308 . ' <span class="email">'
1309 . $this->literal( $finalEmail )
1310 . '</span>]';
1311 }
1312 }
1313 }
1314 $email = implode( ', ', $emails );
1315 }
1316 if ( isset( $vals['CiTelWork'] ) ) {
1317 $tel = '<span class="tel">'
1318 . $this->literal( $vals['CiTelWork'] )
1319 . '</span>';
1320 }
1321 if ( isset( $vals['CiAdrPcode'] ) ) {
1322 $postal = '<span class="postal-code">'
1323 . $this->literal( $vals['CiAdrPcode'] )
1324 . '</span>';
1325 }
1326 if ( isset( $vals['CiAdrRegion'] ) ) {
1327 // Note this is province/state.
1328 $region = '<span class="region">'
1329 . $this->literal( $vals['CiAdrRegion'] )
1330 . '</span>';
1331 }
1332 if ( isset( $vals['CiUrlWork'] ) ) {
1333 $url = '<span class="url">'
1334 . $this->literal( $vals['CiUrlWork'] )
1335 . '</span>';
1336 }
1337
1338 return $this->msg( 'exif-contact-value', $email, $url,
1339 $street, $city, $region, $postal, $country, $tel )->text();
1340 }
1341
1348 public static function getVisibleFields() {
1349 $fields = [];
1350 $lines = explode( "\n", wfMessage( 'metadata-fields' )->inContentLanguage()->text() );
1351 foreach ( $lines as $line ) {
1352 $matches = [];
1353 if ( preg_match( '/^\\*\s*(.*?)\s*$/', $line, $matches ) ) {
1354 $fields[] = $matches[1];
1355 }
1356 }
1357 $fields = array_map( 'strtolower', $fields );
1358
1359 return $fields;
1360 }
1361
1369 public function fetchExtendedMetadata( File $file ) {
1370 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1371
1372 // If revision deleted, exit immediately
1373 if ( $file->isDeleted( File::DELETED_FILE ) ) {
1374 return [];
1375 }
1376
1377 $cacheKey = $cache->makeKey(
1378 'getExtendedMetadata',
1379 $this->getLanguage()->getCode(),
1380 (int)$this->singleLang,
1381 $file->getSha1()
1382 );
1383 $maxCacheTime = ( $file instanceof ForeignAPIFile ) ? 60 * 60 * 12 : 60 * 60 * 24 * 30;
1384
1385 $cachedValue = $cache->getWithSetCallback(
1386 $cacheKey,
1387 $maxCacheTime,
1388 function () use ( $file ) {
1389 $fileMetadata = $this->getExtendedMetadataFromFile( $file );
1390 $extendedMetadata = $this->getExtendedMetadataFromHook( $file, $fileMetadata, $maxCacheTime );
1391 if ( $this->singleLang ) {
1392 $this->resolveMultilangMetadata( $extendedMetadata );
1393 }
1394 $this->discardMultipleValues( $extendedMetadata );
1395 // Make sure the metadata won't break the API when an XML format is used.
1396 // This is an API-specific function so it would be cleaner to call it from
1397 // outside fetchExtendedMetadata, but this way we don't need to redo the
1398 // computation on a cache hit.
1399 $this->sanitizeArrayForAPI( $extendedMetadata );
1400
1401 return [ 'data' => $extendedMetadata, 'timestamp' => wfTimestampNow() ];
1402 },
1403 [
1404 'touchedCallback' => function ( $value ) use ( $file ) {
1405 if (
1406 !$this->getHookRunner()->onValidateExtendedMetadataCache( $value['timestamp'], $file )
1407 ) {
1408 // Reject cache and regenerate
1409 return time();
1410 }
1411 return null;
1412 }
1413 ]
1414 );
1415
1416 return $cachedValue['data'];
1417 }
1418
1428 protected function getExtendedMetadataFromFile( File $file ) {
1429 // If this is a remote file accessed via an API request, we already
1430 // have remote metadata so we just ignore any local one
1431 if ( $file instanceof ForeignAPIFile ) {
1432 // In case of error we pretend no metadata - this will get cached.
1433 // Might or might not be a good idea.
1434 return $file->getExtendedMetadata() ?: [];
1435 }
1436
1437 $uploadDate = wfTimestamp( TS::ISO_8601, $file->getTimestamp() );
1438
1439 $fileMetadata = [
1440 // This is modification time, which is close to "upload" time.
1441 'DateTime' => [
1442 'value' => $uploadDate,
1443 'source' => 'mediawiki-metadata',
1444 ],
1445 ];
1446
1447 $title = $file->getTitle();
1448 if ( $title ) {
1449 $text = $title->getText();
1450 $pos = strrpos( $text, '.' );
1451
1452 if ( $pos ) {
1453 $name = substr( $text, 0, $pos );
1454 } else {
1455 $name = $text;
1456 }
1457
1458 $fileMetadata['ObjectName'] = [
1459 'value' => $name,
1460 'source' => 'mediawiki-metadata',
1461 ];
1462 }
1463
1464 return $fileMetadata;
1465 }
1466
1477 protected function getExtendedMetadataFromHook( File $file, array $extendedMetadata,
1478 &$maxCacheTime
1479 ) {
1480 $this->getHookRunner()->onGetExtendedMetadata(
1481 $extendedMetadata,
1482 $file,
1483 $this->getContext(),
1484 $this->singleLang,
1485 $maxCacheTime
1486 );
1487
1488 $visible = array_fill_keys( self::getVisibleFields(), true );
1489 foreach ( $extendedMetadata as $key => $value ) {
1490 if ( !isset( $visible[strtolower( $key )] ) ) {
1491 $extendedMetadata[$key]['hidden'] = '';
1492 }
1493 }
1494
1495 return $extendedMetadata;
1496 }
1497
1506 protected function resolveMultilangValue( $value ) {
1507 if (
1508 !is_array( $value )
1509 || !isset( $value['_type'] )
1510 || $value['_type'] !== 'lang'
1511 ) {
1512 return $value; // do nothing if not a multilang array
1513 }
1514
1515 // choose the language best matching user or site settings
1516 $priorityLanguages = $this->getPriorityLanguages();
1517 foreach ( $priorityLanguages as $lang ) {
1518 if ( isset( $value[$lang] ) ) {
1519 return $value[$lang];
1520 }
1521 }
1522
1523 // otherwise go with the default language, if set
1524 if ( isset( $value['x-default'] ) ) {
1525 return $value['x-default'];
1526 }
1527
1528 // otherwise just return any one language
1529 unset( $value['_type'] );
1530 if ( $value ) {
1531 return reset( $value );
1532 }
1533
1534 // this should not happen; signal error
1535 return null;
1536 }
1537
1547 protected function resolveMultivalueValue( $value ) {
1548 if ( !is_array( $value ) ) {
1549 return $value;
1550 }
1551 if ( isset( $value['_type'] ) && $value['_type'] === 'lang' ) {
1552 // if this is a multilang array, process fields separately
1553 $newValue = [];
1554 foreach ( $value as $k => $v ) {
1555 $newValue[$k] = $this->resolveMultivalueValue( $v );
1556 }
1557 return $newValue;
1558 }
1559 // _type is 'ul' or 'ol' or missing in which case it defaults to 'ul'
1560 $v = reset( $value );
1561 if ( key( $value ) === '_type' ) {
1562 $v = next( $value );
1563 }
1564 return $v;
1565 }
1566
1573 protected function resolveMultilangMetadata( &$metadata ) {
1574 if ( !is_array( $metadata ) ) {
1575 return;
1576 }
1577 foreach ( $metadata as &$field ) {
1578 if ( isset( $field['value'] ) ) {
1579 $field['value'] = $this->resolveMultilangValue( $field['value'] );
1580 }
1581 }
1582 }
1583
1590 protected function discardMultipleValues( &$metadata ) {
1591 if ( !is_array( $metadata ) ) {
1592 return;
1593 }
1594 foreach ( $metadata as $key => &$field ) {
1595 if ( $key === 'Software' || $key === 'Contact' ) {
1596 // we skip some fields which have composite values. They are not particularly interesting
1597 // and you can get them via the metadata / commonmetadata APIs anyway.
1598 continue;
1599 }
1600 if ( isset( $field['value'] ) ) {
1601 $field['value'] = $this->resolveMultivalueValue( $field['value'] );
1602 }
1603 }
1604 }
1605
1610 protected function sanitizeArrayForAPI( &$arr ) {
1611 if ( !is_array( $arr ) ) {
1612 return;
1613 }
1614
1615 $counter = 1;
1616 foreach ( $arr as $key => &$value ) {
1617 $sanitizedKey = $this->sanitizeKeyForAPI( $key );
1618 if ( $sanitizedKey !== $key ) {
1619 if ( isset( $arr[$sanitizedKey] ) ) {
1620 // Make the sanitized keys hopefully unique.
1621 // To make it definitely unique would be too much effort, given that
1622 // sanitizing is only needed for misformatted metadata anyway, but
1623 // this at least covers the case when $arr is numeric.
1624 $sanitizedKey .= $counter;
1625 ++$counter;
1626 }
1627 $arr[$sanitizedKey] = $arr[$key];
1628 unset( $arr[$key] );
1629 }
1630 if ( is_array( $value ) ) {
1631 $this->sanitizeArrayForAPI( $value );
1632 }
1633 }
1634 unset( $value );
1635
1636 // Handle API metadata keys (particularly "_type")
1637 $keys = array_filter( array_keys( $arr ), ApiResult::isMetadataKey( ... ) );
1638 if ( $keys ) {
1639 ApiResult::setPreserveKeysList( $arr, $keys );
1640 }
1641 }
1642
1649 protected function sanitizeKeyForAPI( $key ) {
1650 // drop all characters which are not valid in an XML tag name
1651 // a bunch of non-ASCII letters would be valid but probably won't
1652 // be used so we take the easy way
1653 $key = preg_replace( '/[^a-zA-Z0-9_:.\-]/', '', $key );
1654 // drop characters which are invalid at the first position
1655 $key = preg_replace( '/^[\d\-.]+/', '', $key );
1656
1657 if ( $key === '' ) {
1658 $key = '_';
1659 // special case for an internal keyword
1660 } elseif ( $key === '_element' ) {
1661 $key = 'element';
1662 }
1663
1664 return $key;
1665 }
1666
1673 protected function getPriorityLanguages() {
1674 $priorityLanguages = MediaWikiServices::getInstance()
1675 ->getLanguageFallback()
1676 ->getAllIncludingSiteLanguage( $this->getLanguage()->getCode() );
1677 $priorityLanguages = array_merge(
1678 (array)$this->getLanguage()->getCode(),
1679 $priorityLanguages[0],
1680 $priorityLanguages[1]
1681 );
1682
1683 return $priorityLanguages;
1684 }
1685}
1686
1688class_alias( FormatMetadata::class, 'FormatMetadata' );
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
wfLogWarning( $msg, $callerOffset=1, $level=E_USER_WARNING)
Send a warning as a PHP error and the debug log.
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
wfTimestamp( $outputtype=TS::UNIX, $ts=0)
Get a timestamp string in one of various formats.
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
if(!defined('MW_SETUP_CALLBACK'))
Definition WebStart.php:71
This class represents the result of the API operations.
Definition ApiResult.php:34
The simplest way of implementing IContextSource is to hold a RequestContext as a member variable and ...
msg( $key,... $params)
Get a Message object with context set Parameters are the same as wfMessage()
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition File.php:80
getSha1()
Get the SHA-1 base 36 hash of the file.
Definition File.php:2456
isDeleted( $field)
Is this file a "deleted" file in a private archive? STUB.
Definition File.php:2202
getTitle()
Return the associated title object.
Definition File.php:378
getTimestamp()
Get the 14-character timestamp of the file upload.
Definition File.php:2432
Foreign file accessible through api.php requests.
This class is a collection of static functions that serve two purposes:
Definition Html.php:44
Create PSR-3 logger objects.
Service locator for MediaWiki core services.
static getInstance()
Returns the global default instance of the top level service locator.
Format Image metadata values into a human readable form.
sanitizeKeyForAPI( $key)
Turns a string into a valid API identifier.
resolveMultilangMetadata(&$metadata)
Takes an array returned by the getExtendedMetadata* functions, and resolves multi-language values in ...
fetchExtendedMetadata(File $file)
Get an array of extended metadata.
bool $singleLang
Only output a single language for multi-language fields.
static getVisibleFields()
Get a list of fields that are visible by default.
collapseContactInfo(array $vals)
Format the contact info field into a single value.
resolveMultilangValue( $value)
Turns an XMP-style multilang array into a single value.
literal( $val)
Convenience function for getFormattedData()
getPriorityLanguages()
Returns a list of languages (first is best) to use when formatting multilang fields,...
flattenArrayReal( $vals, $type='ul', $noHtml=false)
A function to collapse multivalued tags into a single value.
resolveMultivalueValue( $value)
Turns an XMP-style multivalue array into a single value by dropping all but the first value.
sanitizeArrayForAPI(&$arr)
Makes sure the given array is a valid API response fragment.
static getFormattedData( $tags, $context=false)
Numbers given by Exif user agents are often magical, that is they should be replaced by a detailed ex...
getExtendedMetadataFromHook(File $file, array $extendedMetadata, &$maxCacheTime)
Get additional metadata from hooks in standardized format.
getExtendedMetadataFromFile(File $file)
Get file-based metadata in standardized format.
setSingleLanguage( $val)
Trigger only outputting single language for multilanguage fields.
discardMultipleValues(&$metadata)
Takes an array returned by the getExtendedMetadata* functions, and turns all fields into single-value...
makeFormattedData( $tags)
Numbers given by Exif user agents are often magical, that is they should be replaced by a detailed ex...
Interface for objects which can provide a MediaWiki context on request.
msg( $key,... $params)