Don't look for pipes in the root node.
[lhc/web/wiklou.git] / includes / Exif.php
1 <?php
2 /**
3 * Exif metadata reader
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @ingroup Media
21 * @author Ævar Arnfjörð Bjarmason <avarab@gmail.com>
22 * @copyright Copyright © 2005, Ævar Arnfjörð Bjarmason
23 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
24 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 specification
25 * @file
26 */
27
28 /**
29 * @todo document (e.g. one-sentence class-overview description)
30 * @ingroup Media
31 */
32 class Exif {
33
34 const BYTE = 1; //!< An 8-bit (1-byte) unsigned integer.
35 const ASCII = 2; //!< An 8-bit byte containing one 7-bit ASCII code. The final byte is terminated with NULL.
36 const SHORT = 3; //!< A 16-bit (2-byte) unsigned integer.
37 const LONG = 4; //!< A 32-bit (4-byte) unsigned integer.
38 const RATIONAL = 5; //!< Two LONGs. The first LONG is the numerator and the second LONG expresses the denominator
39 const UNDEFINED = 7; //!< An 8-bit byte that can take any value depending on the field definition
40 const SLONG = 9; //!< A 32-bit (4-byte) signed integer (2's complement notation),
41 const SRATIONAL = 10; //!< Two SLONGs. The first SLONG is the numerator and the second SLONG is the denominator.
42
43 //@{
44 /* @var array
45 * @private
46 */
47
48 /**
49 * Exif tags grouped by category, the tagname itself is the key and the type
50 * is the value, in the case of more than one possible value type they are
51 * separated by commas.
52 */
53 var $mExifTags;
54
55 /**
56 * A one dimentional array of all Exif tags
57 */
58 var $mFlatExifTags;
59
60 /**
61 * The raw Exif data returned by exif_read_data()
62 */
63 var $mRawExifData;
64
65 /**
66 * A Filtered version of $mRawExifData that has been pruned of invalid
67 * tags and tags that contain content they shouldn't contain according
68 * to the Exif specification
69 */
70 var $mFilteredExifData;
71
72 /**
73 * Filtered and formatted Exif data, see FormatExif::getFormattedData()
74 */
75 var $mFormattedExifData;
76
77 //@}
78
79 //@{
80 /* @var string
81 * @private
82 */
83
84 /**
85 * The file being processed
86 */
87 var $file;
88
89 /**
90 * The basename of the file being processed
91 */
92 var $basename;
93
94 /**
95 * The private log to log to, e.g. 'exif'
96 */
97 var $log = false;
98
99 //@}
100
101 /**
102 * Constructor
103 *
104 * @param $file String: filename.
105 */
106 function __construct( $file ) {
107 /**
108 * Page numbers here refer to pages in the EXIF 2.2 standard
109 *
110 * @link http://exif.org/Exif2-2.PDF The Exif 2.2 specification
111 */
112 $this->mExifTags = array(
113 # TIFF Rev. 6.0 Attribute Information (p22)
114 'tiff' => array(
115 # Tags relating to image structure
116 'structure' => array(
117 'ImageWidth' => Exif::SHORT.','.Exif::LONG, # Image width
118 'ImageLength' => Exif::SHORT.','.Exif::LONG, # Image height
119 'BitsPerSample' => Exif::SHORT, # Number of bits per component
120 # "When a primary image is JPEG compressed, this designation is not"
121 # "necessary and is omitted." (p23)
122 'Compression' => Exif::SHORT, # Compression scheme #p23
123 'PhotometricInterpretation' => Exif::SHORT, # Pixel composition #p23
124 'Orientation' => Exif::SHORT, # Orientation of image #p24
125 'SamplesPerPixel' => Exif::SHORT, # Number of components
126 'PlanarConfiguration' => Exif::SHORT, # Image data arrangement #p24
127 'YCbCrSubSampling' => Exif::SHORT, # Subsampling ratio of Y to C #p24
128 'YCbCrPositioning' => Exif::SHORT, # Y and C positioning #p24-25
129 'XResolution' => Exif::RATIONAL, # Image resolution in width direction
130 'YResolution' => Exif::RATIONAL, # Image resolution in height direction
131 'ResolutionUnit' => Exif::SHORT, # Unit of X and Y resolution #(p26)
132 ),
133
134 # Tags relating to recording offset
135 'offset' => array(
136 'StripOffsets' => Exif::SHORT.','.Exif::LONG, # Image data location
137 'RowsPerStrip' => Exif::SHORT.','.Exif::LONG, # Number of rows per strip
138 'StripByteCounts' => Exif::SHORT.','.Exif::LONG, # Bytes per compressed strip
139 'JPEGInterchangeFormat' => Exif::SHORT.','.Exif::LONG, # Offset to JPEG SOI
140 'JPEGInterchangeFormatLength' => Exif::SHORT.','.Exif::LONG, # Bytes of JPEG data
141 ),
142
143 # Tags relating to image data characteristics
144 'characteristics' => array(
145 'TransferFunction' => Exif::SHORT, # Transfer function
146 'WhitePoint' => Exif::RATIONAL, # White point chromaticity
147 'PrimaryChromaticities' => Exif::RATIONAL, # Chromaticities of primarities
148 'YCbCrCoefficients' => Exif::RATIONAL, # Color space transformation matrix coefficients #p27
149 'ReferenceBlackWhite' => Exif::RATIONAL # Pair of black and white reference values
150 ),
151
152 # Other tags
153 'other' => array(
154 'DateTime' => Exif::ASCII, # File change date and time
155 'ImageDescription' => Exif::ASCII, # Image title
156 'Make' => Exif::ASCII, # Image input equipment manufacturer
157 'Model' => Exif::ASCII, # Image input equipment model
158 'Software' => Exif::ASCII, # Software used
159 'Artist' => Exif::ASCII, # Person who created the image
160 'Copyright' => Exif::ASCII, # Copyright holder
161 ),
162 ),
163
164 # Exif IFD Attribute Information (p30-31)
165 'exif' => array(
166 # Tags relating to version
167 'version' => array(
168 # TODO: NOTE: Nonexistence of this field is taken to mean nonconformance
169 # to the EXIF 2.1 AND 2.2 standards
170 'ExifVersion' => Exif::UNDEFINED, # Exif version
171 'FlashpixVersion' => Exif::UNDEFINED, # Supported Flashpix version #p32
172 ),
173
174 # Tags relating to Image Data Characteristics
175 'characteristics' => array(
176 'ColorSpace' => Exif::SHORT, # Color space information #p32
177 ),
178
179 # Tags relating to image configuration
180 'configuration' => array(
181 'ComponentsConfiguration' => Exif::UNDEFINED, # Meaning of each component #p33
182 'CompressedBitsPerPixel' => Exif::RATIONAL, # Image compression mode
183 'PixelYDimension' => Exif::SHORT.','.Exif::LONG, # Valid image width
184 'PixelXDimension' => Exif::SHORT.','.Exif::LONG, # Valind image height
185 ),
186
187 # Tags relating to related user information
188 'user' => array(
189 'MakerNote' => Exif::UNDEFINED, # Manufacturer notes
190 'UserComment' => Exif::UNDEFINED, # User comments #p34
191 ),
192
193 # Tags relating to related file information
194 'related' => array(
195 'RelatedSoundFile' => Exif::ASCII, # Related audio file
196 ),
197
198 # Tags relating to date and time
199 'dateandtime' => array(
200 'DateTimeOriginal' => Exif::ASCII, # Date and time of original data generation #p36
201 'DateTimeDigitized' => Exif::ASCII, # Date and time of original data generation
202 'SubSecTime' => Exif::ASCII, # DateTime subseconds
203 'SubSecTimeOriginal' => Exif::ASCII, # DateTimeOriginal subseconds
204 'SubSecTimeDigitized' => Exif::ASCII, # DateTimeDigitized subseconds
205 ),
206
207 # Tags relating to picture-taking conditions (p31)
208 'conditions' => array(
209 'ExposureTime' => Exif::RATIONAL, # Exposure time
210 'FNumber' => Exif::RATIONAL, # F Number
211 'ExposureProgram' => Exif::SHORT, # Exposure Program #p38
212 'SpectralSensitivity' => Exif::ASCII, # Spectral sensitivity
213 'ISOSpeedRatings' => Exif::SHORT, # ISO speed rating
214 'OECF' => Exif::UNDEFINED, # Optoelectronic conversion factor
215 'ShutterSpeedValue' => Exif::SRATIONAL, # Shutter speed
216 'ApertureValue' => Exif::RATIONAL, # Aperture
217 'BrightnessValue' => Exif::SRATIONAL, # Brightness
218 'ExposureBiasValue' => Exif::SRATIONAL, # Exposure bias
219 'MaxApertureValue' => Exif::RATIONAL, # Maximum land aperture
220 'SubjectDistance' => Exif::RATIONAL, # Subject distance
221 'MeteringMode' => Exif::SHORT, # Metering mode #p40
222 'LightSource' => Exif::SHORT, # Light source #p40-41
223 'Flash' => Exif::SHORT, # Flash #p41-42
224 'FocalLength' => Exif::RATIONAL, # Lens focal length
225 'SubjectArea' => Exif::SHORT, # Subject area
226 'FlashEnergy' => Exif::RATIONAL, # Flash energy
227 'SpatialFrequencyResponse' => Exif::UNDEFINED, # Spatial frequency response
228 'FocalPlaneXResolution' => Exif::RATIONAL, # Focal plane X resolution
229 'FocalPlaneYResolution' => Exif::RATIONAL, # Focal plane Y resolution
230 'FocalPlaneResolutionUnit' => Exif::SHORT, # Focal plane resolution unit #p46
231 'SubjectLocation' => Exif::SHORT, # Subject location
232 'ExposureIndex' => Exif::RATIONAL, # Exposure index
233 'SensingMethod' => Exif::SHORT, # Sensing method #p46
234 'FileSource' => Exif::UNDEFINED, # File source #p47
235 'SceneType' => Exif::UNDEFINED, # Scene type #p47
236 'CFAPattern' => Exif::UNDEFINED, # CFA pattern
237 'CustomRendered' => Exif::SHORT, # Custom image processing #p48
238 'ExposureMode' => Exif::SHORT, # Exposure mode #p48
239 'WhiteBalance' => Exif::SHORT, # White Balance #p49
240 'DigitalZoomRatio' => Exif::RATIONAL, # Digital zoom ration
241 'FocalLengthIn35mmFilm' => Exif::SHORT, # Focal length in 35 mm film
242 'SceneCaptureType' => Exif::SHORT, # Scene capture type #p49
243 'GainControl' => Exif::RATIONAL, # Scene control #p49-50
244 'Contrast' => Exif::SHORT, # Contrast #p50
245 'Saturation' => Exif::SHORT, # Saturation #p50
246 'Sharpness' => Exif::SHORT, # Sharpness #p50
247 'DeviceSettingDescription' => Exif::UNDEFINED, # Desice settings description
248 'SubjectDistanceRange' => Exif::SHORT, # Subject distance range #p51
249 ),
250
251 'other' => array(
252 'ImageUniqueID' => Exif::ASCII, # Unique image ID
253 ),
254 ),
255
256 # GPS Attribute Information (p52)
257 'gps' => array(
258 'GPSVersionID' => Exif::BYTE, # GPS tag version
259 'GPSLatitudeRef' => Exif::ASCII, # North or South Latitude #p52-53
260 'GPSLatitude' => Exif::RATIONAL, # Latitude
261 'GPSLongitudeRef' => Exif::ASCII, # East or West Longitude #p53
262 'GPSLongitude' => Exif::RATIONAL, # Longitude
263 'GPSAltitudeRef' => Exif::BYTE, # Altitude reference
264 'GPSAltitude' => Exif::RATIONAL, # Altitude
265 'GPSTimeStamp' => Exif::RATIONAL, # GPS time (atomic clock)
266 'GPSSatellites' => Exif::ASCII, # Satellites used for measurement
267 'GPSStatus' => Exif::ASCII, # Receiver status #p54
268 'GPSMeasureMode' => Exif::ASCII, # Measurement mode #p54-55
269 'GPSDOP' => Exif::RATIONAL, # Measurement precision
270 'GPSSpeedRef' => Exif::ASCII, # Speed unit #p55
271 'GPSSpeed' => Exif::RATIONAL, # Speed of GPS receiver
272 'GPSTrackRef' => Exif::ASCII, # Reference for direction of movement #p55
273 'GPSTrack' => Exif::RATIONAL, # Direction of movement
274 'GPSImgDirectionRef' => Exif::ASCII, # Reference for direction of image #p56
275 'GPSImgDirection' => Exif::RATIONAL, # Direction of image
276 'GPSMapDatum' => Exif::ASCII, # Geodetic survey data used
277 'GPSDestLatitudeRef' => Exif::ASCII, # Reference for latitude of destination #p56
278 'GPSDestLatitude' => Exif::RATIONAL, # Latitude destination
279 'GPSDestLongitudeRef' => Exif::ASCII, # Reference for longitude of destination #p57
280 'GPSDestLongitude' => Exif::RATIONAL, # Longitude of destination
281 'GPSDestBearingRef' => Exif::ASCII, # Reference for bearing of destination #p57
282 'GPSDestBearing' => Exif::RATIONAL, # Bearing of destination
283 'GPSDestDistanceRef' => Exif::ASCII, # Reference for distance to destination #p57-58
284 'GPSDestDistance' => Exif::RATIONAL, # Distance to destination
285 'GPSProcessingMethod' => Exif::UNDEFINED, # Name of GPS processing method
286 'GPSAreaInformation' => Exif::UNDEFINED, # Name of GPS area
287 'GPSDateStamp' => Exif::ASCII, # GPS date
288 'GPSDifferential' => Exif::SHORT, # GPS differential correction
289 ),
290 );
291
292 $this->file = $file;
293 $this->basename = wfBaseName( $this->file );
294
295 $this->makeFlatExifTags();
296
297 $this->debugFile( $this->basename, __FUNCTION__, true );
298 if( function_exists( 'exif_read_data' ) ) {
299 wfSuppressWarnings();
300 $data = exif_read_data( $this->file );
301 wfRestoreWarnings();
302 } else {
303 throw new MWException( "Internal error: exif_read_data not present. \$wgShowEXIF may be incorrectly set or not checked by an extension." );
304 }
305 /**
306 * exif_read_data() will return false on invalid input, such as
307 * when somebody uploads a file called something.jpeg
308 * containing random gibberish.
309 */
310 $this->mRawExifData = $data ? $data : array();
311
312 $this->makeFilteredData();
313 $this->makeFormattedData();
314
315 $this->debugFile( __FUNCTION__, false );
316 }
317
318 /**#@+
319 * @private
320 */
321 /**
322 * Generate a flat list of the exif tags
323 */
324 function makeFlatExifTags() {
325 $this->extractTags( $this->mExifTags );
326 }
327
328 /**
329 * A recursing extractor function used by makeFlatExifTags()
330 *
331 * Note: This used to use an array_walk function, but it made PHP5
332 * segfault, see `cvs diff -u -r 1.4 -r 1.5 Exif.php`
333 */
334 function extractTags( &$tagset ) {
335 foreach( $tagset as $key => $val ) {
336 if( is_array( $val ) ) {
337 $this->extractTags( $val );
338 } else {
339 $this->mFlatExifTags[$key] = $val;
340 }
341 }
342 }
343
344 /**
345 * Make $this->mFilteredExifData
346 */
347 function makeFilteredData() {
348 $this->mFilteredExifData = $this->mRawExifData;
349
350 foreach( $this->mFilteredExifData as $k => $v ) {
351 if ( !in_array( $k, array_keys( $this->mFlatExifTags ) ) ) {
352 $this->debug( $v, __FUNCTION__, "'$k' is not a valid Exif tag" );
353 unset( $this->mFilteredExifData[$k] );
354 }
355 }
356
357 foreach( $this->mFilteredExifData as $k => $v ) {
358 if ( !$this->validate($k, $v) ) {
359 $this->debug( $v, __FUNCTION__, "'$k' contained invalid data" );
360 unset( $this->mFilteredExifData[$k] );
361 }
362 }
363 }
364
365 /**
366 * @todo document
367 */
368 function makeFormattedData( ) {
369 $format = new FormatExif( $this->getFilteredData() );
370 $this->mFormattedExifData = $format->getFormattedData();
371 }
372 /**#@-*/
373
374 /**#@+
375 * @return array
376 */
377 /**
378 * Get $this->mRawExifData
379 */
380 function getData() {
381 return $this->mRawExifData;
382 }
383
384 /**
385 * Get $this->mFilteredExifData
386 */
387 function getFilteredData() {
388 return $this->mFilteredExifData;
389 }
390
391 /**
392 * Get $this->mFormattedExifData
393 */
394 function getFormattedData() {
395 return $this->mFormattedExifData;
396 }
397 /**#@-*/
398
399 /**
400 * The version of the output format
401 *
402 * Before the actual metadata information is saved in the database we
403 * strip some of it since we don't want to save things like thumbnails
404 * which usually accompany Exif data. This value gets saved in the
405 * database along with the actual Exif data, and if the version in the
406 * database doesn't equal the value returned by this function the Exif
407 * data is regenerated.
408 *
409 * @return int
410 */
411 public static function version() {
412 return 1; // We don't need no bloddy constants!
413 }
414
415 /**#@+
416 * Validates if a tag value is of the type it should be according to the Exif spec
417 *
418 * @private
419 *
420 * @param $in Mixed: the input value to check
421 * @return bool
422 */
423 function isByte( $in ) {
424 if ( !is_array( $in ) && sprintf('%d', $in) == $in && $in >= 0 && $in <= 255 ) {
425 $this->debug( $in, __FUNCTION__, true );
426 return true;
427 } else {
428 $this->debug( $in, __FUNCTION__, false );
429 return false;
430 }
431 }
432
433 function isASCII( $in ) {
434 if ( is_array( $in ) ) {
435 return false;
436 }
437
438 if ( preg_match( "/[^\x0a\x20-\x7e]/", $in ) ) {
439 $this->debug( $in, __FUNCTION__, 'found a character not in our whitelist' );
440 return false;
441 }
442
443 if ( preg_match( '/^\s*$/', $in ) ) {
444 $this->debug( $in, __FUNCTION__, 'input consisted solely of whitespace' );
445 return false;
446 }
447
448 return true;
449 }
450
451 function isShort( $in ) {
452 if ( !is_array( $in ) && sprintf('%d', $in) == $in && $in >= 0 && $in <= 65536 ) {
453 $this->debug( $in, __FUNCTION__, true );
454 return true;
455 } else {
456 $this->debug( $in, __FUNCTION__, false );
457 return false;
458 }
459 }
460
461 function isLong( $in ) {
462 if ( !is_array( $in ) && sprintf('%d', $in) == $in && $in >= 0 && $in <= 4294967296 ) {
463 $this->debug( $in, __FUNCTION__, true );
464 return true;
465 } else {
466 $this->debug( $in, __FUNCTION__, false );
467 return false;
468 }
469 }
470
471 function isRational( $in ) {
472 $m = array();
473 if ( !is_array( $in ) && @preg_match( '/^(\d+)\/(\d+[1-9]|[1-9]\d*)$/', $in, $m ) ) { # Avoid division by zero
474 return $this->isLong( $m[1] ) && $this->isLong( $m[2] );
475 } else {
476 $this->debug( $in, __FUNCTION__, 'fed a non-fraction value' );
477 return false;
478 }
479 }
480
481 function isUndefined( $in ) {
482 if ( !is_array( $in ) && preg_match( '/^\d{4}$/', $in ) ) { // Allow ExifVersion and FlashpixVersion
483 $this->debug( $in, __FUNCTION__, true );
484 return true;
485 } else {
486 $this->debug( $in, __FUNCTION__, false );
487 return false;
488 }
489 }
490
491 function isSlong( $in ) {
492 if ( $this->isLong( abs( $in ) ) ) {
493 $this->debug( $in, __FUNCTION__, true );
494 return true;
495 } else {
496 $this->debug( $in, __FUNCTION__, false );
497 return false;
498 }
499 }
500
501 function isSrational( $in ) {
502 $m = array();
503 if ( !is_array( $in ) && preg_match( '/^(\d+)\/(\d+[1-9]|[1-9]\d*)$/', $in, $m ) ) { # Avoid division by zero
504 return $this->isSlong( $m[0] ) && $this->isSlong( $m[1] );
505 } else {
506 $this->debug( $in, __FUNCTION__, 'fed a non-fraction value' );
507 return false;
508 }
509 }
510 /**#@-*/
511
512 /**
513 * Validates if a tag has a legal value according to the Exif spec
514 *
515 * @private
516 *
517 * @param $tag String: the tag to check.
518 * @param $val Mixed: the value of the tag.
519 * @return bool
520 */
521 function validate( $tag, $val ) {
522 $debug = "tag is '$tag'";
523 // Does not work if not typecast
524 switch( (string)$this->mFlatExifTags[$tag] ) {
525 case (string)Exif::BYTE:
526 $this->debug( $val, __FUNCTION__, $debug );
527 return $this->isByte( $val );
528 case (string)Exif::ASCII:
529 $this->debug( $val, __FUNCTION__, $debug );
530 return $this->isASCII( $val );
531 case (string)Exif::SHORT:
532 $this->debug( $val, __FUNCTION__, $debug );
533 return $this->isShort( $val );
534 case (string)Exif::LONG:
535 $this->debug( $val, __FUNCTION__, $debug );
536 return $this->isLong( $val );
537 case (string)Exif::RATIONAL:
538 $this->debug( $val, __FUNCTION__, $debug );
539 return $this->isRational( $val );
540 case (string)Exif::UNDEFINED:
541 $this->debug( $val, __FUNCTION__, $debug );
542 return $this->isUndefined( $val );
543 case (string)Exif::SLONG:
544 $this->debug( $val, __FUNCTION__, $debug );
545 return $this->isSlong( $val );
546 case (string)Exif::SRATIONAL:
547 $this->debug( $val, __FUNCTION__, $debug );
548 return $this->isSrational( $val );
549 case (string)Exif::SHORT.','.Exif::LONG:
550 $this->debug( $val, __FUNCTION__, $debug );
551 return $this->isShort( $val ) || $this->isLong( $val );
552 default:
553 $this->debug( $val, __FUNCTION__, "The tag '$tag' is unknown" );
554 return false;
555 }
556 }
557
558 /**
559 * Convenience function for debugging output
560 *
561 * @private
562 *
563 * @param $in Mixed:
564 * @param $fname String:
565 * @param $action Mixed: , default NULL.
566 */
567 function debug( $in, $fname, $action = null ) {
568 if ( !$this->log ) {
569 return;
570 }
571 $type = gettype( $in );
572 $class = ucfirst( __CLASS__ );
573 if ( $type === 'array' )
574 $in = print_r( $in, true );
575
576 if ( $action === true )
577 wfDebugLog( $this->log, "$class::$fname: accepted: '$in' (type: $type)\n");
578 elseif ( $action === false )
579 wfDebugLog( $this->log, "$class::$fname: rejected: '$in' (type: $type)\n");
580 elseif ( $action === null )
581 wfDebugLog( $this->log, "$class::$fname: input was: '$in' (type: $type)\n");
582 else
583 wfDebugLog( $this->log, "$class::$fname: $action (type: $type; content: '$in')\n");
584 }
585
586 /**
587 * Convenience function for debugging output
588 *
589 * @private
590 *
591 * @param $fname String: the name of the function calling this function
592 * @param $io Boolean: Specify whether we're beginning or ending
593 */
594 function debugFile( $fname, $io ) {
595 if ( !$this->log ) {
596 return;
597 }
598 $class = ucfirst( __CLASS__ );
599 if ( $io ) {
600 wfDebugLog( $this->log, "$class::$fname: begin processing: '{$this->basename}'\n" );
601 } else {
602 wfDebugLog( $this->log, "$class::$fname: end processing: '{$this->basename}'\n" );
603 }
604 }
605
606 }
607
608 /**
609 * @todo document (e.g. one-sentence class-overview description)
610 * @ingroup Media
611 */
612 class FormatExif {
613 /**
614 * The Exif data to format
615 *
616 * @var array
617 * @private
618 */
619 var $mExif;
620
621 /**
622 * Constructor
623 *
624 * @param $exif Array: the Exif data to format ( as returned by
625 * Exif::getFilteredData() )
626 */
627 function __construct( $exif ) {
628 $this->mExif = $exif;
629 }
630
631 /**
632 * Numbers given by Exif user agents are often magical, that is they
633 * should be replaced by a detailed explanation depending on their
634 * value which most of the time are plain integers. This function
635 * formats Exif values into human readable form.
636 *
637 * @return array
638 */
639 function getFormattedData() {
640 global $wgLang;
641
642 $tags =& $this->mExif;
643
644 $resolutionunit = !isset( $tags['ResolutionUnit'] ) || $tags['ResolutionUnit'] == 2 ? 2 : 3;
645 unset( $tags['ResolutionUnit'] );
646
647 foreach( $tags as $tag => $val ) {
648 switch( $tag ) {
649 case 'Compression':
650 switch( $val ) {
651 case 1: case 6:
652 $tags[$tag] = $this->msg( $tag, $val );
653 break;
654 default:
655 $tags[$tag] = $val;
656 break;
657 }
658 break;
659
660 case 'PhotometricInterpretation':
661 switch( $val ) {
662 case 2: case 6:
663 $tags[$tag] = $this->msg( $tag, $val );
664 break;
665 default:
666 $tags[$tag] = $val;
667 break;
668 }
669 break;
670
671 case 'Orientation':
672 switch( $val ) {
673 case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8:
674 $tags[$tag] = $this->msg( $tag, $val );
675 break;
676 default:
677 $tags[$tag] = $val;
678 break;
679 }
680 break;
681
682 case 'PlanarConfiguration':
683 switch( $val ) {
684 case 1: case 2:
685 $tags[$tag] = $this->msg( $tag, $val );
686 break;
687 default:
688 $tags[$tag] = $val;
689 break;
690 }
691 break;
692
693 // TODO: YCbCrSubSampling
694 // TODO: YCbCrPositioning
695
696 case 'XResolution':
697 case 'YResolution':
698 switch( $resolutionunit ) {
699 case 2:
700 $tags[$tag] = $this->msg( 'XYResolution', 'i', $this->formatNum( $val ) );
701 break;
702 case 3:
703 $this->msg( 'XYResolution', 'c', $this->formatNum( $val ) );
704 break;
705 default:
706 $tags[$tag] = $val;
707 break;
708 }
709 break;
710
711 // TODO: YCbCrCoefficients #p27 (see annex E)
712 case 'ExifVersion': case 'FlashpixVersion':
713 $tags[$tag] = "$val"/100;
714 break;
715
716 case 'ColorSpace':
717 switch( $val ) {
718 case 1: case 'FFFF.H':
719 $tags[$tag] = $this->msg( $tag, $val );
720 break;
721 default:
722 $tags[$tag] = $val;
723 break;
724 }
725 break;
726
727 case 'ComponentsConfiguration':
728 switch( $val ) {
729 case 0: case 1: case 2: case 3: case 4: case 5: case 6:
730 $tags[$tag] = $this->msg( $tag, $val );
731 break;
732 default:
733 $tags[$tag] = $val;
734 break;
735 }
736 break;
737
738 case 'DateTime':
739 case 'DateTimeOriginal':
740 case 'DateTimeDigitized':
741 if( $val == '0000:00:00 00:00:00' ) {
742 $tags[$tag] = wfMsg('exif-unknowndate');
743 } elseif( preg_match( '/^(?:\d{4}):(?:\d\d):(?:\d\d) (?:\d\d):(?:\d\d):(?:\d\d)$/', $val ) ) {
744 $tags[$tag] = $wgLang->timeanddate( wfTimestamp(TS_MW, $val) );
745 }
746 break;
747
748 case 'ExposureProgram':
749 switch( $val ) {
750 case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8:
751 $tags[$tag] = $this->msg( $tag, $val );
752 break;
753 default:
754 $tags[$tag] = $val;
755 break;
756 }
757 break;
758
759 case 'SubjectDistance':
760 $tags[$tag] = $this->msg( $tag, '', $this->formatNum( $val ) );
761 break;
762
763 case 'MeteringMode':
764 switch( $val ) {
765 case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 255:
766 $tags[$tag] = $this->msg( $tag, $val );
767 break;
768 default:
769 $tags[$tag] = $val;
770 break;
771 }
772 break;
773
774 case 'LightSource':
775 switch( $val ) {
776 case 0: case 1: case 2: case 3: case 4: case 9: case 10: case 11:
777 case 12: case 13: case 14: case 15: case 17: case 18: case 19: case 20:
778 case 21: case 22: case 23: case 24: case 255:
779 $tags[$tag] = $this->msg( $tag, $val );
780 break;
781 default:
782 $tags[$tag] = $val;
783 break;
784 }
785 break;
786
787 case 'Flash':
788 $flashDecode = array(
789 'fired' => $val & bindec( '00000001' ),
790 'return' => ($val & bindec( '00000110' )) >> 1,
791 'mode' => ($val & bindec( '00011000' )) >> 3,
792 'function' => ($val & bindec( '00100000' )) >> 5,
793 'redeye' => ($val & bindec( '01000000' )) >> 6,
794 // 'reserved' => ($val & bindec( '10000000' )) >> 7,
795 );
796
797 # We do not need to handle unknown values since all are used.
798 foreach( $flashDecode as $subTag => $subValue ) {
799 # We do not need any message for zeroed values.
800 if( $subTag != 'fired' && $subValue == 0) {
801 continue;
802 }
803 $fullTag = $tag . '-' . $subTag ;
804 $flashMsgs[] = $this->msg( $fullTag, $subValue );
805 }
806 $tags[$tag] = $wgLang->commaList( $flashMsgs );
807 break;
808
809 case 'FocalPlaneResolutionUnit':
810 switch( $val ) {
811 case 2:
812 $tags[$tag] = $this->msg( $tag, $val );
813 break;
814 default:
815 $tags[$tag] = $val;
816 break;
817 }
818 break;
819
820 case 'SensingMethod':
821 switch( $val ) {
822 case 1: case 2: case 3: case 4: case 5: case 7: case 8:
823 $tags[$tag] = $this->msg( $tag, $val );
824 break;
825 default:
826 $tags[$tag] = $val;
827 break;
828 }
829 break;
830
831 case 'FileSource':
832 switch( $val ) {
833 case 3:
834 $tags[$tag] = $this->msg( $tag, $val );
835 break;
836 default:
837 $tags[$tag] = $val;
838 break;
839 }
840 break;
841
842 case 'SceneType':
843 switch( $val ) {
844 case 1:
845 $tags[$tag] = $this->msg( $tag, $val );
846 break;
847 default:
848 $tags[$tag] = $val;
849 break;
850 }
851 break;
852
853 case 'CustomRendered':
854 switch( $val ) {
855 case 0: case 1:
856 $tags[$tag] = $this->msg( $tag, $val );
857 break;
858 default:
859 $tags[$tag] = $val;
860 break;
861 }
862 break;
863
864 case 'ExposureMode':
865 switch( $val ) {
866 case 0: case 1: case 2:
867 $tags[$tag] = $this->msg( $tag, $val );
868 break;
869 default:
870 $tags[$tag] = $val;
871 break;
872 }
873 break;
874
875 case 'WhiteBalance':
876 switch( $val ) {
877 case 0: case 1:
878 $tags[$tag] = $this->msg( $tag, $val );
879 break;
880 default:
881 $tags[$tag] = $val;
882 break;
883 }
884 break;
885
886 case 'SceneCaptureType':
887 switch( $val ) {
888 case 0: case 1: case 2: case 3:
889 $tags[$tag] = $this->msg( $tag, $val );
890 break;
891 default:
892 $tags[$tag] = $val;
893 break;
894 }
895 break;
896
897 case 'GainControl':
898 switch( $val ) {
899 case 0: case 1: case 2: case 3: case 4:
900 $tags[$tag] = $this->msg( $tag, $val );
901 break;
902 default:
903 $tags[$tag] = $val;
904 break;
905 }
906 break;
907
908 case 'Contrast':
909 switch( $val ) {
910 case 0: case 1: case 2:
911 $tags[$tag] = $this->msg( $tag, $val );
912 break;
913 default:
914 $tags[$tag] = $val;
915 break;
916 }
917 break;
918
919 case 'Saturation':
920 switch( $val ) {
921 case 0: case 1: case 2:
922 $tags[$tag] = $this->msg( $tag, $val );
923 break;
924 default:
925 $tags[$tag] = $val;
926 break;
927 }
928 break;
929
930 case 'Sharpness':
931 switch( $val ) {
932 case 0: case 1: case 2:
933 $tags[$tag] = $this->msg( $tag, $val );
934 break;
935 default:
936 $tags[$tag] = $val;
937 break;
938 }
939 break;
940
941 case 'SubjectDistanceRange':
942 switch( $val ) {
943 case 0: case 1: case 2: case 3:
944 $tags[$tag] = $this->msg( $tag, $val );
945 break;
946 default:
947 $tags[$tag] = $val;
948 break;
949 }
950 break;
951
952 case 'GPSLatitudeRef':
953 case 'GPSDestLatitudeRef':
954 switch( $val ) {
955 case 'N': case 'S':
956 $tags[$tag] = $this->msg( 'GPSLatitude', $val );
957 break;
958 default:
959 $tags[$tag] = $val;
960 break;
961 }
962 break;
963
964 case 'GPSLongitudeRef':
965 case 'GPSDestLongitudeRef':
966 switch( $val ) {
967 case 'E': case 'W':
968 $tags[$tag] = $this->msg( 'GPSLongitude', $val );
969 break;
970 default:
971 $tags[$tag] = $val;
972 break;
973 }
974 break;
975
976 case 'GPSStatus':
977 switch( $val ) {
978 case 'A': case 'V':
979 $tags[$tag] = $this->msg( $tag, $val );
980 break;
981 default:
982 $tags[$tag] = $val;
983 break;
984 }
985 break;
986
987 case 'GPSMeasureMode':
988 switch( $val ) {
989 case 2: case 3:
990 $tags[$tag] = $this->msg( $tag, $val );
991 break;
992 default:
993 $tags[$tag] = $val;
994 break;
995 }
996 break;
997
998 case 'GPSSpeedRef':
999 case 'GPSDestDistanceRef':
1000 switch( $val ) {
1001 case 'K': case 'M': case 'N':
1002 $tags[$tag] = $this->msg( 'GPSSpeed', $val );
1003 break;
1004 default:
1005 $tags[$tag] = $val;
1006 break;
1007 }
1008 break;
1009
1010 case 'GPSTrackRef':
1011 case 'GPSImgDirectionRef':
1012 case 'GPSDestBearingRef':
1013 switch( $val ) {
1014 case 'T': case 'M':
1015 $tags[$tag] = $this->msg( 'GPSDirection', $val );
1016 break;
1017 default:
1018 $tags[$tag] = $val;
1019 break;
1020 }
1021 break;
1022
1023 case 'GPSDateStamp':
1024 $tags[$tag] = $wgLang->date( substr( $val, 0, 4 ) . substr( $val, 5, 2 ) . substr( $val, 8, 2 ) . '000000' );
1025 break;
1026
1027 // This is not in the Exif standard, just a special
1028 // case for our purposes which enables wikis to wikify
1029 // the make, model and software name to link to their articles.
1030 case 'Make':
1031 case 'Model':
1032 case 'Software':
1033 $tags[$tag] = $this->msg( $tag, '', $val );
1034 break;
1035
1036 case 'ExposureTime':
1037 // Show the pretty fraction as well as decimal version
1038 $tags[$tag] = wfMsg( 'exif-exposuretime-format',
1039 $this->formatFraction( $val ), $this->formatNum( $val ) );
1040 break;
1041
1042 case 'FNumber':
1043 $tags[$tag] = wfMsg( 'exif-fnumber-format',
1044 $this->formatNum( $val ) );
1045 break;
1046
1047 case 'FocalLength':
1048 $tags[$tag] = wfMsg( 'exif-focallength-format',
1049 $this->formatNum( $val ) );
1050 break;
1051
1052 // Do not transform fields with pure text.
1053 // For some languages the formatNum() conversion results to wrong output like
1054 // foo,bar@example,com or foo٫bar@example٫com
1055 case 'ImageDescription':
1056 case 'Artist':
1057 case 'Copyright':
1058 $tags[$tag] = htmlspecialchars( $val );
1059 break;
1060 default:
1061 $tags[$tag] = $this->formatNum( $val );
1062 break;
1063 }
1064 }
1065
1066 return $tags;
1067 }
1068
1069 /**
1070 * Convenience function for getFormattedData()
1071 *
1072 * @private
1073 *
1074 * @param $tag String: the tag name to pass on
1075 * @param $val String: the value of the tag
1076 * @param $arg String: an argument to pass ($1)
1077 * @return string A wfMsg of "exif-$tag-$val" in lower case
1078 */
1079 function msg( $tag, $val, $arg = null ) {
1080 global $wgContLang;
1081
1082 if ($val === '')
1083 $val = 'value';
1084 return wfMsg( $wgContLang->lc( "exif-$tag-$val" ), $arg );
1085 }
1086
1087 /**
1088 * Format a number, convert numbers from fractions into floating point
1089 * numbers
1090 *
1091 * @private
1092 *
1093 * @param $num Mixed: the value to format
1094 * @return mixed A floating point number or whatever we were fed
1095 */
1096 function formatNum( $num ) {
1097 global $wgLang;
1098
1099 $m = array();
1100 if ( preg_match( '/^(\d+)\/(\d+)$/', $num, $m ) )
1101 return $wgLang->formatNum( $m[2] != 0 ? $m[1] / $m[2] : $num );
1102 else
1103 return $wgLang->formatNum( $num );
1104 }
1105
1106 /**
1107 * Format a rational number, reducing fractions
1108 *
1109 * @private
1110 *
1111 * @param $num Mixed: the value to format
1112 * @return mixed A floating point number or whatever we were fed
1113 */
1114 function formatFraction( $num ) {
1115 $m = array();
1116 if ( preg_match( '/^(\d+)\/(\d+)$/', $num, $m ) ) {
1117 $numerator = intval( $m[1] );
1118 $denominator = intval( $m[2] );
1119 $gcd = $this->gcd( $numerator, $denominator );
1120 if( $gcd != 0 ) {
1121 // 0 shouldn't happen! ;)
1122 return $this->formatNum( $numerator / $gcd ) . '/' . $this->formatNum( $denominator / $gcd );
1123 }
1124 }
1125 return $this->formatNum( $num );
1126 }
1127
1128 /**
1129 * Calculate the greatest common divisor of two integers.
1130 *
1131 * @param $a Integer: FIXME
1132 * @param $b Integer: FIXME
1133 * @return int
1134 * @private
1135 */
1136 function gcd( $a, $b ) {
1137 /*
1138 // http://en.wikipedia.org/wiki/Euclidean_algorithm
1139 // Recursive form would be:
1140 if( $b == 0 )
1141 return $a;
1142 else
1143 return gcd( $b, $a % $b );
1144 */
1145 while( $b != 0 ) {
1146 $remainder = $a % $b;
1147
1148 // tail recursion...
1149 $a = $b;
1150 $b = $remainder;
1151 }
1152 return $a;
1153 }
1154 }