Clean up makeFlatExifTags; a simple foreach loop is a little easier on the
[lhc/web/wiklou.git] / includes / Exif.php
1 <?php
2 if (defined('MEDIAWIKI')) {
3 /**
4 * @package MediaWiki
5 * @subpackage Metadata
6 *
7 * @author Ævar Arnfjörð Bjarmason <avarab@gmail.com>
8 * @copyright Copyright © 2005, Ævar Arnfjörð Bjarmason
9 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License along
22 * with this program; if not, write to the Free Software Foundation, Inc.,
23 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
24 * http://www.gnu.org/copyleft/gpl.html
25 *
26 * @link http://exif.org/Exif2-2.PDF The Exif 2.2 specification
27 * @bug 1555, 1947
28 */
29
30 /**
31 * @package MediaWiki
32 * @subpackage Metadata
33 */
34 class Exif {
35 /**#@+
36 * @var array
37 */
38
39 /**
40 * Exif tags grouped by category, the tagname itself is the key and the type
41 * is the value, in the case of more than one possible value type they are
42 * seperated by commas.
43 *
44 * @access private
45 */
46 var $mExif;
47
48 /**
49 * A one dimentional array of all Exif tags
50 */
51 var $mFlatExif;
52
53 /**
54 * A one dimentional array of all Exif tags that we'd want to save in
55 * the database or present on a page.
56 */
57 var $mValidExif;
58
59 /**#@-*/
60
61 /**
62 * Constructor
63 */
64 function Exif() {
65 /**#@+
66 * Exif tag type definition
67 */
68 define('BYTE', 1); # An 8-bit unsigned integer.
69 define('ASCII', 2); # An 8-bit byte containing one 7-bit ASCII code. The final byte is terminated with NULL.
70 define('SHORT', 3); # A 16-bit (2-byte) unsigned integer.
71 define('LONG', 4); # A 32-bit (4-byte) unsigned integer.
72 define('RATIONAL', 5); # Two LONGs. The first LONG is the numerator and the second LONG expresses the denominator
73 define('UNDEFINED', 7); # An 8-bit byte that can take any value depending on the field definition
74 define('SLONG', 9); # A 32-bit (4-byte) signed integer (2's complement notation),
75 define('SRATIONAL', 10); # Two SLONGs. The first SLONG is the numerator and the second SLONG is the denominator.
76 /**#@-*/
77
78 /**
79 * Page numbers here refer to pages in the EXIF 2.2 standard
80 *
81 * @link http://exif.org/Exif2-2.PDF The Exif 2.2 specification
82 */
83 $this->mExif = array(
84 # TIFF Rev. 6.0 Attribute Information (p22)
85 'tiff' => array(
86 # Tags relating to image structure
87 'structure' => array(
88 'ImageWidth' => SHORT.','.LONG, # Image width
89 'ImageLength' => SHORT.','.LONG, # Image height
90 'BitsPerSample' => SHORT, # Number of bits per component
91 # "When a primary image is JPEG compressed, this designation is not"
92 # "necessary and is omitted." (p23)
93 'Compression' => SHORT, # Compression scheme #p23
94 'PhotometricInterpretation' => SHORT, # Pixel composition #p23
95 'Orientation' => SHORT, # Orientation of image #p24
96 'SamplesPerPixel' => SHORT, # Number of components
97 'PlanarConfiguration' => SHORT, # Image data arrangement #p24
98 'YCbCrSubSampling' => SHORT, # Subsampling ratio of Y to C #p24
99 'YCbCrPositioning' => SHORT, # Y and C positioning #p24-25
100 'XResolution' => RATIONAL, # Image resolution in width direction
101 'YResolution' => RATIONAL, # Image resolution in height direction
102 'ResolutionUnit' => SHORT, # Unit of X and Y resolution #(p26)
103 ),
104
105 # Tags relating to recording offset
106 'offset' => array(
107 'StripOffsets' => SHORT.','.LONG, # Image data location
108 'RowsPerStrip' => SHORT.','.LONG, # Number of rows per strip
109 'StripByteCounts' => SHORT.','.LONG, # Bytes per compressed strip
110 'JPEGInterchangeFormat' => SHORT.','.LONG, # Offset to JPEG SOI
111 'JPEGInterchangeFormatLength' => SHORT.','.LONG, # Bytes of JPEG data
112 ),
113
114 # Tags relating to image data characteristics
115 'characteristics' => array(
116 'TransferFunction' => SHORT, # Transfer function
117 'WhitePoint' => RATIONAL, # White point chromaticity
118 'PrimaryChromaticities' => RATIONAL, # Chromaticities of primarities
119 'YCbCrCoefficients' => RATIONAL, # Color space transformation matrix coefficients #p27
120 'ReferenceBlackWhite' => RATIONAL # Pair of black and white reference values
121 ),
122
123 # Other tags
124 'other' => array(
125 'DateTime' => ASCII, # File change date and time
126 'ImageDescription' => ASCII, # Image title
127 'Make' => ASCII, # Image input equipment manufacturer
128 'Model' => ASCII, # Image input equipment model
129 'Software' => ASCII, # Software used
130 'Artist' => ASCII, # Person who created the image
131 'Copyright' => ASCII, # Copyright holder
132 ),
133 ),
134
135 # Exif IFD Attribute Information (p30-31)
136 'exif' => array(
137 # Tags relating to version
138 'version' => array(
139 # TODO: NOTE: Nonexistence of this field is taken to mean nonconformance
140 # to the EXIF 2.1 AND 2.2 standards
141 'ExifVersion' => UNDEFINED, # Exif version
142 'FlashpixVersion' => UNDEFINED, # Supported Flashpix version #p32
143 ),
144
145 # Tags relating to Image Data Characteristics
146 'characteristics' => array(
147 'ColorSpace' => SHORT, # Color space information #p32
148 ),
149
150 # Tags relating to image configuration
151 'configuration' => array(
152 'ComponentsConfiguration' => UNDEFINED, # Meaning of each component #p33
153 'CompressedBitsPerPixel' => RATIONAL, # Image compression mode
154 'PixelYDimension' => SHORT.','.LONG, # Valid image width
155 'PixelXDimension' => SHORT.','.LONG, # Valind image height
156 ),
157
158 # Tags relating to related user information
159 'user' => array(
160 'MakerNote' => UNDEFINED, # Manufacturer notes
161 'UserComment' => UNDEFINED, # User comments #p34
162 ),
163
164 # Tags relating to related file information
165 'related' => array(
166 'RelatedSoundFile' => ASCII, # Related audio file
167 ),
168
169 # Tags relating to date and time
170 'dateandtime' => array(
171 'DateTimeOriginal' => ASCII, # Date and time of original data generation #p36
172 'DateTimeDigitized' => ASCII, # Date and time of original data generation
173 'SubSecTime' => ASCII, # DateTime subseconds
174 'SubSecTimeOriginal' => ASCII, # DateTimeOriginal subseconds
175 'SubSecTimeDigitized' => ASCII, # DateTimeDigitized subseconds
176 ),
177
178 # Tags relating to picture-taking conditions (p31)
179 'conditions' => array(
180 'ExposureTime' => RATIONAL, # Exposure time
181 'FNumber' => RATIONAL, # F Number
182 'ExposureProgram' => SHORT, # Exposure Program #p38
183 'SpectralSensitivity' => ASCII, # Spectral sensitivity
184 'ISOSpeedRatings' => SHORT, # ISO speed rating
185 'OECF' => UNDEFINED, # Optoelectronic conversion factor
186 'ShutterSpeedValue' => SRATIONAL, # Shutter speed
187 'ApertureValue' => RATIONAL, # Aperture
188 'BrightnessValue' => SRATIONAL, # Brightness
189 'ExposureBiasValue' => SRATIONAL, # Exposure bias
190 'MaxApertureValue' => RATIONAL, # Maximum land aperture
191 'SubjectDistance' => RATIONAL, # Subject distance
192 'MeteringMode' => SHORT, # Metering mode #p40
193 'LightSource' => SHORT, # Light source #p40-41
194 'Flash' => SHORT, # Flash #p41-42
195 'FocalLength' => RATIONAL, # Lens focal length
196 'SubjectArea' => SHORT, # Subject area
197 'FlashEnergy' => RATIONAL, # Flash energy
198 'SpatialFrequencyResponse' => UNDEFINED, # Spatial frequency response
199 'FocalPlaneXResolution' => RATIONAL, # Focal plane X resolution
200 'FocalPlaneYResolution' => RATIONAL, # Focal plane Y resolution
201 'FocalPlaneResolutionUnit' => SHORT, # Focal plane resolution unit
202 'SubjectLocation' => SHORT, # Subject location
203 'ExposureIndex' => RATIONAL, # Exposure index
204 'SensingMethod' => SHORT, # Sensing method #p46
205 'FileSource' => UNDEFINED, # File source #p47
206 'SceneType' => UNDEFINED, # Scene type #p47
207 'CFAPattern' => UNDEFINED, # CFA pattern
208 'CustomRendered' => SHORT, # Custom image processing #p48
209 'ExposureMode' => SHORT, # Exposure mode #p48
210 'WhiteBalance' => SHORT, # White Balance #p49
211 'DigitalZoomRatio' => RATIONAL, # Digital zoom ration
212 'FocalLengthIn35mmFilm' => SHORT, # Focal length in 35 mm film
213 'SceneCaptureType' => SHORT, # Scene capture type #p49
214 'GainControl' => RATIONAL, # Scene control #p49-50
215 'Contrast' => SHORT, # Contrast #p50
216 'Saturation' => SHORT, # Saturation #p50
217 'Sharpness' => SHORT, # Sharpness #p50
218 'DeviceSettingDescription' => UNDEFINED, # Desice settings description
219 'SubjectDistanceRange' => SHORT, # Subject distance range #p51
220 ),
221
222 'other' => array(
223 'ImageUniqueID' => ASCII, # Unique image ID
224 ),
225 ),
226
227 # GPS Attribute Information (p52)
228 'gps' => array(
229 'GPSVersionID' => BYTE, # GPS tag version
230 'GPSLatitudeRef' => ASCII, # North or South Latitude #p52-53
231 'GPSLatitude' => RATIONAL, # Latitude
232 'GPSLongitudeRef' => ASCII, # East or West Longitude #p53
233 'GPSLongitude' => RATIONAL, # Longitude
234 'GPSAltitudeRef' => BYTE, # Altitude reference
235 'GPSAltitude' => RATIONAL, # Altitude
236 'GPSTimeStamp' => RATIONAL, # GPS time (atomic clock)
237 'GPSSatellites' => ASCII, # Satellites used for measurement
238 'GPSStatus' => ASCII, # Receiver status #p54
239 'GPSMeasureMode' => ASCII, # Measurement mode #p54-55
240 'GPSDOP' => RATIONAL, # Measurement precision
241 'GPSSpeedRef' => ASCII, # Speed unit #p55
242 'GPSSpeed' => RATIONAL, # Speed of GPS receiver
243 'GPSTrackRef' => ASCII, # Reference for direction of movement #p55
244 'GPSTrack' => RATIONAL, # Direction of movement
245 'GPSImgDirectionRef' => ASCII, # Reference for direction of image #p56
246 'GPSImgDirection' => RATIONAL, # Direction of image
247 'GPSMapDatum' => ASCII, # Geodetic survey data used
248 'GPSDestLatitudeRef' => ASCII, # Reference for latitude of destination #p56
249 'GPSDestLatitude' => RATIONAL, # Latitude destination
250 'GPSDestLongitudeRef' => ASCII, # Reference for longitude of destination #p57
251 'GPSDestLongitude' => RATIONAL, # Longitude of destination
252 'GPSDestBearingRef' => ASCII, # Reference for bearing of destination #p57
253 'GPSDestBearing' => RATIONAL, # Bearing of destination
254 'GPSDestDistanceRef' => ASCII, # Reference for distance to destination #p57-58
255 'GPSDestDistance' => RATIONAL, # Distance to destination
256 'GPSProcessingMethod' => UNDEFINED, # Name of GPS processing method
257 'GPSAreaInformation' => UNDEFINED, # Name of GPS area
258 'GPSDateStamp' => ASCII, # GPS date
259 'GPSDifferential' => SHORT, # GPS differential correction
260 ),
261 );
262
263 $this->makeFlatExifTags();
264 $this->makeValidExifTags();
265 }
266
267 /**
268 * Get the raw list of exiftags
269 *
270 * @access private
271 * @return array
272 */
273 function getExif() {
274 return $this->mExif;
275 }
276
277 /**
278 * Generate a flat list of the exif tags
279 */
280 function makeFlatExifTags() {
281 $exif = $this->getExif();
282 $this->extractTags( $exif );
283 }
284
285 /**
286 * A recursing extractor function used by makeFlatExifTags()
287 */
288 function extractTags( $tagset ) {
289 foreach( $tagset as $key => $val ) {
290 if( is_array( $val ) ) {
291 $this->extractTags( $val );
292 } else {
293 $this->mFlatExif[$key] = $val;
294 }
295 }
296 }
297
298 /**
299 * Produce a list of all Exif tags appropriate for user output
300 *
301 * Produce a list of all tags that we want to show in output, in order not to
302 * output binary gibberish such as raw thumbnails we strip all tags
303 * with the datatype of UNDEFINED.
304 *
305 * @todo We might actually want to display some of the UNDEFINED
306 * stuff, but we strip it for now.
307 */
308 function makeValidExifTags() {
309 foreach($this->mFlatExif as $key => $val) {
310 if (strpos( $val, (string)UNDEFINED ) !== false)
311 continue;
312 $this->mValidExif[] = $key;
313 }
314 }
315
316 /**
317 * The version of the output format
318 *
319 * Before the actual metadata information is saved in the database we
320 * strip some of it since we don't want to save things like thumbnails
321 * which usually accompany Exif data. This value gets saved in the
322 * database along with the actual Exif data, and if the version in the
323 * database doesn't equal the value returned by this function the Exif
324 * data is regenerated.
325 *
326 * @return int
327 */
328 function version() {
329 return 1; // We don't need no bloddy constants!
330 }
331
332 /**#@+
333 * Validates if a tag value is of the type it should be according to the Exif spec
334 *
335 * @param mixed $in The input value to check
336 * @return bool
337 */
338 function isByte( $in ) {
339 return is_numeric($in) && $in >= 0 && $in <= 255;
340 }
341
342 function isASCII( $in ) {
343 return true; // TODO: FIXME
344 }
345
346 function isShort( $in ) {
347 return is_numeric($in) && $in >= 0 && $in <= 65536;
348 }
349
350 function isLong( $in ) {
351 return is_numeric($in) && $in >= 0 && $in <= 4294967296;
352
353 }
354
355 function isRational( $in ) {
356 $in = explode( '/', $in, 2 );
357 return $this->isLong($in[0]) && $this->isLong($in[1]);
358 }
359
360 function isUndefined( $in ) {
361 return true;
362 }
363
364 function isSlong( $in ) {
365 return $this->isLong( abs( $in ) );
366 }
367
368 function isSrational( $in ) {
369 $in = explode( '/', $in, 2 );
370 return $this->isSlong($in[0]) && $this->isSlong($in[1]);
371 }
372 /**#@-*/
373
374 /**
375 * Validates if a tag has a legal value according to the Exif spec, presumes
376 * that the given tag is valid ( has been checked in advance with
377 * $this->mValidExif )
378 *
379 * @param string $tag The tag to check
380 * @param mixed $val The value of the tag
381 * @return bool
382 */
383 function validate( $tag, $val ) {
384 // Fucks up if not typecast
385 switch((string)$this->mFlatExif[$tag]) {
386 case (string)BYTE:
387 return $this->isByte( $val );
388 case (string)ASCII:
389 return $this->isASCII( $val );
390 case (string)SHORT:
391 return $this->isShort( $val );
392 case (string)LONG:
393 return $this->isLong( $val );
394 case (string)RATIONAL:
395 return $this->isRational( $val );
396 case (string)UNDEFINED:
397 return $this->isUndefined( $val );
398 case (string)SLONG:
399 return $this->isSlong( $val );
400 case (string)SRATIONAL:
401 return $this->isSrational( $val );
402 case (string)SHORT.','.LONG:
403 return $this->isShort( $val ) || $this->isLong( $val );
404 default:
405 wfDebug( "Exif: The tag \"$tag\" had an invalid value: \"$val\"\n" );
406 return false;
407 }
408 }
409
410 /**
411 * Numbers given by Exif user agents are often magical, that is they
412 * should be replaced by a detailed explanation depending on their
413 * value which most of the time are plain integers. This function
414 * formats Exif values into human readable form.
415 *
416 * @param string $tag The tag to be formatted
417 * @param mixed $val The value of the tag
418 * @return string
419 */
420 function format( $tag, $val ) {
421 global $wgLang;
422
423 switch ($tag) {
424 case 'Compression':
425 switch ($val) {
426 case 1: case 6:
427 return $this->msg( $tag, $val );
428 }
429
430 case 'PhotometricInterpretation':
431 switch ($val) {
432 case 2: case 6:
433 return $this->msg( $tag, $val );
434 }
435
436 case 'Orientation':
437 switch ($val) {
438 case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8:
439 return $this->msg( $tag, $val );
440 }
441
442 // TODO: If this field does not exist use 1
443 case 'PlanarConfiguration':
444 switch ($val) {
445 case 1: case 2:
446 return $this->msg( $tag, $val );
447 }
448
449 // TODO: YCbCrSubSampling
450 // TODO: YCbCrPositioning
451 // TODO: If this field does not exists use 2
452 case 'ResolutionUnit': #p26
453 switch ($val) {
454 case 2: case 3:
455 return $this->msg( $tag, $val );
456 }
457
458 // TODO: YCbCrCoefficients #p27 (see annex E)
459 case 'ExifVersion': case 'FlashpixVersion':
460 return "$val"/100;
461
462 case 'ColorSpace':
463 switch ($val) {
464 case 1: case 'FFFF.H':
465 return $this->msg( $tag, $val );
466 }
467
468 case 'ComponentsConfiguration':
469 switch ($val) {
470 case 0: case 1: case 2: case 3: case 4: case 5: case 6:
471 return $this->msg( $tag, $val );
472 }
473
474 case 'DateTime':
475 case 'DateTimeOriginal':
476 case 'DateTimeDigitized':
477 return $wgLang->timeanddate( wfTimestamp(TS_MW, $val) );
478 case 'ExposureProgram':
479 switch ($val) {
480 case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8:
481 return $this->msg( $tag, $val );
482 }
483 case 'MeteringMode':
484 switch ($val) {
485 case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 255:
486 return $this->msg( $tag, $val );
487 }
488 case 'LightSource':
489 switch ($val) {
490 case 0: case 1: case 2: case 3: case 4: case 9: case 10: case 11:
491 case 12: case 13: case 14: case 15: case 17: case 18: case 19: case 20:
492 case 21: case 22: case 23: case 24: case 255:
493 return $this->msg( $tag, $val );
494 }
495 // TODO: Flash
496 case 'SensingMethod':
497 switch ($val) {
498 case 1: case 2: case 3: case 4: case 5: case 7: case 8:
499 return $this->msg( $tag, $val );
500 }
501 case 'FileSource':
502 switch ($val) {
503 case 3:
504 return $this->msg( $tag, $val );
505 }
506 case 'SceneType':
507 switch ($val) {
508 case 1:
509 return $this->msg( $tag, $val );
510 }
511 case 'CustomRendered':
512 switch ($val) {
513 case 0: case 1:
514 return $this->msg( $tag, $val );
515 }
516 case 'ExposureMode':
517 switch ($val) {
518 case 0: case 1: case 2:
519 return $this->msg( $tag, $val );
520 }
521 case 'WhiteBalance':
522 switch ($val) {
523 case 0: case 1:
524 return $this->msg( $tag, $val );
525 }
526 case 'SceneCaptureType':
527 switch ($val) {
528 case 0: case 1: case 2: case 3:
529 return $this->msg( $tag, $val );
530 }
531 case 'GainControl':
532 switch ($val) {
533 case 0: case 1: case 2: case 3: case 4:
534 return $this->msg( $tag, $val );
535 }
536 case 'Contrast':
537 switch ($val) {
538 case 0: case 1: case 2:
539 return $this->msg( $tag, $val );
540 }
541 case 'Saturation':
542 switch ($val) {
543 case 0: case 1: case 2:
544 return $this->msg( $tag, $val );
545 }
546 case 'Sharpness':
547 switch ($val) {
548 case 0: case 1: case 2:
549 return $this->msg( $tag, $val );
550 }
551 case 'SubjectDistanceRange':
552 switch ($val) {
553 case 0: case 1: case 2: case 3:
554 return $this->msg( $tag, $val );
555 }
556 case 'GPSLatitudeRef':
557 switch ($val) {
558 case 'N': case 'S':
559 return $this->msg( $tag, $val );
560 }
561 case 'GPSLongitudeRef':
562 switch ($val) {
563 case 'E': case 'W':
564 return $this->msg( $tag, $val );
565 }
566 case 'GPSStatus':
567 switch ($val) {
568 case 'A': case 'V':
569 return $this->msg( $tag, $val );
570 }
571 case 'GPSMeasureMode':
572 switch ($val) {
573 case 2: case 3:
574 return $this->msg( $tag, $val );
575 }
576 case 'GPSSpeedRef':
577 switch ($val) {
578 case 'K': case 'M': case 'N':
579 return $this->msg( $tag, $val );
580 }
581 case 'GPSTrackRef':
582 switch ($val) {
583 case 'T': case 'M':
584 return $this->msg( $tag, $val );
585 }
586 case 'GPSImgDirectionRef':
587 switch ($val) {
588 case 'T': case 'M':
589 return $this->msg( $tag, $val );
590 }
591 case 'GPSDestLatitudeRef':
592 switch ($val) {
593 case 'N': case 'S':
594 return $this->msg( $tag, $val );
595 }
596 case 'GPSDestLongitudeRef':
597 switch ($val) {
598 case 'E': case 'W':
599 return $this->msg( $tag, $val );
600 }
601 case 'GPSDestBearingRef':
602 switch ($val) {
603 case 'T': case 'M':
604 return $this->msg( $tag, $val );
605 }
606 case 'GPSDateStamp':
607 return $wgLang->date( substr($val, 0, 4) . substr($val, 5, 2) . substr($val, 8, 2) . 000000 );
608
609 // This is not in the Exif standard, just a special
610 // case for our purposes which enables wikis to wikify
611 // the make and model to write articles about them.
612 case 'Make': case 'Model':
613 return wfMsg( strtolower( "exif-$tag-value" ), $val );
614 default:
615 return $val;
616 }
617 }
618
619 /**
620 * Conviniance function for format()
621 *
622 * @param string $tag The tag name to pass on
623 * @param string $val The value of the tag
624 * @return string A wfMsg of "exif-$tag-$val" in lower case
625 */
626 function msg( $tag, $val ) {
627 return wfMsg( strtolower("exif-$tag-$val") );
628 }
629 }
630 } // MEDIAWIKI