Declare visibility on class properties of Exif
[lhc/web/wiklou.git] / includes / media / Exif.php
1 <?php
2 /**
3 * Extraction and validation of image metadata.
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, 2009 Brent Garber
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 * Class to extract and validate Exif data from jpeg (and possibly tiff) files.
30 * @ingroup Media
31 */
32 class Exif {
33 /** An 8-bit (1-byte) unsigned integer. */
34 const BYTE = 1;
35
36 /** An 8-bit byte containing one 7-bit ASCII code.
37 * The final byte is terminated with NULL.
38 */
39 const ASCII = 2;
40
41 /** A 16-bit (2-byte) unsigned integer. */
42 const SHORT = 3;
43
44 /** A 32-bit (4-byte) unsigned integer. */
45 const LONG = 4;
46
47 /** Two LONGs. The first LONG is the numerator and the second LONG expresses
48 * the denominator
49 */
50 const RATIONAL = 5;
51
52 /** A 16-bit (2-byte) or 32-bit (4-byte) unsigned integer. */
53 const SHORT_OR_LONG = 6;
54
55 /** An 8-bit byte that can take any value depending on the field definition */
56 const UNDEFINED = 7;
57
58 /** A 32-bit (4-byte) signed integer (2's complement notation), */
59 const SLONG = 9;
60
61 /** Two SLONGs. The first SLONG is the numerator and the second SLONG is
62 * the denominator.
63 */
64 const SRATIONAL = 10;
65
66 /** A fake value for things we don't want or don't support. */
67 const IGNORE = -1;
68
69 /** @var array Exif tags grouped by category, the tagname itself is the key
70 * and the type is the value, in the case of more than one possible value
71 * type they are separated by commas.
72 */
73 private $mExifTags;
74
75 /** @var array The raw Exif data returned by exif_read_data() */
76 private $mRawExifData;
77
78 /** @var array A Filtered version of $mRawExifData that has been pruned
79 * of invalid tags and tags that contain content they shouldn't contain
80 * according to the Exif specification
81 */
82 private $mFilteredExifData;
83
84 /** @var array Filtered and formatted Exif data, see FormatMetadata::getFormattedData() */
85 private $mFormattedExifData;
86
87 /** @var string The file being processed */
88 private $file;
89
90 /** @var string The basename of the file being processed */
91 private $basename;
92
93 /** @var string The private log to log to, e.g. 'exif' */
94 private $log = false;
95
96 /** @var string The byte order of the file. Needed because php's extension
97 * doesn't fully process some obscure props.
98 */
99 private $byteOrder;
100
101 /**
102 * Constructor
103 *
104 * @param string $file filename.
105 * @param string $byteOrder Type of byte ordering either 'BE' (Big Endian)
106 * or 'LE' (Little Endian). Default ''.
107 * @throws MWException
108 * @todo FIXME: The following are broke:
109 * SubjectArea. Need to test the more obscure tags.
110 *
111 * DigitalZoomRatio = 0/0 is rejected. need to determine if that's valid.
112 * possibly should treat 0/0 = 0. need to read exif spec on that.
113 */
114 function __construct( $file, $byteOrder = '' ) {
115 /**
116 * Page numbers here refer to pages in the Exif 2.2 standard
117 *
118 * Note, Exif::UNDEFINED is treated as a string, not as an array of bytes
119 * so don't put a count parameter for any UNDEFINED values.
120 *
121 * @link http://exif.org/Exif2-2.PDF The Exif 2.2 specification
122 */
123 $this->mExifTags = array(
124 # TIFF Rev. 6.0 Attribute Information (p22)
125 'IFD0' => array(
126 # Tags relating to image structure
127 'ImageWidth' => Exif::SHORT_OR_LONG, # Image width
128 'ImageLength' => Exif::SHORT_OR_LONG, # Image height
129 'BitsPerSample' => array( Exif::SHORT, 3 ), # Number of bits per component
130 # "When a primary image is JPEG compressed, this designation is not"
131 # "necessary and is omitted." (p23)
132 'Compression' => Exif::SHORT, # Compression scheme #p23
133 'PhotometricInterpretation' => Exif::SHORT, # Pixel composition #p23
134 'Orientation' => Exif::SHORT, # Orientation of image #p24
135 'SamplesPerPixel' => Exif::SHORT, # Number of components
136 'PlanarConfiguration' => Exif::SHORT, # Image data arrangement #p24
137 'YCbCrSubSampling' => array( Exif::SHORT, 2 ), # Subsampling ratio of Y to C #p24
138 'YCbCrPositioning' => Exif::SHORT, # Y and C positioning #p24-25
139 'XResolution' => Exif::RATIONAL, # Image resolution in width direction
140 'YResolution' => Exif::RATIONAL, # Image resolution in height direction
141 'ResolutionUnit' => Exif::SHORT, # Unit of X and Y resolution #(p26)
142
143 # Tags relating to recording offset
144 'StripOffsets' => Exif::SHORT_OR_LONG, # Image data location
145 'RowsPerStrip' => Exif::SHORT_OR_LONG, # Number of rows per strip
146 'StripByteCounts' => Exif::SHORT_OR_LONG, # Bytes per compressed strip
147 'JPEGInterchangeFormat' => Exif::SHORT_OR_LONG, # Offset to JPEG SOI
148 'JPEGInterchangeFormatLength' => Exif::SHORT_OR_LONG, # Bytes of JPEG data
149
150 # Tags relating to image data characteristics
151 'TransferFunction' => Exif::IGNORE, # Transfer function
152 'WhitePoint' => array( Exif::RATIONAL, 2 ), # White point chromaticity
153 'PrimaryChromaticities' => array( Exif::RATIONAL, 6 ), # Chromaticities of primarities
154 # Color space transformation matrix coefficients #p27
155 'YCbCrCoefficients' => array( Exif::RATIONAL, 3 ),
156 'ReferenceBlackWhite' => array( Exif::RATIONAL, 6 ), # Pair of black and white reference values
157
158 # Other tags
159 'DateTime' => Exif::ASCII, # File change date and time
160 'ImageDescription' => Exif::ASCII, # Image title
161 'Make' => Exif::ASCII, # Image input equipment manufacturer
162 'Model' => Exif::ASCII, # Image input equipment model
163 'Software' => Exif::ASCII, # Software used
164 'Artist' => Exif::ASCII, # Person who created the image
165 'Copyright' => Exif::ASCII, # Copyright holder
166 ),
167
168 # Exif IFD Attribute Information (p30-31)
169 'EXIF' => array(
170 # TODO: NOTE: Nonexistence of this field is taken to mean nonconformance
171 # to the Exif 2.1 AND 2.2 standards
172 'ExifVersion' => Exif::UNDEFINED, # Exif version
173 'FlashPixVersion' => Exif::UNDEFINED, # Supported Flashpix version #p32
174
175 # Tags relating to Image Data Characteristics
176 'ColorSpace' => Exif::SHORT, # Color space information #p32
177
178 # Tags relating to image configuration
179 'ComponentsConfiguration' => Exif::UNDEFINED, # Meaning of each component #p33
180 'CompressedBitsPerPixel' => Exif::RATIONAL, # Image compression mode
181 'PixelYDimension' => Exif::SHORT_OR_LONG, # Valid image width
182 'PixelXDimension' => Exif::SHORT_OR_LONG, # Valid image height
183
184 # Tags relating to related user information
185 'MakerNote' => Exif::IGNORE, # Manufacturer notes
186 'UserComment' => Exif::UNDEFINED, # User comments #p34
187
188 # Tags relating to related file information
189 'RelatedSoundFile' => Exif::ASCII, # Related audio file
190
191 # Tags relating to date and time
192 'DateTimeOriginal' => Exif::ASCII, # Date and time of original data generation #p36
193 'DateTimeDigitized' => Exif::ASCII, # Date and time of original data generation
194 'SubSecTime' => Exif::ASCII, # DateTime subseconds
195 'SubSecTimeOriginal' => Exif::ASCII, # DateTimeOriginal subseconds
196 'SubSecTimeDigitized' => Exif::ASCII, # DateTimeDigitized subseconds
197
198 # Tags relating to picture-taking conditions (p31)
199 'ExposureTime' => Exif::RATIONAL, # Exposure time
200 'FNumber' => Exif::RATIONAL, # F Number
201 'ExposureProgram' => Exif::SHORT, # Exposure Program #p38
202 'SpectralSensitivity' => Exif::ASCII, # Spectral sensitivity
203 'ISOSpeedRatings' => Exif::SHORT, # ISO speed rating
204 'OECF' => Exif::IGNORE,
205 # Optoelectronic conversion factor. Note: We don't have support for this atm.
206 'ShutterSpeedValue' => Exif::SRATIONAL, # Shutter speed
207 'ApertureValue' => Exif::RATIONAL, # Aperture
208 'BrightnessValue' => Exif::SRATIONAL, # Brightness
209 'ExposureBiasValue' => Exif::SRATIONAL, # Exposure bias
210 'MaxApertureValue' => Exif::RATIONAL, # Maximum land aperture
211 'SubjectDistance' => Exif::RATIONAL, # Subject distance
212 'MeteringMode' => Exif::SHORT, # Metering mode #p40
213 'LightSource' => Exif::SHORT, # Light source #p40-41
214 'Flash' => Exif::SHORT, # Flash #p41-42
215 'FocalLength' => Exif::RATIONAL, # Lens focal length
216 'SubjectArea' => array( Exif::SHORT, 4 ), # Subject area
217 'FlashEnergy' => Exif::RATIONAL, # Flash energy
218 'SpatialFrequencyResponse' => Exif::IGNORE, # Spatial frequency response. Not supported atm.
219 'FocalPlaneXResolution' => Exif::RATIONAL, # Focal plane X resolution
220 'FocalPlaneYResolution' => Exif::RATIONAL, # Focal plane Y resolution
221 'FocalPlaneResolutionUnit' => Exif::SHORT, # Focal plane resolution unit #p46
222 'SubjectLocation' => array( Exif::SHORT, 2 ), # Subject location
223 'ExposureIndex' => Exif::RATIONAL, # Exposure index
224 'SensingMethod' => Exif::SHORT, # Sensing method #p46
225 'FileSource' => Exif::UNDEFINED, # File source #p47
226 'SceneType' => Exif::UNDEFINED, # Scene type #p47
227 'CFAPattern' => Exif::IGNORE, # CFA pattern. not supported atm.
228 'CustomRendered' => Exif::SHORT, # Custom image processing #p48
229 'ExposureMode' => Exif::SHORT, # Exposure mode #p48
230 'WhiteBalance' => Exif::SHORT, # White Balance #p49
231 'DigitalZoomRatio' => Exif::RATIONAL, # Digital zoom ration
232 'FocalLengthIn35mmFilm' => Exif::SHORT, # Focal length in 35 mm film
233 'SceneCaptureType' => Exif::SHORT, # Scene capture type #p49
234 'GainControl' => Exif::SHORT, # Scene control #p49-50
235 'Contrast' => Exif::SHORT, # Contrast #p50
236 'Saturation' => Exif::SHORT, # Saturation #p50
237 'Sharpness' => Exif::SHORT, # Sharpness #p50
238 'DeviceSettingDescription' => Exif::IGNORE,
239 # Device settings description. This could maybe be supported. Need to find an
240 # example file that uses this to see if it has stuff of interest in it.
241 'SubjectDistanceRange' => Exif::SHORT, # Subject distance range #p51
242
243 'ImageUniqueID' => Exif::ASCII, # Unique image ID
244 ),
245
246 # GPS Attribute Information (p52)
247 'GPS' => array(
248 'GPSVersion' => Exif::UNDEFINED,
249 # Should be an array of 4 Exif::BYTE's. However php treats it as an undefined
250 # Note exif standard calls this GPSVersionID, but php doesn't like the id suffix
251 'GPSLatitudeRef' => Exif::ASCII, # North or South Latitude #p52-53
252 'GPSLatitude' => array( Exif::RATIONAL, 3 ), # Latitude
253 'GPSLongitudeRef' => Exif::ASCII, # East or West Longitude #p53
254 'GPSLongitude' => array( Exif::RATIONAL, 3 ), # Longitude
255 'GPSAltitudeRef' => Exif::UNDEFINED,
256 # Altitude reference. Note, the exif standard says this should be an EXIF::Byte,
257 # but php seems to disagree.
258 'GPSAltitude' => Exif::RATIONAL, # Altitude
259 'GPSTimeStamp' => array( Exif::RATIONAL, 3 ), # GPS time (atomic clock)
260 'GPSSatellites' => Exif::ASCII, # Satellites used for measurement
261 'GPSStatus' => Exif::ASCII, # Receiver status #p54
262 'GPSMeasureMode' => Exif::ASCII, # Measurement mode #p54-55
263 'GPSDOP' => Exif::RATIONAL, # Measurement precision
264 'GPSSpeedRef' => Exif::ASCII, # Speed unit #p55
265 'GPSSpeed' => Exif::RATIONAL, # Speed of GPS receiver
266 'GPSTrackRef' => Exif::ASCII, # Reference for direction of movement #p55
267 'GPSTrack' => Exif::RATIONAL, # Direction of movement
268 'GPSImgDirectionRef' => Exif::ASCII, # Reference for direction of image #p56
269 'GPSImgDirection' => Exif::RATIONAL, # Direction of image
270 'GPSMapDatum' => Exif::ASCII, # Geodetic survey data used
271 'GPSDestLatitudeRef' => Exif::ASCII, # Reference for latitude of destination #p56
272 'GPSDestLatitude' => array( Exif::RATIONAL, 3 ), # Latitude destination
273 'GPSDestLongitudeRef' => Exif::ASCII, # Reference for longitude of destination #p57
274 'GPSDestLongitude' => array( Exif::RATIONAL, 3 ), # Longitude of destination
275 'GPSDestBearingRef' => Exif::ASCII, # Reference for bearing of destination #p57
276 'GPSDestBearing' => Exif::RATIONAL, # Bearing of destination
277 'GPSDestDistanceRef' => Exif::ASCII, # Reference for distance to destination #p57-58
278 'GPSDestDistance' => Exif::RATIONAL, # Distance to destination
279 'GPSProcessingMethod' => Exif::UNDEFINED, # Name of GPS processing method
280 'GPSAreaInformation' => Exif::UNDEFINED, # Name of GPS area
281 'GPSDateStamp' => Exif::ASCII, # GPS date
282 'GPSDifferential' => Exif::SHORT, # GPS differential correction
283 ),
284 );
285
286 $this->file = $file;
287 $this->basename = wfBaseName( $this->file );
288 if ( $byteOrder === 'BE' || $byteOrder === 'LE' ) {
289 $this->byteOrder = $byteOrder;
290 } else {
291 // Only give a warning for b/c, since originally we didn't
292 // require this. The number of things affected by this is
293 // rather small.
294 wfWarn( 'Exif class did not have byte order specified. ' .
295 'Some properties may be decoded incorrectly.' );
296 $this->byteOrder = 'BE'; // BE seems about twice as popular as LE in jpg's.
297 }
298
299 $this->debugFile( $this->basename, __FUNCTION__, true );
300 if ( function_exists( 'exif_read_data' ) ) {
301 wfSuppressWarnings();
302 $data = exif_read_data( $this->file, 0, true );
303 wfRestoreWarnings();
304 } else {
305 throw new MWException( "Internal error: exif_read_data not present. " .
306 "\$wgShowEXIF may be incorrectly set or not checked by an extension." );
307 }
308 /**
309 * exif_read_data() will return false on invalid input, such as
310 * when somebody uploads a file called something.jpeg
311 * containing random gibberish.
312 */
313 $this->mRawExifData = $data ? $data : array();
314 $this->makeFilteredData();
315 $this->collapseData();
316 $this->debugFile( __FUNCTION__, false );
317 }
318
319 /**
320 * Make $this->mFilteredExifData
321 */
322 function makeFilteredData() {
323 $this->mFilteredExifData = array();
324
325 foreach ( array_keys( $this->mRawExifData ) as $section ) {
326 if ( !in_array( $section, array_keys( $this->mExifTags ) ) ) {
327 $this->debug( $section, __FUNCTION__, "'$section' is not a valid Exif section" );
328 continue;
329 }
330
331 foreach ( array_keys( $this->mRawExifData[$section] ) as $tag ) {
332 if ( !in_array( $tag, array_keys( $this->mExifTags[$section] ) ) ) {
333 $this->debug( $tag, __FUNCTION__, "'$tag' is not a valid tag in '$section'" );
334 continue;
335 }
336
337 $this->mFilteredExifData[$tag] = $this->mRawExifData[$section][$tag];
338 // This is ok, as the tags in the different sections do not conflict.
339 // except in computed and thumbnail section, which we don't use.
340
341 $value = $this->mRawExifData[$section][$tag];
342 if ( !$this->validate( $section, $tag, $value ) ) {
343 $this->debug( $value, __FUNCTION__, "'$tag' contained invalid data" );
344 unset( $this->mFilteredExifData[$tag] );
345 }
346 }
347 }
348 }
349
350 /**
351 * Collapse some fields together.
352 * This converts some fields from exif form, to a more friendly form.
353 * For example GPS latitude to a single number.
354 *
355 * The rationale behind this is that we're storing data, not presenting to the user
356 * For example a longitude is a single number describing how far away you are from
357 * the prime meridian. Well it might be nice to split it up into minutes and seconds
358 * for the user, it doesn't really make sense to split a single number into 4 parts
359 * for storage. (degrees, minutes, second, direction vs single floating point number).
360 *
361 * Other things this might do (not really sure if they make sense or not):
362 * Dates -> mediawiki date format.
363 * convert values that can be in different units to be in one standardized unit.
364 *
365 * As an alternative approach, some of this could be done in the validate phase
366 * if we make up our own types like Exif::DATE.
367 */
368 function collapseData() {
369
370 $this->exifGPStoNumber( 'GPSLatitude' );
371 $this->exifGPStoNumber( 'GPSDestLatitude' );
372 $this->exifGPStoNumber( 'GPSLongitude' );
373 $this->exifGPStoNumber( 'GPSDestLongitude' );
374
375 if ( isset( $this->mFilteredExifData['GPSAltitude'] )
376 && isset( $this->mFilteredExifData['GPSAltitudeRef'] )
377 ) {
378 // We know altitude data is a <num>/<denom> from the validation
379 // functions ran earlier. But multiplying such a string by -1
380 // doesn't work well, so convert.
381 list( $num, $denom ) = explode( '/', $this->mFilteredExifData['GPSAltitude'] );
382 $this->mFilteredExifData['GPSAltitude'] = $num / $denom;
383
384 if ( $this->mFilteredExifData['GPSAltitudeRef'] === "\1" ) {
385 $this->mFilteredExifData['GPSAltitude'] *= -1;
386 }
387 unset( $this->mFilteredExifData['GPSAltitudeRef'] );
388 }
389
390 $this->exifPropToOrd( 'FileSource' );
391 $this->exifPropToOrd( 'SceneType' );
392
393 $this->charCodeString( 'UserComment' );
394 $this->charCodeString( 'GPSProcessingMethod' );
395 $this->charCodeString( 'GPSAreaInformation' );
396
397 //ComponentsConfiguration should really be an array instead of a string...
398 //This turns a string of binary numbers into an array of numbers.
399
400 if ( isset( $this->mFilteredExifData['ComponentsConfiguration'] ) ) {
401 $val = $this->mFilteredExifData['ComponentsConfiguration'];
402 $ccVals = array();
403
404 $strLen = strlen( $val );
405 for ( $i = 0; $i < $strLen; $i++ ) {
406 $ccVals[$i] = ord( substr( $val, $i, 1 ) );
407 }
408 $ccVals['_type'] = 'ol'; //this is for formatting later.
409 $this->mFilteredExifData['ComponentsConfiguration'] = $ccVals;
410 }
411
412 //GPSVersion(ID) is treated as the wrong type by php exif support.
413 //Go through each byte turning it into a version string.
414 //For example: "\x02\x02\x00\x00" -> "2.2.0.0"
415
416 //Also change exif tag name from GPSVersion (what php exif thinks it is)
417 //to GPSVersionID (what the exif standard thinks it is).
418
419 if ( isset( $this->mFilteredExifData['GPSVersion'] ) ) {
420 $val = $this->mFilteredExifData['GPSVersion'];
421 $newVal = '';
422
423 $strLen = strlen( $val );
424 for ( $i = 0; $i < $strLen; $i++ ) {
425 if ( $i !== 0 ) {
426 $newVal .= '.';
427 }
428 $newVal .= ord( substr( $val, $i, 1 ) );
429 }
430
431 if ( $this->byteOrder === 'LE' ) {
432 // Need to reverse the string
433 $newVal2 = '';
434 for ( $i = strlen( $newVal ) - 1; $i >= 0; $i-- ) {
435 $newVal2 .= substr( $newVal, $i, 1 );
436 }
437 $this->mFilteredExifData['GPSVersionID'] = $newVal2;
438 } else {
439 $this->mFilteredExifData['GPSVersionID'] = $newVal;
440 }
441 unset( $this->mFilteredExifData['GPSVersion'] );
442 }
443 }
444
445 /**
446 * Do userComment tags and similar. See pg. 34 of exif standard.
447 * basically first 8 bytes is charset, rest is value.
448 * This has not been tested on any shift-JIS strings.
449 * @param string $prop prop name.
450 */
451 private function charCodeString( $prop ) {
452 if ( isset( $this->mFilteredExifData[$prop] ) ) {
453
454 if ( strlen( $this->mFilteredExifData[$prop] ) <= 8 ) {
455 //invalid. Must be at least 9 bytes long.
456
457 $this->debug( $this->mFilteredExifData[$prop], __FUNCTION__, false );
458 unset( $this->mFilteredExifData[$prop] );
459
460 return;
461 }
462 $charCode = substr( $this->mFilteredExifData[$prop], 0, 8 );
463 $val = substr( $this->mFilteredExifData[$prop], 8 );
464
465 switch ( $charCode ) {
466 case "\x4A\x49\x53\x00\x00\x00\x00\x00":
467 //JIS
468 $charset = "Shift-JIS";
469 break;
470 case "UNICODE\x00":
471 $charset = "UTF-16" . $this->byteOrder;
472 break;
473 default: //ascii or undefined.
474 $charset = "";
475 break;
476 }
477 // This could possibly check to see if iconv is really installed
478 // or if we're using the compatibility wrapper in globalFunctions.php
479 if ( $charset ) {
480 wfSuppressWarnings();
481 $val = iconv( $charset, 'UTF-8//IGNORE', $val );
482 wfRestoreWarnings();
483 } else {
484 // if valid utf-8, assume that, otherwise assume windows-1252
485 $valCopy = $val;
486 UtfNormal::quickIsNFCVerify( $valCopy ); //validates $valCopy.
487 if ( $valCopy !== $val ) {
488 wfSuppressWarnings();
489 $val = iconv( 'Windows-1252', 'UTF-8//IGNORE', $val );
490 wfRestoreWarnings();
491 }
492 }
493
494 //trim and check to make sure not only whitespace.
495 $val = trim( $val );
496 if ( strlen( $val ) === 0 ) {
497 //only whitespace.
498 $this->debug( $this->mFilteredExifData[$prop], __FUNCTION__, "$prop: Is only whitespace" );
499 unset( $this->mFilteredExifData[$prop] );
500
501 return;
502 }
503
504 //all's good.
505 $this->mFilteredExifData[$prop] = $val;
506 }
507 }
508
509 /**
510 * Convert an Exif::UNDEFINED from a raw binary string
511 * to its value. This is sometimes needed depending on
512 * the type of UNDEFINED field
513 * @param string $prop name of property
514 */
515 private function exifPropToOrd( $prop ) {
516 if ( isset( $this->mFilteredExifData[$prop] ) ) {
517 $this->mFilteredExifData[$prop] = ord( $this->mFilteredExifData[$prop] );
518 }
519 }
520
521 /**
522 * Convert gps in exif form to a single floating point number
523 * for example 10 degress 20`40`` S -> -10.34444
524 * @param string $prop a gps coordinate exif tag name (like GPSLongitude)
525 */
526 private function exifGPStoNumber( $prop ) {
527 $loc =& $this->mFilteredExifData[$prop];
528 $dir =& $this->mFilteredExifData[$prop . 'Ref'];
529 $res = false;
530
531 if ( isset( $loc ) && isset( $dir )
532 && ( $dir === 'N' || $dir === 'S' || $dir === 'E' || $dir === 'W' )
533 ) {
534 list( $num, $denom ) = explode( '/', $loc[0] );
535 $res = $num / $denom;
536 list( $num, $denom ) = explode( '/', $loc[1] );
537 $res += ( $num / $denom ) * ( 1 / 60 );
538 list( $num, $denom ) = explode( '/', $loc[2] );
539 $res += ( $num / $denom ) * ( 1 / 3600 );
540
541 if ( $dir === 'S' || $dir === 'W' ) {
542 $res *= -1; // make negative
543 }
544 }
545
546 // update the exif records.
547
548 if ( $res !== false ) { // using !== as $res could potentially be 0
549 $this->mFilteredExifData[$prop] = $res;
550 unset( $this->mFilteredExifData[$prop . 'Ref'] );
551 } else { // if invalid
552 unset( $this->mFilteredExifData[$prop] );
553 unset( $this->mFilteredExifData[$prop . 'Ref'] );
554 }
555 }
556
557 /**
558 * Use FormatMetadata to create formatted values for display to user
559 * (is this ever used?)
560 *
561 * @deprecated since 1.18
562 */
563 function makeFormattedData() {
564 wfDeprecated( __METHOD__, '1.18' );
565 $this->mFormattedExifData = FormatMetadata::getFormattedData(
566 $this->mFilteredExifData );
567 }
568
569 /**#@-*/
570
571 /**#@+
572 * @return array
573 */
574 /**
575 * Get $this->mRawExifData
576 * @return array
577 */
578 function getData() {
579 return $this->mRawExifData;
580 }
581
582 /**
583 * Get $this->mFilteredExifData
584 */
585 function getFilteredData() {
586 return $this->mFilteredExifData;
587 }
588
589 /**
590 * Get $this->mFormattedExifData
591 *
592 * This returns the data for display to user.
593 * Its unclear if this is ever used.
594 *
595 * @deprecated since 1.18
596 */
597 function getFormattedData() {
598 wfDeprecated( __METHOD__, '1.18' );
599 if ( !$this->mFormattedExifData ) {
600 $this->makeFormattedData();
601 }
602
603 return $this->mFormattedExifData;
604 }
605
606 /**#@-*/
607
608 /**
609 * The version of the output format
610 *
611 * Before the actual metadata information is saved in the database we
612 * strip some of it since we don't want to save things like thumbnails
613 * which usually accompany Exif data. This value gets saved in the
614 * database along with the actual Exif data, and if the version in the
615 * database doesn't equal the value returned by this function the Exif
616 * data is regenerated.
617 *
618 * @return int
619 */
620 public static function version() {
621 return 2; // We don't need no bloddy constants!
622 }
623
624 /**#@+
625 * Validates if a tag value is of the type it should be according to the Exif spec
626 *
627 * @private
628 *
629 * @param $in Mixed: the input value to check
630 * @return bool
631 */
632 private function isByte( $in ) {
633 if ( !is_array( $in ) && sprintf( '%d', $in ) == $in && $in >= 0 && $in <= 255 ) {
634 $this->debug( $in, __FUNCTION__, true );
635
636 return true;
637 } else {
638 $this->debug( $in, __FUNCTION__, false );
639
640 return false;
641 }
642 }
643
644 /**
645 * @param $in
646 * @return bool
647 */
648 private function isASCII( $in ) {
649 if ( is_array( $in ) ) {
650 return false;
651 }
652
653 if ( preg_match( "/[^\x0a\x20-\x7e]/", $in ) ) {
654 $this->debug( $in, __FUNCTION__, 'found a character not in our whitelist' );
655
656 return false;
657 }
658
659 if ( preg_match( '/^\s*$/', $in ) ) {
660 $this->debug( $in, __FUNCTION__, 'input consisted solely of whitespace' );
661
662 return false;
663 }
664
665 return true;
666 }
667
668 /**
669 * @param $in
670 * @return bool
671 */
672 private function isShort( $in ) {
673 if ( !is_array( $in ) && sprintf( '%d', $in ) == $in && $in >= 0 && $in <= 65536 ) {
674 $this->debug( $in, __FUNCTION__, true );
675
676 return true;
677 } else {
678 $this->debug( $in, __FUNCTION__, false );
679
680 return false;
681 }
682 }
683
684 /**
685 * @param $in
686 * @return bool
687 */
688 private function isLong( $in ) {
689 if ( !is_array( $in ) && sprintf( '%d', $in ) == $in && $in >= 0 && $in <= 4294967296 ) {
690 $this->debug( $in, __FUNCTION__, true );
691
692 return true;
693 } else {
694 $this->debug( $in, __FUNCTION__, false );
695
696 return false;
697 }
698 }
699
700 /**
701 * @param $in
702 * @return bool
703 */
704 private function isRational( $in ) {
705 $m = array();
706
707 # Avoid division by zero
708 if ( !is_array( $in )
709 && preg_match( '/^(\d+)\/(\d+[1-9]|[1-9]\d*)$/', $in, $m )
710 ) {
711 return $this->isLong( $m[1] ) && $this->isLong( $m[2] );
712 } else {
713 $this->debug( $in, __FUNCTION__, 'fed a non-fraction value' );
714
715 return false;
716 }
717 }
718
719 /**
720 * @param $in
721 * @return bool
722 */
723 private function isUndefined( $in ) {
724 $this->debug( $in, __FUNCTION__, true );
725
726 return true;
727 }
728
729 /**
730 * @param $in
731 * @return bool
732 */
733 private function isSlong( $in ) {
734 if ( $this->isLong( abs( $in ) ) ) {
735 $this->debug( $in, __FUNCTION__, true );
736
737 return true;
738 } else {
739 $this->debug( $in, __FUNCTION__, false );
740
741 return false;
742 }
743 }
744
745 /**
746 * @param $in
747 * @return bool
748 */
749 private function isSrational( $in ) {
750 $m = array();
751
752 # Avoid division by zero
753 if ( !is_array( $in ) &&
754 preg_match( '/^(-?\d+)\/(\d+[1-9]|[1-9]\d*)$/', $in, $m )
755 ) {
756 return $this->isSlong( $m[0] ) && $this->isSlong( $m[1] );
757 } else {
758 $this->debug( $in, __FUNCTION__, 'fed a non-fraction value' );
759
760 return false;
761 }
762 }
763
764 /**#@-*/
765
766 /**
767 * Validates if a tag has a legal value according to the Exif spec
768 *
769 * @private
770 * @param string $section section where tag is located.
771 * @param string $tag the tag to check.
772 * @param $val Mixed: the value of the tag.
773 * @param $recursive Boolean: true if called recursively for array types.
774 * @return bool
775 */
776 private function validate( $section, $tag, $val, $recursive = false ) {
777 $debug = "tag is '$tag'";
778 $etype = $this->mExifTags[$section][$tag];
779 $ecount = 1;
780 if ( is_array( $etype ) ) {
781 list( $etype, $ecount ) = $etype;
782 if ( $recursive ) {
783 $ecount = 1; // checking individual elements
784 }
785 }
786 $count = count( $val );
787 if ( $ecount != $count ) {
788 $this->debug( $val, __FUNCTION__, "Expected $ecount elements for $tag but got $count" );
789
790 return false;
791 }
792 if ( $count > 1 ) {
793 foreach ( $val as $v ) {
794 if ( !$this->validate( $section, $tag, $v, true ) ) {
795 return false;
796 }
797 }
798
799 return true;
800 }
801 // Does not work if not typecast
802 switch ( (string)$etype ) {
803 case (string)Exif::BYTE:
804 $this->debug( $val, __FUNCTION__, $debug );
805
806 return $this->isByte( $val );
807 case (string)Exif::ASCII:
808 $this->debug( $val, __FUNCTION__, $debug );
809
810 return $this->isASCII( $val );
811 case (string)Exif::SHORT:
812 $this->debug( $val, __FUNCTION__, $debug );
813
814 return $this->isShort( $val );
815 case (string)Exif::LONG:
816 $this->debug( $val, __FUNCTION__, $debug );
817
818 return $this->isLong( $val );
819 case (string)Exif::RATIONAL:
820 $this->debug( $val, __FUNCTION__, $debug );
821
822 return $this->isRational( $val );
823 case (string)Exif::SHORT_OR_LONG:
824 $this->debug( $val, __FUNCTION__, $debug );
825
826 return $this->isShort( $val ) || $this->isLong( $val );
827 case (string)Exif::UNDEFINED:
828 $this->debug( $val, __FUNCTION__, $debug );
829
830 return $this->isUndefined( $val );
831 case (string)Exif::SLONG:
832 $this->debug( $val, __FUNCTION__, $debug );
833
834 return $this->isSlong( $val );
835 case (string)Exif::SRATIONAL:
836 $this->debug( $val, __FUNCTION__, $debug );
837
838 return $this->isSrational( $val );
839 case (string)Exif::IGNORE:
840 $this->debug( $val, __FUNCTION__, $debug );
841
842 return false;
843 default:
844 $this->debug( $val, __FUNCTION__, "The tag '$tag' is unknown" );
845
846 return false;
847 }
848 }
849
850 /**
851 * Convenience function for debugging output
852 *
853 * @private
854 *
855 * @param $in Mixed:
856 * @param $fname String:
857 * @param $action Mixed: , default NULL.
858 */
859 private function debug( $in, $fname, $action = null ) {
860 if ( !$this->log ) {
861 return;
862 }
863 $type = gettype( $in );
864 $class = ucfirst( __CLASS__ );
865 if ( is_array( $in ) ) {
866 $in = print_r( $in, true );
867 }
868
869 if ( $action === true ) {
870 wfDebugLog( $this->log, "$class::$fname: accepted: '$in' (type: $type)\n" );
871 } elseif ( $action === false ) {
872 wfDebugLog( $this->log, "$class::$fname: rejected: '$in' (type: $type)\n" );
873 } elseif ( $action === null ) {
874 wfDebugLog( $this->log, "$class::$fname: input was: '$in' (type: $type)\n" );
875 } else {
876 wfDebugLog( $this->log, "$class::$fname: $action (type: $type; content: '$in')\n" );
877 }
878 }
879
880 /**
881 * Convenience function for debugging output
882 *
883 * @private
884 *
885 * @param string $fname the name of the function calling this function
886 * @param $io Boolean: Specify whether we're beginning or ending
887 */
888 private function debugFile( $fname, $io ) {
889 if ( !$this->log ) {
890 return;
891 }
892 $class = ucfirst( __CLASS__ );
893 if ( $io ) {
894 wfDebugLog( $this->log, "$class::$fname: begin processing: '{$this->basename}'\n" );
895 } else {
896 wfDebugLog( $this->log, "$class::$fname: end processing: '{$this->basename}'\n" );
897 }
898 }
899 }