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