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