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