MediaWiki  master
FormatMetadata.php
Go to the documentation of this file.
1 <?php
28 use MediaWiki\HookContainer\ProtectedHookAccessorTrait;
31 use Wikimedia\Timestamp\TimestampException;
32 
55  use ProtectedHookAccessorTrait;
56 
62  protected $singleLang = false;
63 
70  public function setSingleLanguage( $val ) {
71  $this->singleLang = $val;
72  }
73 
87  public static function getFormattedData( $tags, $context = false ) {
88  $obj = new FormatMetadata;
89  if ( $context ) {
90  $obj->setContext( $context );
91  }
92 
93  return $obj->makeFormattedData( $tags );
94  }
95 
107  public function makeFormattedData( $tags ) {
108  $resolutionunit = !isset( $tags['ResolutionUnit'] ) || $tags['ResolutionUnit'] == 2 ? 2 : 3;
109  unset( $tags['ResolutionUnit'] );
110 
111  // Ignore these complex values
112  unset( $tags['HasExtendedXMP'] );
113  unset( $tags['AuthorsPosition'] );
114  unset( $tags['LocationCreated'] );
115  unset( $tags['LocationShown'] );
116 
117  foreach ( $tags as $tag => &$vals ) {
118  // This seems ugly to wrap non-array's in an array just to unwrap again,
119  // especially when most of the time it is not an array
120  if ( !is_array( $vals ) ) {
121  $vals = [ $vals ];
122  }
123 
124  // _type is a special value to say what array type
125  if ( isset( $vals['_type'] ) ) {
126  $type = $vals['_type'];
127  unset( $vals['_type'] );
128  } else {
129  $type = 'ul'; // default unordered list.
130  }
131 
132  // _formatted is a special value to indicate the subclass
133  // already handled & formatted this tag as wikitext
134  if ( isset( $tags[$tag]['_formatted'] ) ) {
135  $tags[$tag] = $this->flattenArrayReal(
136  $tags[$tag]['_formatted'], $type
137  );
138  continue;
139  }
140 
141  // This is done differently as the tag is an array.
142  if ( $tag == 'GPSTimeStamp' && count( $vals ) === 3 ) {
143  // hour min sec array
144 
145  $h = explode( '/', $vals[0] );
146  $m = explode( '/', $vals[1] );
147  $s = explode( '/', $vals[2] );
148 
149  // this should already be validated
150  // when loaded from file, but it could
151  // come from a foreign repo, so be
152  // paranoid.
153  if ( !isset( $h[1] )
154  || !isset( $m[1] )
155  || !isset( $s[1] )
156  || $h[1] == 0
157  || $m[1] == 0
158  || $s[1] == 0
159  ) {
160  continue;
161  }
162  $vals = str_pad( intval( $h[0] / $h[1] ), 2, '0', STR_PAD_LEFT )
163  . ':' . str_pad( intval( $m[0] / $m[1] ), 2, '0', STR_PAD_LEFT )
164  . ':' . str_pad( intval( $s[0] / $s[1] ), 2, '0', STR_PAD_LEFT );
165 
166  try {
167  $time = wfTimestamp( TS_MW, '1971:01:01 ' . $vals );
168  // the 1971:01:01 is just a placeholder, and not shown to user.
169  if ( $time && intval( $time ) > 0 ) {
170  $vals = $this->getLanguage()->time( $time );
171  }
172  } catch ( TimestampException $e ) {
173  // This shouldn't happen, but we've seen bad formats
174  // such as 4-digit seconds in the wild.
175  // leave $vals as-is
176  }
177  continue;
178  }
179 
180  // The contact info is a multi-valued field
181  // instead of the other props which are single
182  // valued (mostly) so handle as a special case.
183  if ( $tag === 'Contact' || $tag === 'CreatorContactInfo' ) {
184  $vals = $this->collapseContactInfo( $vals );
185  continue;
186  }
187 
188  foreach ( $vals as &$val ) {
189  switch ( $tag ) {
190  case 'Compression':
191  switch ( $val ) {
192  case 1:
193  case 2:
194  case 3:
195  case 4:
196  case 5:
197  case 6:
198  case 7:
199  case 8:
200  case 32773:
201  case 32946:
202  case 34712:
203  $val = $this->exifMsg( $tag, $val );
204  break;
205  default:
206  /* If not recognized, display as is. */
207  $val = $this->literal( $val );
208  break;
209  }
210  break;
211 
212  case 'PhotometricInterpretation':
213  switch ( $val ) {
214  case 0:
215  case 1:
216  case 2:
217  case 3:
218  case 4:
219  case 5:
220  case 6:
221  case 8:
222  case 9:
223  case 10:
224  case 32803:
225  case 34892:
226  $val = $this->exifMsg( $tag, $val );
227  break;
228  default:
229  /* If not recognized, display as is. */
230  $val = $this->literal( $val );
231  break;
232  }
233  break;
234 
235  case 'Orientation':
236  switch ( $val ) {
237  case 1:
238  case 2:
239  case 3:
240  case 4:
241  case 5:
242  case 6:
243  case 7:
244  case 8:
245  $val = $this->exifMsg( $tag, $val );
246  break;
247  default:
248  /* If not recognized, display as is. */
249  $val = $this->literal( $val );
250  break;
251  }
252  break;
253 
254  case 'PlanarConfiguration':
255  switch ( $val ) {
256  case 1:
257  case 2:
258  $val = $this->exifMsg( $tag, $val );
259  break;
260  default:
261  /* If not recognized, display as is. */
262  $val = $this->literal( $val );
263  break;
264  }
265  break;
266 
267  // TODO: YCbCrSubSampling
268  case 'YCbCrPositioning':
269  switch ( $val ) {
270  case 1:
271  case 2:
272  $val = $this->exifMsg( $tag, $val );
273  break;
274  default:
275  /* If not recognized, display as is. */
276  $val = $this->literal( $val );
277  break;
278  }
279  break;
280 
281  case 'XResolution':
282  case 'YResolution':
283  switch ( $resolutionunit ) {
284  case 2:
285  $val = $this->exifMsg( 'XYResolution', 'i', $this->formatNum( $val ) );
286  break;
287  case 3:
288  $val = $this->exifMsg( 'XYResolution', 'c', $this->formatNum( $val ) );
289  break;
290  default:
291  /* If not recognized, display as is. */
292  $val = $this->literal( $val );
293  break;
294  }
295  break;
296 
297  // TODO: YCbCrCoefficients #p27 (see annex E)
298  case 'ExifVersion':
299  // PHP likes to be the odd one out with casing of FlashPixVersion;
300  // https://www.exif.org/Exif2-2.PDF#page=32 and
301  // https://www.digitalgalen.net/Documents/External/XMP/XMPSpecificationPart2.pdf#page=51
302  // both use FlashpixVersion. However, since at least 2002, PHP has used FlashPixVersion at
303  // https://github.com/php/php-src/blame/master/ext/exif/exif.c#L725
304  case 'FlashPixVersion':
305  // But we can still get the correct casing from
306  // Wikimedia\XMPReader on PDFs
307  case 'FlashpixVersion':
308  $val = $this->literal( (int)$val / 100 );
309  break;
310 
311  case 'ColorSpace':
312  switch ( $val ) {
313  case 1:
314  case 65535:
315  $val = $this->exifMsg( $tag, $val );
316  break;
317  default:
318  /* If not recognized, display as is. */
319  $val = $this->literal( $val );
320  break;
321  }
322  break;
323 
324  case 'ComponentsConfiguration':
325  switch ( $val ) {
326  case 0:
327  case 1:
328  case 2:
329  case 3:
330  case 4:
331  case 5:
332  case 6:
333  $val = $this->exifMsg( $tag, $val );
334  break;
335  default:
336  /* If not recognized, display as is. */
337  $val = $this->literal( $val );
338  break;
339  }
340  break;
341 
342  case 'DateTime':
343  case 'DateTimeOriginal':
344  case 'DateTimeDigitized':
345  case 'DateTimeReleased':
346  case 'DateTimeExpires':
347  case 'GPSDateStamp':
348  case 'dc-date':
349  case 'DateTimeMetadata':
350  case 'FirstPhotoDate':
351  case 'LastPhotoDate':
352  if ( $val == '0000:00:00 00:00:00' || $val == ' : : : : ' ) {
353  $val = $this->msg( 'exif-unknowndate' )->text();
354  break;
355  } elseif ( preg_match(
356  '/^(?:\d{4}):(?:\d\d):(?:\d\d) (?:\d\d):(?:\d\d):(?:\d\d)$/D',
357  $val
358  ) ) {
359  // Full date.
360  $time = wfTimestamp( TS_MW, $val );
361  if ( $time && intval( $time ) > 0 ) {
362  $val = $this->getLanguage()->timeanddate( $time );
363  break;
364  }
365  } elseif ( preg_match( '/^(?:\d{4}):(?:\d\d):(?:\d\d) (?:\d\d):(?:\d\d)$/D', $val ) ) {
366  // No second field. Still format the same
367  // since timeanddate doesn't include seconds anyways,
368  // but second still available in api
369  $time = wfTimestamp( TS_MW, $val . ':00' );
370  if ( $time && intval( $time ) > 0 ) {
371  $val = $this->getLanguage()->timeanddate( $time );
372  break;
373  }
374  } elseif ( preg_match( '/^(?:\d{4}):(?:\d\d):(?:\d\d)$/D', $val ) ) {
375  // If only the date but not the time is filled in.
376  $time = wfTimestamp( TS_MW, substr( $val, 0, 4 )
377  . substr( $val, 5, 2 )
378  . substr( $val, 8, 2 )
379  . '000000' );
380  if ( $time && intval( $time ) > 0 ) {
381  $val = $this->getLanguage()->date( $time );
382  break;
383  }
384  }
385  // else it will just output $val without formatting it.
386  $val = $this->literal( $val );
387  break;
388 
389  case 'ExposureProgram':
390  switch ( $val ) {
391  case 0:
392  case 1:
393  case 2:
394  case 3:
395  case 4:
396  case 5:
397  case 6:
398  case 7:
399  case 8:
400  $val = $this->exifMsg( $tag, $val );
401  break;
402  default:
403  /* If not recognized, display as is. */
404  $val = $this->literal( $val );
405  break;
406  }
407  break;
408 
409  case 'SubjectDistance':
410  $val = $this->exifMsg( $tag, '', $this->formatNum( $val ) );
411  break;
412 
413  case 'MeteringMode':
414  switch ( $val ) {
415  case 0:
416  case 1:
417  case 2:
418  case 3:
419  case 4:
420  case 5:
421  case 6:
422  case 7:
423  case 255:
424  $val = $this->exifMsg( $tag, $val );
425  break;
426  default:
427  /* If not recognized, display as is. */
428  $val = $this->literal( $val );
429  break;
430  }
431  break;
432 
433  case 'LightSource':
434  switch ( $val ) {
435  case 0:
436  case 1:
437  case 2:
438  case 3:
439  case 4:
440  case 9:
441  case 10:
442  case 11:
443  case 12:
444  case 13:
445  case 14:
446  case 15:
447  case 17:
448  case 18:
449  case 19:
450  case 20:
451  case 21:
452  case 22:
453  case 23:
454  case 24:
455  case 255:
456  $val = $this->exifMsg( $tag, $val );
457  break;
458  default:
459  /* If not recognized, display as is. */
460  $val = $this->literal( $val );
461  break;
462  }
463  break;
464 
465  case 'Flash':
466  $flashDecode = [
467  'fired' => $val & 0b00000001,
468  'return' => ( $val & 0b00000110 ) >> 1,
469  'mode' => ( $val & 0b00011000 ) >> 3,
470  'function' => ( $val & 0b00100000 ) >> 5,
471  'redeye' => ( $val & 0b01000000 ) >> 6,
472  // 'reserved' => ( $val & 0b10000000 ) >> 7,
473  ];
474  $flashMsgs = [];
475  # We do not need to handle unknown values since all are used.
476  foreach ( $flashDecode as $subTag => $subValue ) {
477  # We do not need any message for zeroed values.
478  if ( $subTag != 'fired' && $subValue == 0 ) {
479  continue;
480  }
481  $fullTag = $tag . '-' . $subTag;
482  $flashMsgs[] = $this->exifMsg( $fullTag, $subValue );
483  }
484  $val = $this->getLanguage()->commaList( $flashMsgs );
485  break;
486 
487  case 'FocalPlaneResolutionUnit':
488  switch ( $val ) {
489  case 2:
490  $val = $this->exifMsg( $tag, $val );
491  break;
492  default:
493  /* If not recognized, display as is. */
494  $val = $this->literal( $val );
495  break;
496  }
497  break;
498 
499  case 'SensingMethod':
500  switch ( $val ) {
501  case 1:
502  case 2:
503  case 3:
504  case 4:
505  case 5:
506  case 7:
507  case 8:
508  $val = $this->exifMsg( $tag, $val );
509  break;
510  default:
511  /* If not recognized, display as is. */
512  $val = $this->literal( $val );
513  break;
514  }
515  break;
516 
517  case 'FileSource':
518  switch ( $val ) {
519  case 3:
520  $val = $this->exifMsg( $tag, $val );
521  break;
522  default:
523  /* If not recognized, display as is. */
524  $val = $this->literal( $val );
525  break;
526  }
527  break;
528 
529  case 'SceneType':
530  switch ( $val ) {
531  case 1:
532  $val = $this->exifMsg( $tag, $val );
533  break;
534  default:
535  /* If not recognized, display as is. */
536  $val = $this->literal( $val );
537  break;
538  }
539  break;
540 
541  case 'CustomRendered':
542  switch ( $val ) {
543  case 0: /* normal */
544  case 1: /* custom */
545  /* The following are unofficial Apple additions */
546  case 2: /* HDR (no original saved) */
547  case 3: /* HDR (original saved) */
548  case 4: /* Original (for HDR) */
549  /* Yes 5 is not present ;) */
550  case 6: /* Panorama */
551  case 7: /* Portrait HDR */
552  case 8: /* Portrait */
553  $val = $this->exifMsg( $tag, $val );
554  break;
555  default:
556  /* If not recognized, display as is. */
557  $val = $this->literal( $val );
558  break;
559  }
560  break;
561 
562  case 'ExposureMode':
563  switch ( $val ) {
564  case 0:
565  case 1:
566  case 2:
567  $val = $this->exifMsg( $tag, $val );
568  break;
569  default:
570  /* If not recognized, display as is. */
571  break;
572  }
573  break;
574 
575  case 'WhiteBalance':
576  switch ( $val ) {
577  case 0:
578  case 1:
579  $val = $this->exifMsg( $tag, $val );
580  break;
581  default:
582  /* If not recognized, display as is. */
583  $val = $this->literal( $val );
584  break;
585  }
586  break;
587 
588  case 'SceneCaptureType':
589  switch ( $val ) {
590  case 0:
591  case 1:
592  case 2:
593  case 3:
594  $val = $this->exifMsg( $tag, $val );
595  break;
596  default:
597  /* If not recognized, display as is. */
598  $val = $this->literal( $val );
599  break;
600  }
601  break;
602 
603  case 'GainControl':
604  switch ( $val ) {
605  case 0:
606  case 1:
607  case 2:
608  case 3:
609  case 4:
610  $val = $this->exifMsg( $tag, $val );
611  break;
612  default:
613  /* If not recognized, display as is. */
614  $val = $this->literal( $val );
615  break;
616  }
617  break;
618 
619  case 'Contrast':
620  switch ( $val ) {
621  case 0:
622  case 1:
623  case 2:
624  $val = $this->exifMsg( $tag, $val );
625  break;
626  default:
627  /* If not recognized, display as is. */
628  $val = $this->literal( $val );
629  break;
630  }
631  break;
632 
633  case 'Saturation':
634  switch ( $val ) {
635  case 0:
636  case 1:
637  case 2:
638  $val = $this->exifMsg( $tag, $val );
639  break;
640  default:
641  /* If not recognized, display as is. */
642  $val = $this->literal( $val );
643  break;
644  }
645  break;
646 
647  case 'Sharpness':
648  switch ( $val ) {
649  case 0:
650  case 1:
651  case 2:
652  $val = $this->exifMsg( $tag, $val );
653  break;
654  default:
655  /* If not recognized, display as is. */
656  $val = $this->literal( $val );
657  break;
658  }
659  break;
660 
661  case 'SubjectDistanceRange':
662  switch ( $val ) {
663  case 0:
664  case 1:
665  case 2:
666  case 3:
667  $val = $this->exifMsg( $tag, $val );
668  break;
669  default:
670  /* If not recognized, display as is. */
671  $val = $this->literal( $val );
672  break;
673  }
674  break;
675 
676  // The GPS...Ref values are kept for compatibility, probably won't be reached.
677  case 'GPSLatitudeRef':
678  case 'GPSDestLatitudeRef':
679  switch ( $val ) {
680  case 'N':
681  case 'S':
682  $val = $this->exifMsg( 'GPSLatitude', $val );
683  break;
684  default:
685  /* If not recognized, display as is. */
686  $val = $this->literal( $val );
687  break;
688  }
689  break;
690 
691  case 'GPSLongitudeRef':
692  case 'GPSDestLongitudeRef':
693  switch ( $val ) {
694  case 'E':
695  case 'W':
696  $val = $this->exifMsg( 'GPSLongitude', $val );
697  break;
698  default:
699  /* If not recognized, display as is. */
700  $val = $this->literal( $val );
701  break;
702  }
703  break;
704 
705  case 'GPSAltitude':
706  if ( $val < 0 ) {
707  $val = $this->exifMsg( 'GPSAltitude', 'below-sealevel', $this->formatNum( -$val, 3 ) );
708  } else {
709  $val = $this->exifMsg( 'GPSAltitude', 'above-sealevel', $this->formatNum( $val, 3 ) );
710  }
711  break;
712 
713  case 'GPSStatus':
714  switch ( $val ) {
715  case 'A':
716  case 'V':
717  $val = $this->exifMsg( $tag, $val );
718  break;
719  default:
720  /* If not recognized, display as is. */
721  $val = $this->literal( $val );
722  break;
723  }
724  break;
725 
726  case 'GPSMeasureMode':
727  switch ( $val ) {
728  case 2:
729  case 3:
730  $val = $this->exifMsg( $tag, $val );
731  break;
732  default:
733  /* If not recognized, display as is. */
734  $val = $this->literal( $val );
735  break;
736  }
737  break;
738 
739  case 'GPSTrackRef':
740  case 'GPSImgDirectionRef':
741  case 'GPSDestBearingRef':
742  switch ( $val ) {
743  case 'T':
744  case 'M':
745  $val = $this->exifMsg( 'GPSDirection', $val );
746  break;
747  default:
748  /* If not recognized, display as is. */
749  $val = $this->literal( $val );
750  break;
751  }
752  break;
753 
754  case 'GPSLatitude':
755  case 'GPSDestLatitude':
756  $val = $this->formatCoords( $val, 'latitude' );
757  break;
758  case 'GPSLongitude':
759  case 'GPSDestLongitude':
760  $val = $this->formatCoords( $val, 'longitude' );
761  break;
762 
763  case 'GPSSpeedRef':
764  switch ( $val ) {
765  case 'K':
766  case 'M':
767  case 'N':
768  $val = $this->exifMsg( 'GPSSpeed', $val );
769  break;
770  default:
771  /* If not recognized, display as is. */
772  $val = $this->literal( $val );
773  break;
774  }
775  break;
776 
777  case 'GPSDestDistanceRef':
778  switch ( $val ) {
779  case 'K':
780  case 'M':
781  case 'N':
782  $val = $this->exifMsg( 'GPSDestDistance', $val );
783  break;
784  default:
785  /* If not recognized, display as is. */
786  $val = $this->literal( $val );
787  break;
788  }
789  break;
790 
791  case 'GPSDOP':
792  // See https://en.wikipedia.org/wiki/Dilution_of_precision_(GPS)
793  if ( $val <= 2 ) {
794  $val = $this->exifMsg( $tag, 'excellent', $this->formatNum( $val ) );
795  } elseif ( $val <= 5 ) {
796  $val = $this->exifMsg( $tag, 'good', $this->formatNum( $val ) );
797  } elseif ( $val <= 10 ) {
798  $val = $this->exifMsg( $tag, 'moderate', $this->formatNum( $val ) );
799  } elseif ( $val <= 20 ) {
800  $val = $this->exifMsg( $tag, 'fair', $this->formatNum( $val ) );
801  } else {
802  $val = $this->exifMsg( $tag, 'poor', $this->formatNum( $val ) );
803  }
804  break;
805 
806  // This is not in the Exif standard, just a special
807  // case for our purposes which enables wikis to wikify
808  // the make, model and software name to link to their articles.
809  case 'Make':
810  case 'Model':
811  $val = $this->exifMsg( $tag, '', $this->literal( $val ) );
812  break;
813 
814  case 'Software':
815  if ( is_array( $val ) ) {
816  if ( count( $val ) > 1 ) {
817  // if its a software, version array.
818  $val = $this->msg(
819  'exif-software-version-value',
820  $this->literal( $val[0] ),
821  $this->literal( $val[1] )
822  )->text();
823  } else {
824  // https://phabricator.wikimedia.org/T178130
825  $val = $this->exifMsg( $tag, '', $this->literal( $val[0] ) );
826  }
827  } else {
828  $val = $this->exifMsg( $tag, '', $this->literal( $val ) );
829  }
830  break;
831 
832  case 'ExposureTime':
833  // Show the pretty fraction as well as decimal version
834  $val = $this->msg( 'exif-exposuretime-format',
835  $this->formatFraction( $val ), $this->formatNum( $val ) )->text();
836  break;
837  case 'ISOSpeedRatings':
838  // If its = 65535 that means its at the
839  // limit of the size of Exif::short and
840  // is really higher.
841  if ( $val == '65535' ) {
842  $val = $this->exifMsg( $tag, 'overflow' );
843  } else {
844  $val = $this->formatNum( $val );
845  }
846  break;
847  case 'FNumber':
848  $val = $this->msg( 'exif-fnumber-format',
849  $this->formatNum( $val ) )->text();
850  break;
851 
852  case 'FocalLength':
853  case 'FocalLengthIn35mmFilm':
854  $val = $this->msg( 'exif-focallength-format',
855  $this->formatNum( $val ) )->text();
856  break;
857 
858  case 'MaxApertureValue':
859  if ( strpos( $val, '/' ) !== false ) {
860  // need to expand this earlier to calculate fNumber
861  list( $n, $d ) = explode( '/', $val );
862  if ( is_numeric( $n ) && is_numeric( $d ) ) {
863  $val = $n / $d;
864  }
865  }
866  if ( is_numeric( $val ) ) {
867  $fNumber = 2 ** ( $val / 2 );
868  if ( is_finite( $fNumber ) ) {
869  $val = $this->msg( 'exif-maxaperturevalue-value',
870  $this->formatNum( $val ),
871  $this->formatNum( $fNumber, 2 )
872  )->text();
873  break;
874  }
875  }
876  $val = $this->literal( $val );
877  break;
878 
879  case 'iimCategory':
880  switch ( strtolower( $val ) ) {
881  // See pg 29 of IPTC photo
882  // metadata standard.
883  case 'ace':
884  case 'clj':
885  case 'dis':
886  case 'fin':
887  case 'edu':
888  case 'evn':
889  case 'hth':
890  case 'hum':
891  case 'lab':
892  case 'lif':
893  case 'pol':
894  case 'rel':
895  case 'sci':
896  case 'soi':
897  case 'spo':
898  case 'war':
899  case 'wea':
900  $val = $this->exifMsg(
901  'iimcategory',
902  $val
903  );
904  default:
905  $val = $this->literal( $val );
906  }
907  break;
908  case 'SubjectNewsCode':
909  // Essentially like iimCategory.
910  // 8 (numeric) digit hierarchical
911  // classification. We decode the
912  // first 2 digits, which provide
913  // a broad category.
914  $val = $this->convertNewsCode( $val );
915  break;
916  case 'Urgency':
917  // 1-8 with 1 being highest, 5 normal
918  // 0 is reserved, and 9 is 'user-defined'.
919  $urgency = '';
920  if ( $val == 0 || $val == 9 ) {
921  $urgency = 'other';
922  } elseif ( $val < 5 && $val > 1 ) {
923  $urgency = 'high';
924  } elseif ( $val == 5 ) {
925  $urgency = 'normal';
926  } elseif ( $val <= 8 && $val > 5 ) {
927  $urgency = 'low';
928  }
929 
930  if ( $urgency !== '' ) {
931  $val = $this->exifMsg( 'urgency',
932  $urgency, $this->literal( $val )
933  );
934  } else {
935  $val = $this->literal( $val );
936  }
937  break;
938 
939  // Things that have a unit of pixels.
940  case 'OriginalImageHeight':
941  case 'OriginalImageWidth':
942  case 'PixelXDimension':
943  case 'PixelYDimension':
944  case 'ImageWidth':
945  case 'ImageLength':
946  $val = $this->formatNum( $val ) . ' ' . $this->msg( 'unit-pixel' )->text();
947  break;
948 
949  // Do not transform fields with pure text.
950  // For some languages the formatNum()
951  // conversion results to wrong output like
952  // foo,bar@example,com or foo٫bar@example٫com.
953  // Also some 'numeric' things like Scene codes
954  // are included here as we really don't want
955  // commas inserted.
956  case 'ImageDescription':
957  case 'UserComment':
958  case 'Artist':
959  case 'Copyright':
960  case 'RelatedSoundFile':
961  case 'ImageUniqueID':
962  case 'SpectralSensitivity':
963  case 'GPSSatellites':
964  case 'GPSVersionID':
965  case 'GPSMapDatum':
966  case 'Keywords':
967  case 'WorldRegionDest':
968  case 'CountryDest':
969  case 'CountryCodeDest':
970  case 'ProvinceOrStateDest':
971  case 'CityDest':
972  case 'SublocationDest':
973  case 'WorldRegionCreated':
974  case 'CountryCreated':
975  case 'CountryCodeCreated':
976  case 'ProvinceOrStateCreated':
977  case 'CityCreated':
978  case 'SublocationCreated':
979  case 'ObjectName':
980  case 'SpecialInstructions':
981  case 'Headline':
982  case 'Credit':
983  case 'Source':
984  case 'EditStatus':
985  case 'FixtureIdentifier':
986  case 'LocationDest':
987  case 'LocationDestCode':
988  case 'Writer':
989  case 'JPEGFileComment':
990  case 'iimSupplementalCategory':
991  case 'OriginalTransmissionRef':
992  case 'Identifier':
993  case 'dc-contributor':
994  case 'dc-coverage':
995  case 'dc-publisher':
996  case 'dc-relation':
997  case 'dc-rights':
998  case 'dc-source':
999  case 'dc-type':
1000  case 'Lens':
1001  case 'SerialNumber':
1002  case 'CameraOwnerName':
1003  case 'Label':
1004  case 'Nickname':
1005  case 'RightsCertificate':
1006  case 'CopyrightOwner':
1007  case 'UsageTerms':
1008  case 'WebStatement':
1009  case 'OriginalDocumentID':
1010  case 'LicenseUrl':
1011  case 'MorePermissionsUrl':
1012  case 'AttributionUrl':
1013  case 'PreferredAttributionName':
1014  case 'PNGFileComment':
1015  case 'Disclaimer':
1016  case 'ContentWarning':
1017  case 'GIFFileComment':
1018  case 'SceneCode':
1019  case 'IntellectualGenre':
1020  case 'Event':
1021  case 'OrganisationInImage':
1022  case 'PersonInImage':
1023  case 'CaptureSoftware':
1024  case 'GPSAreaInformation':
1025  case 'GPSProcessingMethod':
1026  case 'StitchingSoftware':
1027  case 'SubSecTime':
1028  case 'SubSecTimeOriginal':
1029  case 'SubSecTimeDigitized':
1030  $val = $this->literal( $val );
1031  break;
1032 
1033  case 'ProjectionType':
1034  switch ( $val ) {
1035  case 'equirectangular':
1036  $val = $this->exifMsg( $tag, $val );
1037  break;
1038  default:
1039  $val = $this->literal( $val );
1040  break;
1041  }
1042  break;
1043  case 'ObjectCycle':
1044  switch ( $val ) {
1045  case 'a':
1046  case 'p':
1047  case 'b':
1048  $val = $this->exifMsg( $tag, $val );
1049  break;
1050  default:
1051  $val = $this->literal( $val );
1052  break;
1053  }
1054  break;
1055  case 'Copyrighted':
1056  case 'UsePanoramaViewer':
1057  case 'ExposureLockUsed':
1058  switch ( $val ) {
1059  case 'True':
1060  case 'False':
1061  $val = $this->exifMsg( $tag, $val );
1062  break;
1063  default:
1064  $val = $this->literal( $val );
1065  break;
1066  }
1067  break;
1068  case 'Rating':
1069  if ( $val == '-1' ) {
1070  $val = $this->exifMsg( $tag, 'rejected' );
1071  } else {
1072  $val = $this->formatNum( $val );
1073  }
1074  break;
1075 
1076  case 'LanguageCode':
1077  $lang = MediaWikiServices::getInstance()
1078  ->getLanguageNameUtils()
1079  ->getLanguageName( strtolower( $val ), $this->getLanguage()->getCode() );
1080  $val = $this->literal( $lang ?: $val );
1081  break;
1082 
1083  default:
1084  $val = $this->formatNum( $val, false, $tag );
1085  break;
1086  }
1087  }
1088  // End formatting values, start flattening arrays.
1089  $vals = $this->flattenArrayReal( $vals, $type );
1090  }
1091 
1092  return $tags;
1093  }
1094 
1113  public static function flattenArrayContentLang( $vals, $type = 'ul',
1114  $noHtml = false, $context = false
1115  ) {
1116  // Allow $noHtml to be omitted.
1117  if ( $noHtml instanceof IContextSource ) {
1118  $context = $noHtml;
1119  $noHtml = false;
1120  }
1121  if ( $noHtml ) {
1122  wfDeprecated( __METHOD__ . ' with $noHtml = true', '1.36' );
1123  }
1124  $obj = new FormatMetadata;
1125  if ( $context ) {
1126  $obj->setContext( $context );
1127  }
1128  $context = new DerivativeContext( $obj->getContext() );
1129  $context->setLanguage( MediaWikiServices::getInstance()->getContentLanguage() );
1130  $obj->setContext( $context );
1131 
1132  return $obj->flattenArrayReal( $vals, $type, $noHtml );
1133  }
1134 
1152  public function flattenArrayReal( $vals, $type = 'ul', $noHtml = false ) {
1153  if ( !is_array( $vals ) ) {
1154  return $vals; // do nothing if not an array;
1155  }
1156 
1157  if ( isset( $vals['_type'] ) ) {
1158  $type = $vals['_type'];
1159  unset( $vals['_type'] );
1160  }
1161 
1162  if ( count( $vals ) === 1 && $type !== 'lang' && isset( $vals[0] ) ) {
1163  return $vals[0];
1164  } elseif ( count( $vals ) === 0 ) {
1165  wfDebug( __METHOD__ . " metadata array with 0 elements!" );
1166 
1167  return ""; // paranoia. This should never happen
1168  } else {
1169  /* @todo FIXME: This should hide some of the list entries if there are
1170  * say more than four. Especially if a field is translated into 20
1171  * languages, we don't want to show them all by default
1172  */
1173  switch ( $type ) {
1174  case 'lang':
1175  // Display default, followed by ContentLanguage,
1176  // followed by the rest in no particular
1177  // order.
1178 
1179  // Todo: hide some items if really long list.
1180 
1181  $content = '';
1182 
1183  $priorityLanguages = $this->getPriorityLanguages();
1184  $defaultItem = false;
1185  $defaultLang = false;
1186 
1187  // If default is set, save it for later,
1188  // as we don't know if it's equal to
1189  // one of the lang codes. (In xmp
1190  // you specify the language for a
1191  // default property by having both
1192  // a default prop, and one in the language
1193  // that are identical)
1194  if ( isset( $vals['x-default'] ) ) {
1195  $defaultItem = $vals['x-default'];
1196  unset( $vals['x-default'] );
1197  }
1198  foreach ( $priorityLanguages as $pLang ) {
1199  if ( isset( $vals[$pLang] ) ) {
1200  $isDefault = false;
1201  if ( $vals[$pLang] === $defaultItem ) {
1202  $defaultItem = false;
1203  $isDefault = true;
1204  }
1205  $content .= $this->langItem(
1206  $vals[$pLang], $pLang,
1207  $isDefault, $noHtml );
1208 
1209  unset( $vals[$pLang] );
1210 
1211  if ( $this->singleLang ) {
1212  return Html::rawElement( 'span',
1213  [ 'lang' => $pLang ], $vals[$pLang] );
1214  }
1215  }
1216  }
1217 
1218  // Now do the rest.
1219  foreach ( $vals as $lang => $item ) {
1220  if ( $item === $defaultItem ) {
1221  $defaultLang = $lang;
1222  continue;
1223  }
1224  $content .= $this->langItem( $item,
1225  $lang, false, $noHtml );
1226  if ( $this->singleLang ) {
1227  return Html::rawElement( 'span',
1228  [ 'lang' => $lang ], $item );
1229  }
1230  }
1231  if ( $defaultItem !== false ) {
1232  $content = $this->langItem( $defaultItem,
1233  $defaultLang, true, $noHtml ) .
1234  $content;
1235  if ( $this->singleLang ) {
1236  return $defaultItem;
1237  }
1238  }
1239  if ( $noHtml ) {
1240  return $content;
1241  }
1242 
1243  return '<ul class="metadata-langlist">' .
1244  $content .
1245  '</ul>';
1246  case 'ol':
1247  if ( $noHtml ) {
1248  return "\n#" . implode( "\n#", $vals );
1249  }
1250 
1251  return "<ol><li>" . implode( "</li>\n<li>", $vals ) . '</li></ol>';
1252  case 'ul':
1253  default:
1254  if ( $noHtml ) {
1255  return "\n*" . implode( "\n*", $vals );
1256  }
1257 
1258  return "<ul><li>" . implode( "</li>\n<li>", $vals ) . '</li></ul>';
1259  }
1260  }
1261  }
1262 
1273  private function langItem( $value, $lang, $default = false, $noHtml = false ) {
1274  if ( $lang === false && $default === false ) {
1275  throw new MWException( '$lang and $default cannot both '
1276  . 'be false.' );
1277  }
1278 
1279  if ( $noHtml ) {
1280  $wrappedValue = $this->literal( $value );
1281  } else {
1282  $wrappedValue = '<span class="mw-metadata-lang-value">'
1283  . $this->literal( $value ) . '</span>';
1284  }
1285 
1286  if ( $lang === false ) {
1287  $msg = $this->msg( 'metadata-langitem-default', $wrappedValue );
1288  if ( $noHtml ) {
1289  return $msg->text() . "\n\n";
1290  } /* else */
1291 
1292  return '<li class="mw-metadata-lang-default">'
1293  . $msg->text()
1294  . "</li>\n";
1295  }
1296 
1297  $lowLang = strtolower( $lang );
1298  $languageNameUtils = MediaWikiServices::getInstance()->getLanguageNameUtils();
1299  $langName = $languageNameUtils->getLanguageName( $lowLang );
1300  if ( $langName === '' ) {
1301  // try just the base language name. (aka en-US -> en ).
1302  $langPrefix = explode( '-', $lowLang, 2 )[0];
1303  $langName = $languageNameUtils->getLanguageName( $langPrefix );
1304  if ( $langName === '' ) {
1305  // give up.
1306  $langName = $lang;
1307  }
1308  }
1309  // else we have a language specified
1310 
1311  $msg = $this->msg( 'metadata-langitem', $wrappedValue, $langName, $lang );
1312  if ( $noHtml ) {
1313  return '*' . $msg->text();
1314  } /* else: */
1315 
1316  $item = '<li class="mw-metadata-lang-code-'
1317  . $lang;
1318  if ( $default ) {
1319  $item .= ' mw-metadata-lang-default';
1320  }
1321  $item .= '" lang="' . $lang . '">';
1322  $item .= $msg->text();
1323  $item .= "</li>\n";
1324 
1325  return $item;
1326  }
1327 
1335  protected function literal( $val ) {
1336  // T266707: historically this has used htmlspecialchars to protect
1337  // the string contents, but it should probably be changed to use
1338  // wfEscapeWikitext() instead -- however, "we still want to auto-link
1339  // urls" so wfEscapeWikitext isn't *quite* right...
1340  return htmlspecialchars( $val );
1341  }
1342 
1352  private function exifMsg( $tag, $val, $arg = null, $arg2 = null ) {
1353  if ( $val === '' ) {
1354  $val = 'value';
1355  }
1356 
1357  return $this->msg(
1358  MediaWikiServices::getInstance()->getContentLanguage()->lc( "exif-$tag-$val" ),
1359  $arg,
1360  $arg2
1361  )->text();
1362  }
1363 
1373  private function formatNum( $num, $round = false, $tagName = null ) {
1374  $m = [];
1375  if ( is_array( $num ) ) {
1376  $out = [];
1377  foreach ( $num as $number ) {
1378  $out[] = $this->formatNum( $number, $round, $tagName );
1379  }
1380 
1381  return $this->getLanguage()->commaList( $out );
1382  }
1383  if ( is_numeric( $num ) ) {
1384  if ( $round !== false ) {
1385  $num = round( $num, $round );
1386  }
1387  return $this->getLanguage()->formatNum( $num );
1388  }
1389  if ( preg_match( '/^(-?\d+)\/(\d+)$/', $num, $m ) ) {
1390  if ( $m[2] != 0 ) {
1391  $newNum = $m[1] / $m[2];
1392  if ( $round !== false ) {
1393  $newNum = round( $newNum, $round );
1394  }
1395  } else {
1396  $newNum = $num;
1397  }
1398 
1399  return $this->getLanguage()->formatNum( $newNum );
1400  }
1401  # T267370: there are a lot of strange EXIF tags floating around.
1402  LoggerFactory::getInstance( 'formatnum' )->warning(
1403  'FormatMetadata::formatNum with non-numeric value',
1404  [
1405  'tag' => $tagName,
1406  'value' => $num,
1407  ]
1408  );
1409  return $this->literal( $num );
1410  }
1411 
1418  private function formatFraction( $num ) {
1419  $m = [];
1420  if ( preg_match( '/^(-?\d+)\/(\d+)$/', $num, $m ) ) {
1421  $numerator = intval( $m[1] );
1422  $denominator = intval( $m[2] );
1423  $gcd = $this->gcd( abs( $numerator ), $denominator );
1424  if ( $gcd != 0 ) {
1425  // 0 shouldn't happen! ;)
1426  return $this->formatNum( $numerator / $gcd ) . '/' . $this->formatNum( $denominator / $gcd );
1427  }
1428  }
1429 
1430  return $this->formatNum( $num );
1431  }
1432 
1440  private function gcd( $a, $b ) {
1441  /*
1442  // https://en.wikipedia.org/wiki/Euclidean_algorithm
1443  // Recursive form would be:
1444  if( $b == 0 )
1445  return $a;
1446  else
1447  return gcd( $b, $a % $b );
1448  */
1449  while ( $b != 0 ) {
1450  $remainder = $a % $b;
1451 
1452  // tail recursion...
1453  $a = $b;
1454  $b = $remainder;
1455  }
1456 
1457  return $a;
1458  }
1459 
1472  private function convertNewsCode( $val ) {
1473  if ( !preg_match( '/^\d{8}$/D', $val ) ) {
1474  // Not a valid news code.
1475  return $val;
1476  }
1477  $cat = '';
1478  switch ( substr( $val, 0, 2 ) ) {
1479  case '01':
1480  $cat = 'ace';
1481  break;
1482  case '02':
1483  $cat = 'clj';
1484  break;
1485  case '03':
1486  $cat = 'dis';
1487  break;
1488  case '04':
1489  $cat = 'fin';
1490  break;
1491  case '05':
1492  $cat = 'edu';
1493  break;
1494  case '06':
1495  $cat = 'evn';
1496  break;
1497  case '07':
1498  $cat = 'hth';
1499  break;
1500  case '08':
1501  $cat = 'hum';
1502  break;
1503  case '09':
1504  $cat = 'lab';
1505  break;
1506  case '10':
1507  $cat = 'lif';
1508  break;
1509  case '11':
1510  $cat = 'pol';
1511  break;
1512  case '12':
1513  $cat = 'rel';
1514  break;
1515  case '13':
1516  $cat = 'sci';
1517  break;
1518  case '14':
1519  $cat = 'soi';
1520  break;
1521  case '15':
1522  $cat = 'spo';
1523  break;
1524  case '16':
1525  $cat = 'war';
1526  break;
1527  case '17':
1528  $cat = 'wea';
1529  break;
1530  }
1531  if ( $cat !== '' ) {
1532  $catMsg = $this->exifMsg( 'iimcategory', $cat );
1533  $val = $this->exifMsg( 'subjectnewscode', '', $this->literal( $val ), $catMsg );
1534  }
1535 
1536  return $val;
1537  }
1538 
1547  private function formatCoords( $coord, string $type ) {
1548  if ( !is_numeric( $coord ) ) {
1549  wfDebugLog( 'exif', __METHOD__ . ": \"$coord\" is not a number" );
1550  return $this->literal( (string)$coord );
1551  }
1552 
1553  $ref = '';
1554  if ( $coord < 0 ) {
1555  $nCoord = -$coord;
1556  if ( $type === 'latitude' ) {
1557  $ref = 'S';
1558  } elseif ( $type === 'longitude' ) {
1559  $ref = 'W';
1560  }
1561  } else {
1562  $nCoord = (float)$coord;
1563  if ( $type === 'latitude' ) {
1564  $ref = 'N';
1565  } elseif ( $type === 'longitude' ) {
1566  $ref = 'E';
1567  }
1568  }
1569 
1570  $deg = floor( $nCoord );
1571  $min = floor( ( $nCoord - $deg ) * 60 );
1572  $sec = round( ( ( $nCoord - $deg ) * 60 - $min ) * 60, 2 );
1573 
1574  $deg = $this->formatNum( $deg );
1575  $min = $this->formatNum( $min );
1576  $sec = $this->formatNum( $sec );
1577 
1578  // Note the default message "$1° $2′ $3″ $4" ignores the 5th parameter
1579  return $this->msg( 'exif-coordinate-format', $deg, $min, $sec, $ref, $this->literal( $coord ) )->text();
1580  }
1581 
1596  public function collapseContactInfo( array $vals ) {
1597  if ( !( isset( $vals['CiAdrExtadr'] )
1598  || isset( $vals['CiAdrCity'] )
1599  || isset( $vals['CiAdrCtry'] )
1600  || isset( $vals['CiEmailWork'] )
1601  || isset( $vals['CiTelWork'] )
1602  || isset( $vals['CiAdrPcode'] )
1603  || isset( $vals['CiAdrRegion'] )
1604  || isset( $vals['CiUrlWork'] )
1605  ) ) {
1606  // We don't have any sub-properties
1607  // This could happen if its using old
1608  // iptc that just had this as a free-form
1609  // text value.
1610  // Note: people often insert >, etc into
1611  // the metadata which should not be interpreted
1612  // but we still want to auto-link urls.
1613  foreach ( $vals as &$val ) {
1614  $val = $this->literal( $val );
1615  }
1616 
1617  return $this->flattenArrayReal( $vals );
1618  } else {
1619  // We have a real ContactInfo field.
1620  // Its unclear if all these fields have to be
1621  // set, so assume they do not.
1622  $url = $tel = $street = $city = $country = '';
1623  $email = $postal = $region = '';
1624 
1625  // Also note, some of the class names this uses
1626  // are similar to those used by hCard. This is
1627  // mostly because they're sensible names. This
1628  // does not (and does not attempt to) output
1629  // stuff in the hCard microformat. However it
1630  // might output in the adr microformat.
1631 
1632  if ( isset( $vals['CiAdrExtadr'] ) ) {
1633  // Todo: This can potentially be multi-line.
1634  // Need to check how that works in XMP.
1635  $street = '<span class="extended-address">'
1636  . $this->literal(
1637  $vals['CiAdrExtadr'] )
1638  . '</span>';
1639  }
1640  if ( isset( $vals['CiAdrCity'] ) ) {
1641  $city = '<span class="locality">'
1642  . $this->literal( $vals['CiAdrCity'] )
1643  . '</span>';
1644  }
1645  if ( isset( $vals['CiAdrCtry'] ) ) {
1646  $country = '<span class="country-name">'
1647  . $this->literal( $vals['CiAdrCtry'] )
1648  . '</span>';
1649  }
1650  if ( isset( $vals['CiEmailWork'] ) ) {
1651  $emails = [];
1652  // Have to split multiple emails at commas/new lines.
1653  $splitEmails = explode( "\n", $vals['CiEmailWork'] );
1654  foreach ( $splitEmails as $e1 ) {
1655  // Also split on comma
1656  foreach ( explode( ',', $e1 ) as $e2 ) {
1657  $finalEmail = trim( $e2 );
1658  if ( $finalEmail == ',' || $finalEmail == '' ) {
1659  continue;
1660  }
1661  if ( strpos( $finalEmail, '<' ) !== false ) {
1662  // Don't do fancy formatting to
1663  // "My name" <foo@bar.com> style stuff
1664  $emails[] = $this->literal( $finalEmail );
1665  } else {
1666  $emails[] = '[mailto:'
1667  . $finalEmail
1668  . ' <span class="email">'
1669  . $this->literal( $finalEmail )
1670  . '</span>]';
1671  }
1672  }
1673  }
1674  $email = implode( ', ', $emails );
1675  }
1676  if ( isset( $vals['CiTelWork'] ) ) {
1677  $tel = '<span class="tel">'
1678  . $this->literal( $vals['CiTelWork'] )
1679  . '</span>';
1680  }
1681  if ( isset( $vals['CiAdrPcode'] ) ) {
1682  $postal = '<span class="postal-code">'
1683  . $this->literal(
1684  $vals['CiAdrPcode'] )
1685  . '</span>';
1686  }
1687  if ( isset( $vals['CiAdrRegion'] ) ) {
1688  // Note this is province/state.
1689  $region = '<span class="region">'
1690  . $this->literal(
1691  $vals['CiAdrRegion'] )
1692  . '</span>';
1693  }
1694  if ( isset( $vals['CiUrlWork'] ) ) {
1695  $url = '<span class="url">'
1696  . $this->literal( $vals['CiUrlWork'] )
1697  . '</span>';
1698  }
1699 
1700  return $this->msg( 'exif-contact-value', $email, $url,
1701  $street, $city, $region, $postal, $country,
1702  $tel )->text();
1703  }
1704  }
1705 
1712  public static function getVisibleFields() {
1713  $fields = [];
1714  $lines = explode( "\n", wfMessage( 'metadata-fields' )->inContentLanguage()->text() );
1715  foreach ( $lines as $line ) {
1716  $matches = [];
1717  if ( preg_match( '/^\\*\s*(.*?)\s*$/', $line, $matches ) ) {
1718  $fields[] = $matches[1];
1719  }
1720  }
1721  $fields = array_map( 'strtolower', $fields );
1722 
1723  return $fields;
1724  }
1725 
1733  public function fetchExtendedMetadata( File $file ) {
1734  $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1735 
1736  // If revision deleted, exit immediately
1737  if ( $file->isDeleted( File::DELETED_FILE ) ) {
1738  return [];
1739  }
1740 
1741  $cacheKey = $cache->makeKey(
1742  'getExtendedMetadata',
1743  $this->getLanguage()->getCode(),
1744  (int)$this->singleLang,
1745  $file->getSha1()
1746  );
1747 
1748  $cachedValue = $cache->get( $cacheKey );
1749  if (
1750  $cachedValue
1751  && $this->getHookRunner()->onValidateExtendedMetadataCache( $cachedValue['timestamp'], $file )
1752  ) {
1753  $extendedMetadata = $cachedValue['data'];
1754  } else {
1755  $maxCacheTime = ( $file instanceof ForeignAPIFile ) ? 60 * 60 * 12 : 60 * 60 * 24 * 30;
1756  $fileMetadata = $this->getExtendedMetadataFromFile( $file );
1757  $extendedMetadata = $this->getExtendedMetadataFromHook( $file, $fileMetadata, $maxCacheTime );
1758  if ( $this->singleLang ) {
1759  $this->resolveMultilangMetadata( $extendedMetadata );
1760  }
1761  $this->discardMultipleValues( $extendedMetadata );
1762  // Make sure the metadata won't break the API when an XML format is used.
1763  // This is an API-specific function so it would be cleaner to call it from
1764  // outside fetchExtendedMetadata, but this way we don't need to redo the
1765  // computation on a cache hit.
1766  $this->sanitizeArrayForAPI( $extendedMetadata );
1767  $valueToCache = [ 'data' => $extendedMetadata, 'timestamp' => wfTimestampNow() ];
1768  $cache->set( $cacheKey, $valueToCache, $maxCacheTime );
1769  }
1770 
1771  return $extendedMetadata;
1772  }
1773 
1783  protected function getExtendedMetadataFromFile( File $file ) {
1784  // If this is a remote file accessed via an API request, we already
1785  // have remote metadata so we just ignore any local one
1786  if ( $file instanceof ForeignAPIFile ) {
1787  // In case of error we pretend no metadata - this will get cached.
1788  // Might or might not be a good idea.
1789  return $file->getExtendedMetadata() ?: [];
1790  }
1791 
1792  $uploadDate = wfTimestamp( TS_ISO_8601, $file->getTimestamp() );
1793 
1794  $fileMetadata = [
1795  // This is modification time, which is close to "upload" time.
1796  'DateTime' => [
1797  'value' => $uploadDate,
1798  'source' => 'mediawiki-metadata',
1799  ],
1800  ];
1801 
1802  $title = $file->getTitle();
1803  if ( $title ) {
1804  $text = $title->getText();
1805  $pos = strrpos( $text, '.' );
1806 
1807  if ( $pos ) {
1808  $name = substr( $text, 0, $pos );
1809  } else {
1810  $name = $text;
1811  }
1812 
1813  $fileMetadata['ObjectName'] = [
1814  'value' => $name,
1815  'source' => 'mediawiki-metadata',
1816  ];
1817  }
1818 
1819  return $fileMetadata;
1820  }
1821 
1832  protected function getExtendedMetadataFromHook( File $file, array $extendedMetadata,
1833  &$maxCacheTime
1834  ) {
1835  $this->getHookRunner()->onGetExtendedMetadata(
1836  $extendedMetadata,
1837  $file,
1838  $this->getContext(),
1839  $this->singleLang,
1840  $maxCacheTime
1841  );
1842 
1843  $visible = array_flip( self::getVisibleFields() );
1844  foreach ( $extendedMetadata as $key => $value ) {
1845  if ( !isset( $visible[strtolower( $key )] ) ) {
1846  $extendedMetadata[$key]['hidden'] = '';
1847  }
1848  }
1849 
1850  return $extendedMetadata;
1851  }
1852 
1861  protected function resolveMultilangValue( $value ) {
1862  if (
1863  !is_array( $value )
1864  || !isset( $value['_type'] )
1865  || $value['_type'] != 'lang'
1866  ) {
1867  return $value; // do nothing if not a multilang array
1868  }
1869 
1870  // choose the language best matching user or site settings
1871  $priorityLanguages = $this->getPriorityLanguages();
1872  foreach ( $priorityLanguages as $lang ) {
1873  if ( isset( $value[$lang] ) ) {
1874  return $value[$lang];
1875  }
1876  }
1877 
1878  // otherwise go with the default language, if set
1879  if ( isset( $value['x-default'] ) ) {
1880  return $value['x-default'];
1881  }
1882 
1883  // otherwise just return any one language
1884  unset( $value['_type'] );
1885  if ( !empty( $value ) ) {
1886  return reset( $value );
1887  }
1888 
1889  // this should not happen; signal error
1890  return null;
1891  }
1892 
1902  protected function resolveMultivalueValue( $value ) {
1903  if ( !is_array( $value ) ) {
1904  return $value;
1905  } elseif ( isset( $value['_type'] ) && $value['_type'] === 'lang' ) {
1906  // if this is a multilang array, process fields separately
1907  $newValue = [];
1908  foreach ( $value as $k => $v ) {
1909  $newValue[$k] = $this->resolveMultivalueValue( $v );
1910  }
1911  return $newValue;
1912  } else { // _type is 'ul' or 'ol' or missing in which case it defaults to 'ul'
1913  $v = reset( $value );
1914  if ( key( $value ) === '_type' ) {
1915  $v = next( $value );
1916  }
1917  return $v;
1918  }
1919  }
1920 
1927  protected function resolveMultilangMetadata( &$metadata ) {
1928  if ( !is_array( $metadata ) ) {
1929  return;
1930  }
1931  foreach ( $metadata as &$field ) {
1932  if ( isset( $field['value'] ) ) {
1933  $field['value'] = $this->resolveMultilangValue( $field['value'] );
1934  }
1935  }
1936  }
1937 
1944  protected function discardMultipleValues( &$metadata ) {
1945  if ( !is_array( $metadata ) ) {
1946  return;
1947  }
1948  foreach ( $metadata as $key => &$field ) {
1949  if ( $key === 'Software' || $key === 'Contact' ) {
1950  // we skip some fields which have composite values. They are not particularly interesting
1951  // and you can get them via the metadata / commonmetadata APIs anyway.
1952  continue;
1953  }
1954  if ( isset( $field['value'] ) ) {
1955  $field['value'] = $this->resolveMultivalueValue( $field['value'] );
1956  }
1957  }
1958  }
1959 
1964  protected function sanitizeArrayForAPI( &$arr ) {
1965  if ( !is_array( $arr ) ) {
1966  return;
1967  }
1968 
1969  $counter = 1;
1970  foreach ( $arr as $key => &$value ) {
1971  $sanitizedKey = $this->sanitizeKeyForAPI( $key );
1972  if ( $sanitizedKey !== $key ) {
1973  if ( isset( $arr[$sanitizedKey] ) ) {
1974  // Make the sanitized keys hopefully unique.
1975  // To make it definitely unique would be too much effort, given that
1976  // sanitizing is only needed for misformatted metadata anyway, but
1977  // this at least covers the case when $arr is numeric.
1978  $sanitizedKey .= $counter;
1979  ++$counter;
1980  }
1981  $arr[$sanitizedKey] = $arr[$key];
1982  unset( $arr[$key] );
1983  }
1984  if ( is_array( $value ) ) {
1985  $this->sanitizeArrayForAPI( $value );
1986  }
1987  }
1988 
1989  // Handle API metadata keys (particularly "_type")
1990  $keys = array_filter( array_keys( $arr ), 'ApiResult::isMetadataKey' );
1991  if ( $keys ) {
1993  }
1994  }
1995 
2002  protected function sanitizeKeyForAPI( $key ) {
2003  // drop all characters which are not valid in an XML tag name
2004  // a bunch of non-ASCII letters would be valid but probably won't
2005  // be used so we take the easy way
2006  $key = preg_replace( '/[^a-zA-z0-9_:.\-]/', '', $key );
2007  // drop characters which are invalid at the first position
2008  $key = preg_replace( '/^[\d\-.]+/', '', $key );
2009 
2010  if ( $key === '' ) {
2011  $key = '_';
2012  // special case for an internal keyword
2013  } elseif ( $key === '_element' ) {
2014  $key = 'element';
2015  }
2016 
2017  return $key;
2018  }
2019 
2026  protected function getPriorityLanguages() {
2027  $priorityLanguages = MediaWikiServices::getInstance()
2028  ->getLanguageFallback()
2029  ->getAllIncludingSiteLanguage( $this->getLanguage()->getCode() );
2030  $priorityLanguages = array_merge(
2031  (array)$this->getLanguage()->getCode(),
2032  $priorityLanguages[0],
2033  $priorityLanguages[1]
2034  );
2035 
2036  return $priorityLanguages;
2037  }
2038 }
ContextSource\$context
IContextSource $context
Definition: ContextSource.php:37
ContextSource\getContext
getContext()
Get the base IContextSource object.
Definition: ContextSource.php:45
FormatMetadata\formatNum
formatNum( $num, $round=false, $tagName=null)
Format a number, convert numbers from fractions into floating point numbers, joins arrays of numbers ...
Definition: FormatMetadata.php:1373
FormatMetadata\sanitizeKeyForAPI
sanitizeKeyForAPI( $key)
Turns a string into a valid API identifier.
Definition: FormatMetadata.php:2002
FormatMetadata\gcd
gcd( $a, $b)
Calculate the greatest common divisor of two integers.
Definition: FormatMetadata.php:1440
FormatMetadata\getFormattedData
static getFormattedData( $tags, $context=false)
Numbers given by Exif user agents are often magical, that is they should be replaced by a detailed ex...
Definition: FormatMetadata.php:87
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:165
$lang
if(!isset( $args[0])) $lang
Definition: testCompression.php:37
FormatMetadata\collapseContactInfo
collapseContactInfo(array $vals)
Format the contact info field into a single value.
Definition: FormatMetadata.php:1596
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1815
FormatMetadata\fetchExtendedMetadata
fetchExtendedMetadata(File $file)
Get an array of extended metadata.
Definition: FormatMetadata.php:1733
$file
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42
wfMessage
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Definition: GlobalFunctions.php:1220
$s
$s
Definition: mergeMessageFileList.php:184
FormatMetadata\literal
literal( $val)
Convenience function for getFormattedData()
Definition: FormatMetadata.php:1335
FormatMetadata\getExtendedMetadataFromFile
getExtendedMetadataFromFile(File $file)
Get file-based metadata in standardized format.
Definition: FormatMetadata.php:1783
wfDebugLog
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
Definition: GlobalFunctions.php:989
FormatMetadata\formatFraction
formatFraction( $num)
Format a rational number, reducing fractions.
Definition: FormatMetadata.php:1418
FormatMetadata\setSingleLanguage
setSingleLanguage( $val)
Trigger only outputting single language for multilanguage fields.
Definition: FormatMetadata.php:70
ContextSource\getLanguage
getLanguage()
Definition: ContextSource.php:143
DerivativeContext
An IContextSource implementation which will inherit context from another source but allow individual ...
Definition: DerivativeContext.php:31
FormatMetadata\discardMultipleValues
discardMultipleValues(&$metadata)
Takes an array returned by the getExtendedMetadata* functions, and turns all fields into single-value...
Definition: FormatMetadata.php:1944
FormatMetadata\convertNewsCode
convertNewsCode( $val)
Fetch the human readable version of a news code.
Definition: FormatMetadata.php:1472
File
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition: File.php:63
MWException
MediaWiki exception.
Definition: MWException.php:29
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that $function is deprecated.
Definition: GlobalFunctions.php:1027
MediaWiki\Logger\LoggerFactory
PSR-3 logger instance factory.
Definition: LoggerFactory.php:45
FormatMetadata\resolveMultivalueValue
resolveMultivalueValue( $value)
Turns an XMP-style multivalue array into a single value by dropping all but the first value.
Definition: FormatMetadata.php:1902
FormatMetadata\getPriorityLanguages
getPriorityLanguages()
Returns a list of languages (first is best) to use when formatting multilang fields,...
Definition: FormatMetadata.php:2026
FormatMetadata\langItem
langItem( $value, $lang, $default=false, $noHtml=false)
Helper function for creating lists of translations.
Definition: FormatMetadata.php:1273
$matches
$matches
Definition: NoLocalSettings.php:24
ContextSource
The simplest way of implementing IContextSource is to hold a RequestContext as a member variable and ...
Definition: ContextSource.php:31
FormatMetadata\getExtendedMetadataFromHook
getExtendedMetadataFromHook(File $file, array $extendedMetadata, &$maxCacheTime)
Get additional metadata from hooks in standardized format.
Definition: FormatMetadata.php:1832
$title
$title
Definition: testCompression.php:38
wfTimestampNow
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
Definition: GlobalFunctions.php:1844
wfDebug
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:910
ContextSource\setContext
setContext(IContextSource $context)
Definition: ContextSource.php:61
ContextSource\msg
msg( $key,... $params)
Get a Message object with context set Parameters are the same as wfMessage()
Definition: ContextSource.php:187
$content
$content
Definition: router.php:76
FormatMetadata\$singleLang
bool $singleLang
Only output a single language for multi-language fields.
Definition: FormatMetadata.php:62
$line
$line
Definition: mcc.php:119
FormatMetadata\flattenArrayContentLang
static flattenArrayContentLang( $vals, $type='ul', $noHtml=false, $context=false)
Flatten an array, using the content language for any messages.
Definition: FormatMetadata.php:1113
$lines
if(!file_exists( $CREDITS)) $lines
Definition: updateCredits.php:49
IContextSource
Interface for objects which can provide a MediaWiki context on request.
Definition: IContextSource.php:55
FormatMetadata
Format Image metadata values into a human readable form.
Definition: FormatMetadata.php:54
FormatMetadata\exifMsg
exifMsg( $tag, $val, $arg=null, $arg2=null)
Convenience function for getFormattedData()
Definition: FormatMetadata.php:1352
FormatMetadata\sanitizeArrayForAPI
sanitizeArrayForAPI(&$arr)
Makes sure the given array is a valid API response fragment.
Definition: FormatMetadata.php:1964
ApiResult\setPreserveKeysList
static setPreserveKeysList(array &$arr, $names)
Preserve specified keys.
Definition: ApiResult.php:662
FormatMetadata\resolveMultilangMetadata
resolveMultilangMetadata(&$metadata)
Takes an array returned by the getExtendedMetadata* functions, and resolves multi-language values in ...
Definition: FormatMetadata.php:1927
$cache
$cache
Definition: mcc.php:33
Html\rawElement
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:212
$keys
$keys
Definition: testCompression.php:72
FormatMetadata\flattenArrayReal
flattenArrayReal( $vals, $type='ul', $noHtml=false)
A function to collapse multivalued tags into a single value.
Definition: FormatMetadata.php:1152
File\DELETED_FILE
const DELETED_FILE
Definition: File.php:67
FormatMetadata\formatCoords
formatCoords( $coord, string $type)
Format a coordinate value, convert numbers from floating point into degree minute second representati...
Definition: FormatMetadata.php:1547
ForeignAPIFile
Foreign file accessible through api.php requests.
Definition: ForeignAPIFile.php:32
FormatMetadata\getVisibleFields
static getVisibleFields()
Get a list of fields that are visible by default.
Definition: FormatMetadata.php:1712
FormatMetadata\resolveMultilangValue
resolveMultilangValue( $value)
Turns an XMP-style multilang array into a single value.
Definition: FormatMetadata.php:1861
FormatMetadata\makeFormattedData
makeFormattedData( $tags)
Numbers given by Exif user agents are often magical, that is they should be replaced by a detailed ex...
Definition: FormatMetadata.php:107
$type
$type
Definition: testCompression.php:52