root/ext/exif/exif.c

/* [<][>][^][v][top][bottom][index][help] */

DEFINITIONS

This source file includes following definitions.
  1. PHP_MINFO_FUNCTION
  2. ZEND_INI_MH
  3. ZEND_INI_MH
  4. PHP_INI_BEGIN
  5. PHP_MINIT_FUNCTION
  6. PHP_MSHUTDOWN_FUNCTION
  7. ZEND_GET_MODULE
  8. exif_get_tagformat
  9. exif_get_tagname
  10. exif_char_dump
  11. php_jpg_get16
  12. php_ifd_get16u
  13. php_ifd_get16s
  14. php_ifd_get32s
  15. php_ifd_get32u
  16. php_ifd_set16u
  17. php_ifd_set32u
  18. exif_dump_data
  19. exif_convert_any_format
  20. exif_convert_any_to_int
  21. exif_get_sectionname
  22. exif_get_tag_table
  23. exif_get_sectionlist
  24. exif_error_docref
  25. exif_file_sections_add
  26. exif_file_sections_realloc
  27. exif_file_sections_free
  28. exif_iif_add_value
  29. exif_iif_add_tag
  30. exif_iif_add_int
  31. exif_iif_add_str
  32. exif_iif_add_fmt
  33. exif_iif_add_buffer
  34. exif_iif_free
  35. add_assoc_image_info
  36. exif_process_COM
  37. exif_process_CME
  38. exif_process_SOFn
  39. exif_get_markername
  40. PHP_FUNCTION
  41. exif_ifd_make_value
  42. exif_thumbnail_build
  43. exif_thumbnail_extract
  44. exif_process_undefined
  45. exif_process_string_raw
  46. exif_process_string
  47. exif_process_user_comment
  48. exif_process_unicode
  49. exif_process_IFD_in_MAKERNOTE
  50. exif_process_IFD_TAG
  51. exif_process_IFD_in_JPEG
  52. exif_process_TIFF_in_JPEG
  53. exif_process_APP1
  54. exif_process_APP12
  55. exif_scan_JPEG_header
  56. exif_scan_thumbnail
  57. exif_process_IFD_in_TIFF
  58. exif_scan_FILE_header
  59. exif_discard_imageinfo
  60. exif_read_file
  61. PHP_FUNCTION
  62. PHP_FUNCTION
  63. PHP_FUNCTION

   1 /*
   2    +----------------------------------------------------------------------+
   3    | PHP Version 5                                                        |
   4    +----------------------------------------------------------------------+
   5    | Copyright (c) 1997-2016 The PHP Group                                |
   6    +----------------------------------------------------------------------+
   7    | This source file is subject to version 3.01 of the PHP license,      |
   8    | that is bundled with this package in the file LICENSE, and is        |
   9    | available through the world-wide-web at the following url:           |
  10    | http://www.php.net/license/3_01.txt                                  |
  11    | If you did not receive a copy of the PHP license and are unable to   |
  12    | obtain it through the world-wide-web, please send a note to          |
  13    | license@php.net so we can mail you a copy immediately.               |
  14    +----------------------------------------------------------------------+
  15    | Authors: Rasmus Lerdorf <rasmus@php.net>                             |
  16    |          Marcus Boerger <helly@php.net>                              |
  17    +----------------------------------------------------------------------+
  18  */
  19 
  20 /* $Id: f94e075e5a1ebe5108ef2729498d2f198df3c078 $ */
  21 
  22 /*  ToDos
  23  *
  24  *      See if example images from http://www.exif.org have illegal
  25  *              thumbnail sizes or if code is corrupt.
  26  *      Create/Update exif headers.
  27  *      Create/Remove/Update image thumbnails.
  28  */
  29 
  30 /*  Security
  31  *
  32  *  At current time i do not see any security problems but a potential
  33  *  attacker could generate an image with recursive ifd pointers...(Marcus)
  34  */
  35 
  36 #ifdef HAVE_CONFIG_H
  37 #include "config.h"
  38 #endif
  39 
  40 #include "php.h"
  41 #include "ext/standard/file.h"
  42 
  43 #if HAVE_EXIF
  44 
  45 /* When EXIF_DEBUG is defined the module generates a lot of debug messages
  46  * that help understanding what is going on. This can and should be used
  47  * while extending the module as it shows if you are at the right position.
  48  * You are always considered to have a copy of TIFF6.0 and EXIF2.10 standard.
  49  */
  50 #undef EXIF_DEBUG
  51 
  52 #ifdef EXIF_DEBUG
  53 #define EXIFERR_DC , const char *_file, size_t _line TSRMLS_DC
  54 #define EXIFERR_CC , __FILE__, __LINE__ TSRMLS_CC
  55 #else
  56 #define EXIFERR_DC TSRMLS_DC
  57 #define EXIFERR_CC TSRMLS_CC
  58 #endif
  59 
  60 #undef EXIF_JPEG2000
  61 
  62 #include "php_exif.h"
  63 #include <math.h>
  64 #include "php_ini.h"
  65 #include "ext/standard/php_string.h"
  66 #include "ext/standard/php_image.h"
  67 #include "ext/standard/info.h"
  68 
  69 /* needed for ssize_t definition */
  70 #include <sys/types.h>
  71 
  72 typedef unsigned char uchar;
  73 
  74 #ifndef safe_emalloc
  75 # define safe_emalloc(a,b,c) emalloc((a)*(b)+(c))
  76 #endif
  77 #ifndef safe_erealloc
  78 # define safe_erealloc(p,a,b,c) erealloc(p, (a)*(b)+(c))
  79 #endif
  80 
  81 #ifndef TRUE
  82 #       define TRUE 1
  83 #       define FALSE 0
  84 #endif
  85 
  86 #ifndef max
  87 #       define max(a,b) ((a)>(b) ? (a) : (b))
  88 #endif
  89 
  90 #define EFREE_IF(ptr)   if (ptr) efree(ptr)
  91 
  92 #define MAX_IFD_NESTING_LEVEL 100
  93 
  94 /* {{{ arginfo */
  95 ZEND_BEGIN_ARG_INFO(arginfo_exif_tagname, 0)
  96         ZEND_ARG_INFO(0, index)
  97 ZEND_END_ARG_INFO()
  98 
  99 ZEND_BEGIN_ARG_INFO_EX(arginfo_exif_read_data, 0, 0, 1)
 100         ZEND_ARG_INFO(0, filename)
 101         ZEND_ARG_INFO(0, sections_needed)
 102         ZEND_ARG_INFO(0, sub_arrays)
 103         ZEND_ARG_INFO(0, read_thumbnail)
 104 ZEND_END_ARG_INFO()
 105 
 106 ZEND_BEGIN_ARG_INFO_EX(arginfo_exif_thumbnail, 0, 0, 1)
 107         ZEND_ARG_INFO(0, filename)
 108         ZEND_ARG_INFO(1, width)
 109         ZEND_ARG_INFO(1, height)
 110         ZEND_ARG_INFO(1, imagetype)
 111 ZEND_END_ARG_INFO()
 112 
 113 ZEND_BEGIN_ARG_INFO(arginfo_exif_imagetype, 0)
 114         ZEND_ARG_INFO(0, imagefile)
 115 ZEND_END_ARG_INFO()
 116 
 117 /* }}} */
 118 
 119 /* {{{ exif_functions[]
 120  */
 121 const zend_function_entry exif_functions[] = {
 122         PHP_FE(exif_read_data, arginfo_exif_read_data)
 123         PHP_FALIAS(read_exif_data, exif_read_data, arginfo_exif_read_data)
 124         PHP_FE(exif_tagname, arginfo_exif_tagname)
 125         PHP_FE(exif_thumbnail, arginfo_exif_thumbnail)
 126         PHP_FE(exif_imagetype, arginfo_exif_imagetype)
 127         PHP_FE_END
 128 };
 129 /* }}} */
 130 
 131 #define EXIF_VERSION "1.4 $Id: f94e075e5a1ebe5108ef2729498d2f198df3c078 $"
 132 
 133 /* {{{ PHP_MINFO_FUNCTION
 134  */
 135 PHP_MINFO_FUNCTION(exif)
 136 {
 137         php_info_print_table_start();
 138         php_info_print_table_row(2, "EXIF Support", "enabled");
 139         php_info_print_table_row(2, "EXIF Version", EXIF_VERSION);
 140         php_info_print_table_row(2, "Supported EXIF Version", "0220");
 141         php_info_print_table_row(2, "Supported filetypes", "JPEG,TIFF");
 142         php_info_print_table_end();
 143         DISPLAY_INI_ENTRIES();
 144 }
 145 /* }}} */
 146 
 147 ZEND_BEGIN_MODULE_GLOBALS(exif)
 148         char * encode_unicode;
 149         char * decode_unicode_be;
 150         char * decode_unicode_le;
 151         char * encode_jis;
 152         char * decode_jis_be;
 153         char * decode_jis_le;
 154 ZEND_END_MODULE_GLOBALS(exif)
 155 
 156 ZEND_DECLARE_MODULE_GLOBALS(exif)
 157 
 158 #ifdef ZTS
 159 #define EXIF_G(v) TSRMG(exif_globals_id, zend_exif_globals *, v)
 160 #else
 161 #define EXIF_G(v) (exif_globals.v)
 162 #endif
 163 
 164 /* {{{ PHP_INI
 165  */
 166 
 167 ZEND_INI_MH(OnUpdateEncode)
 168 {
 169         if (new_value && new_value_length) {
 170                 const zend_encoding **return_list;
 171                 size_t return_size;
 172                 if (FAILURE == zend_multibyte_parse_encoding_list(new_value, new_value_length,
 173         &return_list, &return_size, 0 TSRMLS_CC)) {
 174                         php_error_docref(NULL TSRMLS_CC, E_WARNING, "Illegal encoding ignored: '%s'", new_value);
 175                         return FAILURE;
 176                 }
 177                 efree(return_list);
 178         }
 179         return OnUpdateString(entry, new_value, new_value_length, mh_arg1, mh_arg2, mh_arg3, stage TSRMLS_CC);
 180 }
 181 
 182 ZEND_INI_MH(OnUpdateDecode)
 183 {
 184         if (new_value) {
 185                 const zend_encoding **return_list;
 186                 size_t return_size;
 187                 if (FAILURE == zend_multibyte_parse_encoding_list(new_value, new_value_length,
 188         &return_list, &return_size, 0 TSRMLS_CC)) {
 189                         php_error_docref(NULL TSRMLS_CC, E_WARNING, "Illegal encoding ignored: '%s'", new_value);
 190                         return FAILURE;
 191                 }
 192                 efree(return_list);
 193         }
 194         return OnUpdateString(entry, new_value, new_value_length, mh_arg1, mh_arg2, mh_arg3, stage TSRMLS_CC);
 195 }
 196 
 197 PHP_INI_BEGIN()
 198     STD_PHP_INI_ENTRY("exif.encode_unicode",          "ISO-8859-15", PHP_INI_ALL, OnUpdateEncode, encode_unicode,    zend_exif_globals, exif_globals)
 199     STD_PHP_INI_ENTRY("exif.decode_unicode_motorola", "UCS-2BE",     PHP_INI_ALL, OnUpdateDecode, decode_unicode_be, zend_exif_globals, exif_globals)
 200     STD_PHP_INI_ENTRY("exif.decode_unicode_intel",    "UCS-2LE",     PHP_INI_ALL, OnUpdateDecode, decode_unicode_le, zend_exif_globals, exif_globals)
 201     STD_PHP_INI_ENTRY("exif.encode_jis",              "",            PHP_INI_ALL, OnUpdateEncode, encode_jis,        zend_exif_globals, exif_globals)
 202     STD_PHP_INI_ENTRY("exif.decode_jis_motorola",     "JIS",         PHP_INI_ALL, OnUpdateDecode, decode_jis_be,     zend_exif_globals, exif_globals)
 203     STD_PHP_INI_ENTRY("exif.decode_jis_intel",        "JIS",         PHP_INI_ALL, OnUpdateDecode, decode_jis_le,     zend_exif_globals, exif_globals)
 204 PHP_INI_END()
 205 /* }}} */
 206 
 207 /* {{{ PHP_GINIT_FUNCTION
 208  */
 209 static PHP_GINIT_FUNCTION(exif)
 210 {
 211         exif_globals->encode_unicode    = NULL;
 212         exif_globals->decode_unicode_be = NULL;
 213         exif_globals->decode_unicode_le = NULL;
 214         exif_globals->encode_jis        = NULL;
 215         exif_globals->decode_jis_be     = NULL;
 216         exif_globals->decode_jis_le     = NULL;
 217 }
 218 /* }}} */
 219 
 220 /* {{{ PHP_MINIT_FUNCTION(exif)
 221    Get the size of an image as 4-element array */
 222 PHP_MINIT_FUNCTION(exif)
 223 {
 224         REGISTER_INI_ENTRIES();
 225         if (zend_hash_exists(&module_registry, "mbstring", sizeof("mbstring"))) {
 226                 REGISTER_LONG_CONSTANT("EXIF_USE_MBSTRING", 1, CONST_CS | CONST_PERSISTENT);
 227         } else {
 228                 REGISTER_LONG_CONSTANT("EXIF_USE_MBSTRING", 0, CONST_CS | CONST_PERSISTENT);
 229         }
 230         return SUCCESS;
 231 }
 232 /* }}} */
 233 
 234 /* {{{ PHP_MSHUTDOWN_FUNCTION
 235  */
 236 PHP_MSHUTDOWN_FUNCTION(exif)
 237 {
 238         UNREGISTER_INI_ENTRIES();
 239         return SUCCESS;
 240 }
 241 /* }}} */
 242 
 243 /* {{{ exif dependencies */
 244 static const zend_module_dep exif_module_deps[] = {
 245         ZEND_MOD_REQUIRED("standard")
 246         ZEND_MOD_OPTIONAL("mbstring")
 247         ZEND_MOD_END
 248 };
 249 /* }}} */
 250 
 251 /* {{{ exif_module_entry
 252  */
 253 zend_module_entry exif_module_entry = {
 254         STANDARD_MODULE_HEADER_EX, NULL,
 255         exif_module_deps,
 256         "exif",
 257         exif_functions,
 258         PHP_MINIT(exif),
 259         PHP_MSHUTDOWN(exif),
 260         NULL, NULL,
 261         PHP_MINFO(exif),
 262 #if ZEND_MODULE_API_NO >= 20010901
 263         EXIF_VERSION,
 264 #endif
 265 #if ZEND_MODULE_API_NO >= 20060613
 266         PHP_MODULE_GLOBALS(exif),
 267         PHP_GINIT(exif),
 268         NULL,
 269         NULL,
 270         STANDARD_MODULE_PROPERTIES_EX
 271 #else
 272         STANDARD_MODULE_PROPERTIES
 273 #endif
 274 };
 275 /* }}} */
 276 
 277 #ifdef COMPILE_DL_EXIF
 278 ZEND_GET_MODULE(exif)
 279 #endif
 280 
 281 /* {{{ php_strnlen
 282  * get length of string if buffer if less than buffer size or buffer size */
 283 static size_t php_strnlen(char* str, size_t maxlen) {
 284         size_t len = 0;
 285 
 286         if (str && maxlen && *str) {
 287                 do {
 288                         len++;
 289                 } while (--maxlen && *(++str));
 290         }
 291         return len;
 292 }
 293 /* }}} */
 294 
 295 /* {{{ error messages
 296 */
 297 static const char * EXIF_ERROR_FILEEOF   = "Unexpected end of file reached";
 298 static const char * EXIF_ERROR_CORRUPT   = "File structure corrupted";
 299 static const char * EXIF_ERROR_THUMBEOF  = "Thumbnail goes IFD boundary or end of file reached";
 300 static const char * EXIF_ERROR_FSREALLOC = "Illegal reallocating of undefined file section";
 301 
 302 #define EXIF_ERRLOG_FILEEOF(ImageInfo)    exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "%s", EXIF_ERROR_FILEEOF);
 303 #define EXIF_ERRLOG_CORRUPT(ImageInfo)    exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "%s", EXIF_ERROR_CORRUPT);
 304 #define EXIF_ERRLOG_THUMBEOF(ImageInfo)   exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "%s", EXIF_ERROR_THUMBEOF);
 305 #define EXIF_ERRLOG_FSREALLOC(ImageInfo)  exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "%s", EXIF_ERROR_FSREALLOC);
 306 /* }}} */
 307 
 308 /* {{{ format description defines
 309    Describes format descriptor
 310 */
 311 static int php_tiff_bytes_per_format[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8, 1};
 312 #define NUM_FORMATS 13
 313 
 314 #define TAG_FMT_BYTE       1
 315 #define TAG_FMT_STRING     2
 316 #define TAG_FMT_USHORT     3
 317 #define TAG_FMT_ULONG      4
 318 #define TAG_FMT_URATIONAL  5
 319 #define TAG_FMT_SBYTE      6
 320 #define TAG_FMT_UNDEFINED  7
 321 #define TAG_FMT_SSHORT     8
 322 #define TAG_FMT_SLONG      9
 323 #define TAG_FMT_SRATIONAL 10
 324 #define TAG_FMT_SINGLE    11
 325 #define TAG_FMT_DOUBLE    12
 326 #define TAG_FMT_IFD       13
 327 
 328 #ifdef EXIF_DEBUG
 329 static char *exif_get_tagformat(int format)
 330 {
 331         switch(format) {
 332                 case TAG_FMT_BYTE:      return "BYTE";
 333                 case TAG_FMT_STRING:    return "STRING";
 334                 case TAG_FMT_USHORT:    return "USHORT";
 335                 case TAG_FMT_ULONG:     return "ULONG";
 336                 case TAG_FMT_URATIONAL: return "URATIONAL";
 337                 case TAG_FMT_SBYTE:     return "SBYTE";
 338                 case TAG_FMT_UNDEFINED: return "UNDEFINED";
 339                 case TAG_FMT_SSHORT:    return "SSHORT";
 340                 case TAG_FMT_SLONG:     return "SLONG";
 341                 case TAG_FMT_SRATIONAL: return "SRATIONAL";
 342                 case TAG_FMT_SINGLE:    return "SINGLE";
 343                 case TAG_FMT_DOUBLE:    return "DOUBLE";
 344                 case TAG_FMT_IFD:       return "IFD";
 345         }
 346         return "*Illegal";
 347 }
 348 #endif
 349 
 350 /* Describes tag values */
 351 #define TAG_GPS_VERSION_ID              0x0000
 352 #define TAG_GPS_LATITUDE_REF            0x0001
 353 #define TAG_GPS_LATITUDE                0x0002
 354 #define TAG_GPS_LONGITUDE_REF           0x0003
 355 #define TAG_GPS_LONGITUDE               0x0004
 356 #define TAG_GPS_ALTITUDE_REF            0x0005
 357 #define TAG_GPS_ALTITUDE                0x0006
 358 #define TAG_GPS_TIME_STAMP              0x0007
 359 #define TAG_GPS_SATELLITES              0x0008
 360 #define TAG_GPS_STATUS                  0x0009
 361 #define TAG_GPS_MEASURE_MODE            0x000A
 362 #define TAG_GPS_DOP                     0x000B
 363 #define TAG_GPS_SPEED_REF               0x000C
 364 #define TAG_GPS_SPEED                   0x000D
 365 #define TAG_GPS_TRACK_REF               0x000E
 366 #define TAG_GPS_TRACK                   0x000F
 367 #define TAG_GPS_IMG_DIRECTION_REF       0x0010
 368 #define TAG_GPS_IMG_DIRECTION           0x0011
 369 #define TAG_GPS_MAP_DATUM               0x0012
 370 #define TAG_GPS_DEST_LATITUDE_REF       0x0013
 371 #define TAG_GPS_DEST_LATITUDE           0x0014
 372 #define TAG_GPS_DEST_LONGITUDE_REF      0x0015
 373 #define TAG_GPS_DEST_LONGITUDE          0x0016
 374 #define TAG_GPS_DEST_BEARING_REF        0x0017
 375 #define TAG_GPS_DEST_BEARING            0x0018
 376 #define TAG_GPS_DEST_DISTANCE_REF       0x0019
 377 #define TAG_GPS_DEST_DISTANCE           0x001A
 378 #define TAG_GPS_PROCESSING_METHOD       0x001B
 379 #define TAG_GPS_AREA_INFORMATION        0x001C
 380 #define TAG_GPS_DATE_STAMP              0x001D
 381 #define TAG_GPS_DIFFERENTIAL            0x001E
 382 #define TAG_TIFF_COMMENT                0x00FE /* SHOUDLNT HAPPEN */
 383 #define TAG_NEW_SUBFILE                 0x00FE /* New version of subfile tag */
 384 #define TAG_SUBFILE_TYPE                0x00FF /* Old version of subfile tag */
 385 #define TAG_IMAGEWIDTH                  0x0100
 386 #define TAG_IMAGEHEIGHT                 0x0101
 387 #define TAG_BITS_PER_SAMPLE             0x0102
 388 #define TAG_COMPRESSION                 0x0103
 389 #define TAG_PHOTOMETRIC_INTERPRETATION  0x0106
 390 #define TAG_TRESHHOLDING                0x0107
 391 #define TAG_CELL_WIDTH                  0x0108
 392 #define TAG_CELL_HEIGHT                 0x0109
 393 #define TAG_FILL_ORDER                  0x010A
 394 #define TAG_DOCUMENT_NAME               0x010D
 395 #define TAG_IMAGE_DESCRIPTION           0x010E
 396 #define TAG_MAKE                        0x010F
 397 #define TAG_MODEL                       0x0110
 398 #define TAG_STRIP_OFFSETS               0x0111
 399 #define TAG_ORIENTATION                 0x0112
 400 #define TAG_SAMPLES_PER_PIXEL           0x0115
 401 #define TAG_ROWS_PER_STRIP              0x0116
 402 #define TAG_STRIP_BYTE_COUNTS           0x0117
 403 #define TAG_MIN_SAMPPLE_VALUE           0x0118
 404 #define TAG_MAX_SAMPLE_VALUE            0x0119
 405 #define TAG_X_RESOLUTION                0x011A
 406 #define TAG_Y_RESOLUTION                0x011B
 407 #define TAG_PLANAR_CONFIGURATION        0x011C
 408 #define TAG_PAGE_NAME                   0x011D
 409 #define TAG_X_POSITION                  0x011E
 410 #define TAG_Y_POSITION                  0x011F
 411 #define TAG_FREE_OFFSETS                0x0120
 412 #define TAG_FREE_BYTE_COUNTS            0x0121
 413 #define TAG_GRAY_RESPONSE_UNIT          0x0122
 414 #define TAG_GRAY_RESPONSE_CURVE         0x0123
 415 #define TAG_RESOLUTION_UNIT             0x0128
 416 #define TAG_PAGE_NUMBER                 0x0129
 417 #define TAG_TRANSFER_FUNCTION           0x012D
 418 #define TAG_SOFTWARE                    0x0131
 419 #define TAG_DATETIME                    0x0132
 420 #define TAG_ARTIST                      0x013B
 421 #define TAG_HOST_COMPUTER               0x013C
 422 #define TAG_PREDICTOR                   0x013D
 423 #define TAG_WHITE_POINT                 0x013E
 424 #define TAG_PRIMARY_CHROMATICITIES      0x013F
 425 #define TAG_COLOR_MAP                   0x0140
 426 #define TAG_HALFTONE_HINTS              0x0141
 427 #define TAG_TILE_WIDTH                  0x0142
 428 #define TAG_TILE_LENGTH                 0x0143
 429 #define TAG_TILE_OFFSETS                0x0144
 430 #define TAG_TILE_BYTE_COUNTS            0x0145
 431 #define TAG_SUB_IFD                     0x014A
 432 #define TAG_INK_SETMPUTER               0x014C
 433 #define TAG_INK_NAMES                   0x014D
 434 #define TAG_NUMBER_OF_INKS              0x014E
 435 #define TAG_DOT_RANGE                   0x0150
 436 #define TAG_TARGET_PRINTER              0x0151
 437 #define TAG_EXTRA_SAMPLE                0x0152
 438 #define TAG_SAMPLE_FORMAT               0x0153
 439 #define TAG_S_MIN_SAMPLE_VALUE          0x0154
 440 #define TAG_S_MAX_SAMPLE_VALUE          0x0155
 441 #define TAG_TRANSFER_RANGE              0x0156
 442 #define TAG_JPEG_TABLES                 0x015B
 443 #define TAG_JPEG_PROC                   0x0200
 444 #define TAG_JPEG_INTERCHANGE_FORMAT     0x0201
 445 #define TAG_JPEG_INTERCHANGE_FORMAT_LEN 0x0202
 446 #define TAG_JPEG_RESTART_INTERVAL       0x0203
 447 #define TAG_JPEG_LOSSLESS_PREDICTOR     0x0205
 448 #define TAG_JPEG_POINT_TRANSFORMS       0x0206
 449 #define TAG_JPEG_Q_TABLES               0x0207
 450 #define TAG_JPEG_DC_TABLES              0x0208
 451 #define TAG_JPEG_AC_TABLES              0x0209
 452 #define TAG_YCC_COEFFICIENTS            0x0211
 453 #define TAG_YCC_SUB_SAMPLING            0x0212
 454 #define TAG_YCC_POSITIONING             0x0213
 455 #define TAG_REFERENCE_BLACK_WHITE       0x0214
 456 /* 0x0301 - 0x0302 */
 457 /* 0x0320 */
 458 /* 0x0343 */
 459 /* 0x5001 - 0x501B */
 460 /* 0x5021 - 0x503B */
 461 /* 0x5090 - 0x5091 */
 462 /* 0x5100 - 0x5101 */
 463 /* 0x5110 - 0x5113 */
 464 /* 0x80E3 - 0x80E6 */
 465 /* 0x828d - 0x828F */
 466 #define TAG_COPYRIGHT                   0x8298
 467 #define TAG_EXPOSURETIME                0x829A
 468 #define TAG_FNUMBER                     0x829D
 469 #define TAG_EXIF_IFD_POINTER            0x8769
 470 #define TAG_ICC_PROFILE                 0x8773
 471 #define TAG_EXPOSURE_PROGRAM            0x8822
 472 #define TAG_SPECTRAL_SENSITY            0x8824
 473 #define TAG_GPS_IFD_POINTER             0x8825
 474 #define TAG_ISOSPEED                    0x8827
 475 #define TAG_OPTOELECTRIC_CONVERSION_F   0x8828
 476 /* 0x8829 - 0x882b */
 477 #define TAG_EXIFVERSION                 0x9000
 478 #define TAG_DATE_TIME_ORIGINAL          0x9003
 479 #define TAG_DATE_TIME_DIGITIZED         0x9004
 480 #define TAG_COMPONENT_CONFIG            0x9101
 481 #define TAG_COMPRESSED_BITS_PER_PIXEL   0x9102
 482 #define TAG_SHUTTERSPEED                0x9201
 483 #define TAG_APERTURE                    0x9202
 484 #define TAG_BRIGHTNESS_VALUE            0x9203
 485 #define TAG_EXPOSURE_BIAS_VALUE         0x9204
 486 #define TAG_MAX_APERTURE                0x9205
 487 #define TAG_SUBJECT_DISTANCE            0x9206
 488 #define TAG_METRIC_MODULE               0x9207
 489 #define TAG_LIGHT_SOURCE                0x9208
 490 #define TAG_FLASH                       0x9209
 491 #define TAG_FOCAL_LENGTH                0x920A
 492 /* 0x920B - 0x920D */
 493 /* 0x9211 - 0x9216 */
 494 #define TAG_SUBJECT_AREA                0x9214
 495 #define TAG_MAKER_NOTE                  0x927C
 496 #define TAG_USERCOMMENT                 0x9286
 497 #define TAG_SUB_SEC_TIME                0x9290
 498 #define TAG_SUB_SEC_TIME_ORIGINAL       0x9291
 499 #define TAG_SUB_SEC_TIME_DIGITIZED      0x9292
 500 /* 0x923F */
 501 /* 0x935C */
 502 #define TAG_XP_TITLE                    0x9C9B
 503 #define TAG_XP_COMMENTS                 0x9C9C
 504 #define TAG_XP_AUTHOR                   0x9C9D
 505 #define TAG_XP_KEYWORDS                 0x9C9E
 506 #define TAG_XP_SUBJECT                  0x9C9F
 507 #define TAG_FLASH_PIX_VERSION           0xA000
 508 #define TAG_COLOR_SPACE                 0xA001
 509 #define TAG_COMP_IMAGE_WIDTH            0xA002 /* compressed images only */
 510 #define TAG_COMP_IMAGE_HEIGHT           0xA003
 511 #define TAG_RELATED_SOUND_FILE          0xA004
 512 #define TAG_INTEROP_IFD_POINTER         0xA005 /* IFD pointer */
 513 #define TAG_FLASH_ENERGY                0xA20B
 514 #define TAG_SPATIAL_FREQUENCY_RESPONSE  0xA20C
 515 #define TAG_FOCALPLANE_X_RES            0xA20E
 516 #define TAG_FOCALPLANE_Y_RES            0xA20F
 517 #define TAG_FOCALPLANE_RESOLUTION_UNIT  0xA210
 518 #define TAG_SUBJECT_LOCATION            0xA214
 519 #define TAG_EXPOSURE_INDEX              0xA215
 520 #define TAG_SENSING_METHOD              0xA217
 521 #define TAG_FILE_SOURCE                 0xA300
 522 #define TAG_SCENE_TYPE                  0xA301
 523 #define TAG_CFA_PATTERN                 0xA302
 524 #define TAG_CUSTOM_RENDERED             0xA401
 525 #define TAG_EXPOSURE_MODE               0xA402
 526 #define TAG_WHITE_BALANCE               0xA403
 527 #define TAG_DIGITAL_ZOOM_RATIO          0xA404
 528 #define TAG_FOCAL_LENGTH_IN_35_MM_FILM  0xA405
 529 #define TAG_SCENE_CAPTURE_TYPE          0xA406
 530 #define TAG_GAIN_CONTROL                0xA407
 531 #define TAG_CONTRAST                    0xA408
 532 #define TAG_SATURATION                  0xA409
 533 #define TAG_SHARPNESS                   0xA40A
 534 #define TAG_DEVICE_SETTING_DESCRIPTION  0xA40B
 535 #define TAG_SUBJECT_DISTANCE_RANGE      0xA40C
 536 #define TAG_IMAGE_UNIQUE_ID             0xA420
 537 
 538 /* Olympus specific tags */
 539 #define TAG_OLYMPUS_SPECIALMODE         0x0200
 540 #define TAG_OLYMPUS_JPEGQUAL            0x0201
 541 #define TAG_OLYMPUS_MACRO               0x0202
 542 #define TAG_OLYMPUS_DIGIZOOM            0x0204
 543 #define TAG_OLYMPUS_SOFTWARERELEASE     0x0207
 544 #define TAG_OLYMPUS_PICTINFO            0x0208
 545 #define TAG_OLYMPUS_CAMERAID            0x0209
 546 /* end Olympus specific tags */
 547 
 548 /* Internal */
 549 #define TAG_NONE                                -1 /* note that -1 <> 0xFFFF */
 550 #define TAG_COMPUTED_VALUE                      -2
 551 #define TAG_END_OF_LIST                 0xFFFD
 552 
 553 /* Values for TAG_PHOTOMETRIC_INTERPRETATION */
 554 #define PMI_BLACK_IS_ZERO       0
 555 #define PMI_WHITE_IS_ZERO       1
 556 #define PMI_RGB                     2
 557 #define PMI_PALETTE_COLOR       3
 558 #define PMI_TRANSPARENCY_MASK   4
 559 #define PMI_SEPARATED           5
 560 #define PMI_YCBCR               6
 561 #define PMI_CIELAB              8
 562 
 563 /* }}} */
 564 
 565 /* {{{ TabTable[]
 566  */
 567 typedef const struct {
 568         unsigned short Tag;
 569         char *Desc;
 570 } tag_info_type;
 571 
 572 typedef tag_info_type  tag_info_array[];
 573 typedef tag_info_type  *tag_table_type;
 574 
 575 #define TAG_TABLE_END \
 576   {TAG_NONE,           "No tag value"},\
 577   {TAG_COMPUTED_VALUE, "Computed value"},\
 578   {TAG_END_OF_LIST,    ""}  /* Important for exif_get_tagname() IF value != "" function result is != false */
 579 
 580 static tag_info_array tag_table_IFD = {
 581   { 0x000B, "ACDComment"},
 582   { 0x00FE, "NewSubFile"}, /* better name it 'ImageType' ? */
 583   { 0x00FF, "SubFile"},
 584   { 0x0100, "ImageWidth"},
 585   { 0x0101, "ImageLength"},
 586   { 0x0102, "BitsPerSample"},
 587   { 0x0103, "Compression"},
 588   { 0x0106, "PhotometricInterpretation"},
 589   { 0x010A, "FillOrder"},
 590   { 0x010D, "DocumentName"},
 591   { 0x010E, "ImageDescription"},
 592   { 0x010F, "Make"},
 593   { 0x0110, "Model"},
 594   { 0x0111, "StripOffsets"},
 595   { 0x0112, "Orientation"},
 596   { 0x0115, "SamplesPerPixel"},
 597   { 0x0116, "RowsPerStrip"},
 598   { 0x0117, "StripByteCounts"},
 599   { 0x0118, "MinSampleValue"},
 600   { 0x0119, "MaxSampleValue"},
 601   { 0x011A, "XResolution"},
 602   { 0x011B, "YResolution"},
 603   { 0x011C, "PlanarConfiguration"},
 604   { 0x011D, "PageName"},
 605   { 0x011E, "XPosition"},
 606   { 0x011F, "YPosition"},
 607   { 0x0120, "FreeOffsets"},
 608   { 0x0121, "FreeByteCounts"},
 609   { 0x0122, "GrayResponseUnit"},
 610   { 0x0123, "GrayResponseCurve"},
 611   { 0x0124, "T4Options"},
 612   { 0x0125, "T6Options"},
 613   { 0x0128, "ResolutionUnit"},
 614   { 0x0129, "PageNumber"},
 615   { 0x012D, "TransferFunction"},
 616   { 0x0131, "Software"},
 617   { 0x0132, "DateTime"},
 618   { 0x013B, "Artist"},
 619   { 0x013C, "HostComputer"},
 620   { 0x013D, "Predictor"},
 621   { 0x013E, "WhitePoint"},
 622   { 0x013F, "PrimaryChromaticities"},
 623   { 0x0140, "ColorMap"},
 624   { 0x0141, "HalfToneHints"},
 625   { 0x0142, "TileWidth"},
 626   { 0x0143, "TileLength"},
 627   { 0x0144, "TileOffsets"},
 628   { 0x0145, "TileByteCounts"},
 629   { 0x014A, "SubIFD"},
 630   { 0x014C, "InkSet"},
 631   { 0x014D, "InkNames"},
 632   { 0x014E, "NumberOfInks"},
 633   { 0x0150, "DotRange"},
 634   { 0x0151, "TargetPrinter"},
 635   { 0x0152, "ExtraSample"},
 636   { 0x0153, "SampleFormat"},
 637   { 0x0154, "SMinSampleValue"},
 638   { 0x0155, "SMaxSampleValue"},
 639   { 0x0156, "TransferRange"},
 640   { 0x0157, "ClipPath"},
 641   { 0x0158, "XClipPathUnits"},
 642   { 0x0159, "YClipPathUnits"},
 643   { 0x015A, "Indexed"},
 644   { 0x015B, "JPEGTables"},
 645   { 0x015F, "OPIProxy"},
 646   { 0x0200, "JPEGProc"},
 647   { 0x0201, "JPEGInterchangeFormat"},
 648   { 0x0202, "JPEGInterchangeFormatLength"},
 649   { 0x0203, "JPEGRestartInterval"},
 650   { 0x0205, "JPEGLosslessPredictors"},
 651   { 0x0206, "JPEGPointTransforms"},
 652   { 0x0207, "JPEGQTables"},
 653   { 0x0208, "JPEGDCTables"},
 654   { 0x0209, "JPEGACTables"},
 655   { 0x0211, "YCbCrCoefficients"},
 656   { 0x0212, "YCbCrSubSampling"},
 657   { 0x0213, "YCbCrPositioning"},
 658   { 0x0214, "ReferenceBlackWhite"},
 659   { 0x02BC, "ExtensibleMetadataPlatform"}, /* XAP: Extensible Authoring Publishing, obsoleted by XMP: Extensible Metadata Platform */
 660   { 0x0301, "Gamma"},
 661   { 0x0302, "ICCProfileDescriptor"},
 662   { 0x0303, "SRGBRenderingIntent"},
 663   { 0x0320, "ImageTitle"},
 664   { 0x5001, "ResolutionXUnit"},
 665   { 0x5002, "ResolutionYUnit"},
 666   { 0x5003, "ResolutionXLengthUnit"},
 667   { 0x5004, "ResolutionYLengthUnit"},
 668   { 0x5005, "PrintFlags"},
 669   { 0x5006, "PrintFlagsVersion"},
 670   { 0x5007, "PrintFlagsCrop"},
 671   { 0x5008, "PrintFlagsBleedWidth"},
 672   { 0x5009, "PrintFlagsBleedWidthScale"},
 673   { 0x500A, "HalftoneLPI"},
 674   { 0x500B, "HalftoneLPIUnit"},
 675   { 0x500C, "HalftoneDegree"},
 676   { 0x500D, "HalftoneShape"},
 677   { 0x500E, "HalftoneMisc"},
 678   { 0x500F, "HalftoneScreen"},
 679   { 0x5010, "JPEGQuality"},
 680   { 0x5011, "GridSize"},
 681   { 0x5012, "ThumbnailFormat"},
 682   { 0x5013, "ThumbnailWidth"},
 683   { 0x5014, "ThumbnailHeight"},
 684   { 0x5015, "ThumbnailColorDepth"},
 685   { 0x5016, "ThumbnailPlanes"},
 686   { 0x5017, "ThumbnailRawBytes"},
 687   { 0x5018, "ThumbnailSize"},
 688   { 0x5019, "ThumbnailCompressedSize"},
 689   { 0x501A, "ColorTransferFunction"},
 690   { 0x501B, "ThumbnailData"},
 691   { 0x5020, "ThumbnailImageWidth"},
 692   { 0x5021, "ThumbnailImageHeight"},
 693   { 0x5022, "ThumbnailBitsPerSample"},
 694   { 0x5023, "ThumbnailCompression"},
 695   { 0x5024, "ThumbnailPhotometricInterp"},
 696   { 0x5025, "ThumbnailImageDescription"},
 697   { 0x5026, "ThumbnailEquipMake"},
 698   { 0x5027, "ThumbnailEquipModel"},
 699   { 0x5028, "ThumbnailStripOffsets"},
 700   { 0x5029, "ThumbnailOrientation"},
 701   { 0x502A, "ThumbnailSamplesPerPixel"},
 702   { 0x502B, "ThumbnailRowsPerStrip"},
 703   { 0x502C, "ThumbnailStripBytesCount"},
 704   { 0x502D, "ThumbnailResolutionX"},
 705   { 0x502E, "ThumbnailResolutionY"},
 706   { 0x502F, "ThumbnailPlanarConfig"},
 707   { 0x5030, "ThumbnailResolutionUnit"},
 708   { 0x5031, "ThumbnailTransferFunction"},
 709   { 0x5032, "ThumbnailSoftwareUsed"},
 710   { 0x5033, "ThumbnailDateTime"},
 711   { 0x5034, "ThumbnailArtist"},
 712   { 0x5035, "ThumbnailWhitePoint"},
 713   { 0x5036, "ThumbnailPrimaryChromaticities"},
 714   { 0x5037, "ThumbnailYCbCrCoefficients"},
 715   { 0x5038, "ThumbnailYCbCrSubsampling"},
 716   { 0x5039, "ThumbnailYCbCrPositioning"},
 717   { 0x503A, "ThumbnailRefBlackWhite"},
 718   { 0x503B, "ThumbnailCopyRight"},
 719   { 0x5090, "LuminanceTable"},
 720   { 0x5091, "ChrominanceTable"},
 721   { 0x5100, "FrameDelay"},
 722   { 0x5101, "LoopCount"},
 723   { 0x5110, "PixelUnit"},
 724   { 0x5111, "PixelPerUnitX"},
 725   { 0x5112, "PixelPerUnitY"},
 726   { 0x5113, "PaletteHistogram"},
 727   { 0x1000, "RelatedImageFileFormat"},
 728   { 0x800D, "ImageID"},
 729   { 0x80E3, "Matteing"},   /* obsoleted by ExtraSamples */
 730   { 0x80E4, "DataType"},   /* obsoleted by SampleFormat */
 731   { 0x80E5, "ImageDepth"},
 732   { 0x80E6, "TileDepth"},
 733   { 0x828D, "CFARepeatPatternDim"},
 734   { 0x828E, "CFAPattern"},
 735   { 0x828F, "BatteryLevel"},
 736   { 0x8298, "Copyright"},
 737   { 0x829A, "ExposureTime"},
 738   { 0x829D, "FNumber"},
 739   { 0x83BB, "IPTC/NAA"},
 740   { 0x84E3, "IT8RasterPadding"},
 741   { 0x84E5, "IT8ColorTable"},
 742   { 0x8649, "ImageResourceInformation"}, /* PhotoShop */
 743   { 0x8769, "Exif_IFD_Pointer"},
 744   { 0x8773, "ICC_Profile"},
 745   { 0x8822, "ExposureProgram"},
 746   { 0x8824, "SpectralSensity"},
 747   { 0x8828, "OECF"},
 748   { 0x8825, "GPS_IFD_Pointer"},
 749   { 0x8827, "ISOSpeedRatings"},
 750   { 0x8828, "OECF"},
 751   { 0x9000, "ExifVersion"},
 752   { 0x9003, "DateTimeOriginal"},
 753   { 0x9004, "DateTimeDigitized"},
 754   { 0x9101, "ComponentsConfiguration"},
 755   { 0x9102, "CompressedBitsPerPixel"},
 756   { 0x9201, "ShutterSpeedValue"},
 757   { 0x9202, "ApertureValue"},
 758   { 0x9203, "BrightnessValue"},
 759   { 0x9204, "ExposureBiasValue"},
 760   { 0x9205, "MaxApertureValue"},
 761   { 0x9206, "SubjectDistance"},
 762   { 0x9207, "MeteringMode"},
 763   { 0x9208, "LightSource"},
 764   { 0x9209, "Flash"},
 765   { 0x920A, "FocalLength"},
 766   { 0x920B, "FlashEnergy"},                 /* 0xA20B  in JPEG   */
 767   { 0x920C, "SpatialFrequencyResponse"},    /* 0xA20C    -  -    */
 768   { 0x920D, "Noise"},
 769   { 0x920E, "FocalPlaneXResolution"},       /* 0xA20E    -  -    */
 770   { 0x920F, "FocalPlaneYResolution"},       /* 0xA20F    -  -    */
 771   { 0x9210, "FocalPlaneResolutionUnit"},    /* 0xA210    -  -    */
 772   { 0x9211, "ImageNumber"},
 773   { 0x9212, "SecurityClassification"},
 774   { 0x9213, "ImageHistory"},
 775   { 0x9214, "SubjectLocation"},             /* 0xA214    -  -    */
 776   { 0x9215, "ExposureIndex"},               /* 0xA215    -  -    */
 777   { 0x9216, "TIFF/EPStandardID"},
 778   { 0x9217, "SensingMethod"},               /* 0xA217    -  -    */
 779   { 0x923F, "StoNits"},
 780   { 0x927C, "MakerNote"},
 781   { 0x9286, "UserComment"},
 782   { 0x9290, "SubSecTime"},
 783   { 0x9291, "SubSecTimeOriginal"},
 784   { 0x9292, "SubSecTimeDigitized"},
 785   { 0x935C, "ImageSourceData"},             /* "Adobe Photoshop Document Data Block": 8BIM... */
 786   { 0x9c9b, "Title" },                      /* Win XP specific, Unicode  */
 787   { 0x9c9c, "Comments" },                   /* Win XP specific, Unicode  */
 788   { 0x9c9d, "Author" },                     /* Win XP specific, Unicode  */
 789   { 0x9c9e, "Keywords" },                   /* Win XP specific, Unicode  */
 790   { 0x9c9f, "Subject" },                    /* Win XP specific, Unicode, not to be confused with SubjectDistance and SubjectLocation */
 791   { 0xA000, "FlashPixVersion"},
 792   { 0xA001, "ColorSpace"},
 793   { 0xA002, "ExifImageWidth"},
 794   { 0xA003, "ExifImageLength"},
 795   { 0xA004, "RelatedSoundFile"},
 796   { 0xA005, "InteroperabilityOffset"},
 797   { 0xA20B, "FlashEnergy"},                 /* 0x920B in TIFF/EP */
 798   { 0xA20C, "SpatialFrequencyResponse"},    /* 0x920C    -  -    */
 799   { 0xA20D, "Noise"},
 800   { 0xA20E, "FocalPlaneXResolution"},           /* 0x920E    -  -    */
 801   { 0xA20F, "FocalPlaneYResolution"},       /* 0x920F    -  -    */
 802   { 0xA210, "FocalPlaneResolutionUnit"},    /* 0x9210    -  -    */
 803   { 0xA211, "ImageNumber"},
 804   { 0xA212, "SecurityClassification"},
 805   { 0xA213, "ImageHistory"},
 806   { 0xA214, "SubjectLocation"},             /* 0x9214    -  -    */
 807   { 0xA215, "ExposureIndex"},               /* 0x9215    -  -    */
 808   { 0xA216, "TIFF/EPStandardID"},
 809   { 0xA217, "SensingMethod"},               /* 0x9217    -  -    */
 810   { 0xA300, "FileSource"},
 811   { 0xA301, "SceneType"},
 812   { 0xA302, "CFAPattern"},
 813   { 0xA401, "CustomRendered"},
 814   { 0xA402, "ExposureMode"},
 815   { 0xA403, "WhiteBalance"},
 816   { 0xA404, "DigitalZoomRatio"},
 817   { 0xA405, "FocalLengthIn35mmFilm"},
 818   { 0xA406, "SceneCaptureType"},
 819   { 0xA407, "GainControl"},
 820   { 0xA408, "Contrast"},
 821   { 0xA409, "Saturation"},
 822   { 0xA40A, "Sharpness"},
 823   { 0xA40B, "DeviceSettingDescription"},
 824   { 0xA40C, "SubjectDistanceRange"},
 825   { 0xA420, "ImageUniqueID"},
 826   TAG_TABLE_END
 827 } ;
 828 
 829 static tag_info_array tag_table_GPS = {
 830   { 0x0000, "GPSVersion"},
 831   { 0x0001, "GPSLatitudeRef"},
 832   { 0x0002, "GPSLatitude"},
 833   { 0x0003, "GPSLongitudeRef"},
 834   { 0x0004, "GPSLongitude"},
 835   { 0x0005, "GPSAltitudeRef"},
 836   { 0x0006, "GPSAltitude"},
 837   { 0x0007, "GPSTimeStamp"},
 838   { 0x0008, "GPSSatellites"},
 839   { 0x0009, "GPSStatus"},
 840   { 0x000A, "GPSMeasureMode"},
 841   { 0x000B, "GPSDOP"},
 842   { 0x000C, "GPSSpeedRef"},
 843   { 0x000D, "GPSSpeed"},
 844   { 0x000E, "GPSTrackRef"},
 845   { 0x000F, "GPSTrack"},
 846   { 0x0010, "GPSImgDirectionRef"},
 847   { 0x0011, "GPSImgDirection"},
 848   { 0x0012, "GPSMapDatum"},
 849   { 0x0013, "GPSDestLatitudeRef"},
 850   { 0x0014, "GPSDestLatitude"},
 851   { 0x0015, "GPSDestLongitudeRef"},
 852   { 0x0016, "GPSDestLongitude"},
 853   { 0x0017, "GPSDestBearingRef"},
 854   { 0x0018, "GPSDestBearing"},
 855   { 0x0019, "GPSDestDistanceRef"},
 856   { 0x001A, "GPSDestDistance"},
 857   { 0x001B, "GPSProcessingMode"},
 858   { 0x001C, "GPSAreaInformation"},
 859   { 0x001D, "GPSDateStamp"},
 860   { 0x001E, "GPSDifferential"},
 861   TAG_TABLE_END
 862 };
 863 
 864 static tag_info_array tag_table_IOP = {
 865   { 0x0001, "InterOperabilityIndex"}, /* should be 'R98' or 'THM' */
 866   { 0x0002, "InterOperabilityVersion"},
 867   { 0x1000, "RelatedFileFormat"},
 868   { 0x1001, "RelatedImageWidth"},
 869   { 0x1002, "RelatedImageHeight"},
 870   TAG_TABLE_END
 871 };
 872 
 873 static tag_info_array tag_table_VND_CANON = {
 874   { 0x0001, "ModeArray"}, /* guess */
 875   { 0x0004, "ImageInfo"}, /* guess */
 876   { 0x0006, "ImageType"},
 877   { 0x0007, "FirmwareVersion"},
 878   { 0x0008, "ImageNumber"},
 879   { 0x0009, "OwnerName"},
 880   { 0x000C, "Camera"},
 881   { 0x000F, "CustomFunctions"},
 882   TAG_TABLE_END
 883 };
 884 
 885 static tag_info_array tag_table_VND_CASIO = {
 886   { 0x0001, "RecordingMode"},
 887   { 0x0002, "Quality"},
 888   { 0x0003, "FocusingMode"},
 889   { 0x0004, "FlashMode"},
 890   { 0x0005, "FlashIntensity"},
 891   { 0x0006, "ObjectDistance"},
 892   { 0x0007, "WhiteBalance"},
 893   { 0x000A, "DigitalZoom"},
 894   { 0x000B, "Sharpness"},
 895   { 0x000C, "Contrast"},
 896   { 0x000D, "Saturation"},
 897   { 0x0014, "CCDSensitivity"},
 898   TAG_TABLE_END
 899 };
 900 
 901 static tag_info_array tag_table_VND_FUJI = {
 902   { 0x0000, "Version"},
 903   { 0x1000, "Quality"},
 904   { 0x1001, "Sharpness"},
 905   { 0x1002, "WhiteBalance"},
 906   { 0x1003, "Color"},
 907   { 0x1004, "Tone"},
 908   { 0x1010, "FlashMode"},
 909   { 0x1011, "FlashStrength"},
 910   { 0x1020, "Macro"},
 911   { 0x1021, "FocusMode"},
 912   { 0x1030, "SlowSync"},
 913   { 0x1031, "PictureMode"},
 914   { 0x1100, "ContTake"},
 915   { 0x1300, "BlurWarning"},
 916   { 0x1301, "FocusWarning"},
 917   { 0x1302, "AEWarning "},
 918   TAG_TABLE_END
 919 };
 920 
 921 static tag_info_array tag_table_VND_NIKON = {
 922   { 0x0003, "Quality"},
 923   { 0x0004, "ColorMode"},
 924   { 0x0005, "ImageAdjustment"},
 925   { 0x0006, "CCDSensitivity"},
 926   { 0x0007, "WhiteBalance"},
 927   { 0x0008, "Focus"},
 928   { 0x000a, "DigitalZoom"},
 929   { 0x000b, "Converter"},
 930   TAG_TABLE_END
 931 };
 932 
 933 static tag_info_array tag_table_VND_NIKON_990 = {
 934   { 0x0001, "Version"},
 935   { 0x0002, "ISOSetting"},
 936   { 0x0003, "ColorMode"},
 937   { 0x0004, "Quality"},
 938   { 0x0005, "WhiteBalance"},
 939   { 0x0006, "ImageSharpening"},
 940   { 0x0007, "FocusMode"},
 941   { 0x0008, "FlashSetting"},
 942   { 0x000F, "ISOSelection"},
 943   { 0x0080, "ImageAdjustment"},
 944   { 0x0082, "AuxiliaryLens"},
 945   { 0x0085, "ManualFocusDistance"},
 946   { 0x0086, "DigitalZoom"},
 947   { 0x0088, "AFFocusPosition"},
 948   { 0x0010, "DataDump"},
 949   TAG_TABLE_END
 950 };
 951 
 952 static tag_info_array tag_table_VND_OLYMPUS = {
 953   { 0x0200, "SpecialMode"},
 954   { 0x0201, "JPEGQuality"},
 955   { 0x0202, "Macro"},
 956   { 0x0204, "DigitalZoom"},
 957   { 0x0207, "SoftwareRelease"},
 958   { 0x0208, "PictureInfo"},
 959   { 0x0209, "CameraId"},
 960   { 0x0F00, "DataDump"},
 961   TAG_TABLE_END
 962 };
 963 
 964 typedef enum mn_byte_order_t {
 965         MN_ORDER_INTEL    = 0,
 966         MN_ORDER_MOTOROLA = 1,
 967         MN_ORDER_NORMAL
 968 } mn_byte_order_t;
 969 
 970 typedef enum mn_offset_mode_t {
 971         MN_OFFSET_NORMAL,
 972         MN_OFFSET_MAKER,
 973         MN_OFFSET_GUESS
 974 } mn_offset_mode_t;
 975 
 976 typedef struct {
 977         tag_table_type   tag_table;
 978         char *           make;
 979         char *           model;
 980         char *           id_string;
 981         int              id_string_len;
 982         int              offset;
 983         mn_byte_order_t  byte_order;
 984         mn_offset_mode_t offset_mode;
 985 } maker_note_type;
 986 
 987 static const maker_note_type maker_note_array[] = {
 988   { tag_table_VND_CANON,     "Canon",                   NULL,  NULL,                       0,  0,  MN_ORDER_INTEL,    MN_OFFSET_GUESS},
 989 /*  { tag_table_VND_CANON,     "Canon",                   NULL,  NULL,                       0,  0,  MN_ORDER_NORMAL,   MN_OFFSET_NORMAL},*/
 990   { tag_table_VND_CASIO,     "CASIO",                   NULL,  NULL,                       0,  0,  MN_ORDER_MOTOROLA, MN_OFFSET_NORMAL},
 991   { tag_table_VND_FUJI,      "FUJIFILM",                NULL,  "FUJIFILM\x0C\x00\x00\x00", 12, 12, MN_ORDER_INTEL,    MN_OFFSET_MAKER},
 992   { tag_table_VND_NIKON,     "NIKON",                   NULL,  "Nikon\x00\x01\x00",        8,  8,  MN_ORDER_NORMAL,   MN_OFFSET_NORMAL},
 993   { tag_table_VND_NIKON_990, "NIKON",                   NULL,  NULL,                       0,  0,  MN_ORDER_NORMAL,   MN_OFFSET_NORMAL},
 994   { tag_table_VND_OLYMPUS,   "OLYMPUS OPTICAL CO.,LTD", NULL,  "OLYMP\x00\x01\x00",        8,  8,  MN_ORDER_NORMAL,   MN_OFFSET_NORMAL},
 995 };
 996 /* }}} */
 997 
 998 /* {{{ exif_get_tagname
 999         Get headername for tag_num or NULL if not defined */
1000 static char * exif_get_tagname(int tag_num, char *ret, int len, tag_table_type tag_table TSRMLS_DC)
1001 {
1002         int i, t;
1003         char tmp[32];
1004 
1005         for (i = 0; (t = tag_table[i].Tag) != TAG_END_OF_LIST; i++) {
1006                 if (t == tag_num) {
1007                         if (ret && len)  {
1008                                 strlcpy(ret, tag_table[i].Desc, abs(len));
1009                                 if (len < 0) {
1010                                         memset(ret + strlen(ret), ' ', -len - strlen(ret) - 1);
1011                                         ret[-len - 1] = '\0';
1012                                 }
1013                                 return ret;
1014                         }
1015                         return tag_table[i].Desc;
1016                 }
1017         }
1018 
1019         if (ret && len) {
1020                 snprintf(tmp, sizeof(tmp), "UndefinedTag:0x%04X", tag_num);
1021                 strlcpy(ret, tmp, abs(len));
1022                 if (len < 0) {
1023                         memset(ret + strlen(ret), ' ', -len - strlen(ret) - 1);
1024                         ret[-len - 1] = '\0';
1025                 }
1026                 return ret;
1027         }
1028         return "";
1029 }
1030 /* }}} */
1031 
1032 /* {{{ exif_char_dump
1033  * Do not use! This is a debug function... */
1034 #ifdef EXIF_DEBUG
1035 static unsigned char* exif_char_dump(unsigned char * addr, int len, int offset)
1036 {
1037         static unsigned char buf[4096+1];
1038         static unsigned char tmp[20];
1039         int c, i, p=0, n = 5+31;
1040 
1041         p += slprintf(buf+p, sizeof(buf)-p, "\nDump Len: %08X (%d)", len, len);
1042         if (len) {
1043                 for(i=0; i<len+15 && p+n<=sizeof(buf); i++) {
1044                         if (i%16==0) {
1045                                 p += slprintf(buf+p, sizeof(buf)-p, "\n%08X: ", i+offset);
1046                         }
1047                         if (i<len) {
1048                                 c = *addr++;
1049                                 p += slprintf(buf+p, sizeof(buf)-p, "%02X ", c);
1050                                 tmp[i%16] = c>=32 ? c : '.';
1051                                 tmp[(i%16)+1] = '\0';
1052                         } else {
1053                                 p += slprintf(buf+p, sizeof(buf)-p, "   ");
1054                         }
1055                         if (i%16==15) {
1056                                 p += slprintf(buf+p, sizeof(buf)-p, "    %s", tmp);
1057                                 if (i>=len) {
1058                                         break;
1059                                 }
1060                         }
1061                 }
1062         }
1063         buf[sizeof(buf)-1] = '\0';
1064         return buf;
1065 }
1066 #endif
1067 /* }}} */
1068 
1069 /* {{{ php_jpg_get16
1070    Get 16 bits motorola order (always) for jpeg header stuff.
1071 */
1072 static int php_jpg_get16(void *value)
1073 {
1074         return (((uchar *)value)[0] << 8) | ((uchar *)value)[1];
1075 }
1076 /* }}} */
1077 
1078 /* {{{ php_ifd_get16u
1079  * Convert a 16 bit unsigned value from file's native byte order */
1080 static int php_ifd_get16u(void *value, int motorola_intel)
1081 {
1082         if (motorola_intel) {
1083                 return (((uchar *)value)[0] << 8) | ((uchar *)value)[1];
1084         } else {
1085                 return (((uchar *)value)[1] << 8) | ((uchar *)value)[0];
1086         }
1087 }
1088 /* }}} */
1089 
1090 /* {{{ php_ifd_get16s
1091  * Convert a 16 bit signed value from file's native byte order */
1092 static signed short php_ifd_get16s(void *value, int motorola_intel)
1093 {
1094         return (signed short)php_ifd_get16u(value, motorola_intel);
1095 }
1096 /* }}} */
1097 
1098 /* {{{ php_ifd_get32s
1099  * Convert a 32 bit signed value from file's native byte order */
1100 static int php_ifd_get32s(void *value, int motorola_intel)
1101 {
1102         if (motorola_intel) {
1103                 return  (((char  *)value)[0] << 24)
1104                           | (((uchar *)value)[1] << 16)
1105                           | (((uchar *)value)[2] << 8 )
1106                           | (((uchar *)value)[3]      );
1107         } else {
1108                 return  (((char  *)value)[3] << 24)
1109                           | (((uchar *)value)[2] << 16)
1110                           | (((uchar *)value)[1] << 8 )
1111                           | (((uchar *)value)[0]      );
1112         }
1113 }
1114 /* }}} */
1115 
1116 /* {{{ php_ifd_get32u
1117  * Write 32 bit unsigned value to data */
1118 static unsigned php_ifd_get32u(void *value, int motorola_intel)
1119 {
1120         return (unsigned)php_ifd_get32s(value, motorola_intel) & 0xffffffff;
1121 }
1122 /* }}} */
1123 
1124 /* {{{ php_ifd_set16u
1125  * Write 16 bit unsigned value to data */
1126 static void php_ifd_set16u(char *data, unsigned int value, int motorola_intel)
1127 {
1128         if (motorola_intel) {
1129                 data[0] = (value & 0xFF00) >> 8;
1130                 data[1] = (value & 0x00FF);
1131         } else {
1132                 data[1] = (value & 0xFF00) >> 8;
1133                 data[0] = (value & 0x00FF);
1134         }
1135 }
1136 /* }}} */
1137 
1138 /* {{{ php_ifd_set32u
1139  * Convert a 32 bit unsigned value from file's native byte order */
1140 static void php_ifd_set32u(char *data, size_t value, int motorola_intel)
1141 {
1142         if (motorola_intel) {
1143                 data[0] = (value & 0xFF000000) >> 24;
1144                 data[1] = (value & 0x00FF0000) >> 16;
1145                 data[2] = (value & 0x0000FF00) >>  8;
1146                 data[3] = (value & 0x000000FF);
1147         } else {
1148                 data[3] = (value & 0xFF000000) >> 24;
1149                 data[2] = (value & 0x00FF0000) >> 16;
1150                 data[1] = (value & 0x0000FF00) >>  8;
1151                 data[0] = (value & 0x000000FF);
1152         }
1153 }
1154 /* }}} */
1155 
1156 #ifdef EXIF_DEBUG
1157 char * exif_dump_data(int *dump_free, int format, int components, int length, int motorola_intel, char *value_ptr TSRMLS_DC) /* {{{ */
1158 {
1159         char *dump;
1160         int len;
1161 
1162         *dump_free = 0;
1163         if (format == TAG_FMT_STRING) {
1164                 return value_ptr ? value_ptr : "<no data>";
1165         }
1166         if (format == TAG_FMT_UNDEFINED) {
1167                 return "<undefined>\n";
1168         }
1169         if (format == TAG_FMT_IFD) {
1170                 return "";
1171         }
1172         if (format == TAG_FMT_SINGLE || format == TAG_FMT_DOUBLE) {
1173                 return "<not implemented>";
1174         }
1175         *dump_free = 1;
1176         if (components > 1) {
1177                 len = spprintf(&dump, 0, "(%d,%d) {", components, length);
1178         } else {
1179                 len = spprintf(&dump, 0, "{");
1180         }
1181         while(components > 0) {
1182                 switch(format) {
1183                         case TAG_FMT_BYTE:
1184                         case TAG_FMT_UNDEFINED:
1185                         case TAG_FMT_STRING:
1186                         case TAG_FMT_SBYTE:
1187                                 dump = erealloc(dump, len + 4 + 1);
1188                                 snprintf(dump + len, 4 + 1, "0x%02X", *value_ptr);
1189                                 len += 4;
1190                                 value_ptr++;
1191                                 break;
1192                         case TAG_FMT_USHORT:
1193                         case TAG_FMT_SSHORT:
1194                                 dump = erealloc(dump, len + 6 + 1);
1195                                 snprintf(dump + len, 6 + 1, "0x%04X", php_ifd_get16s(value_ptr, motorola_intel));
1196                                 len += 6;
1197                                 value_ptr += 2;
1198                                 break;
1199                         case TAG_FMT_ULONG:
1200                         case TAG_FMT_SLONG:
1201                                 dump = erealloc(dump, len + 6 + 1);
1202                                 snprintf(dump + len, 6 + 1, "0x%04X", php_ifd_get32s(value_ptr, motorola_intel));
1203                                 len += 6;
1204                                 value_ptr += 4;
1205                                 break;
1206                         case TAG_FMT_URATIONAL:
1207                         case TAG_FMT_SRATIONAL:
1208                                 dump = erealloc(dump, len + 13 + 1);
1209                                 snprintf(dump + len, 13 + 1, "0x%04X/0x%04X", php_ifd_get32s(value_ptr, motorola_intel), php_ifd_get32s(value_ptr+4, motorola_intel));
1210                                 len += 13;
1211                                 value_ptr += 8;
1212                                 break;
1213                 }
1214                 if (components > 0) {
1215                         dump = erealloc(dump, len + 2 + 1);
1216                         snprintf(dump + len, 2 + 1, ", ");
1217                         len += 2;
1218                         components--;
1219                 } else{
1220                         break;
1221                 }
1222         }
1223         dump = erealloc(dump, len + 1 + 1);
1224         snprintf(dump + len, 1 + 1, "}");
1225         return dump;
1226 }
1227 /* }}} */
1228 #endif
1229 
1230 /* {{{ exif_convert_any_format
1231  * Evaluate number, be it int, rational, or float from directory. */
1232 static double exif_convert_any_format(void *value, int format, int motorola_intel TSRMLS_DC)
1233 {
1234         int             s_den;
1235         unsigned        u_den;
1236 
1237         switch(format) {
1238                 case TAG_FMT_SBYTE:     return *(signed char *)value;
1239                 case TAG_FMT_BYTE:      return *(uchar *)value;
1240 
1241                 case TAG_FMT_USHORT:    return php_ifd_get16u(value, motorola_intel);
1242                 case TAG_FMT_ULONG:     return php_ifd_get32u(value, motorola_intel);
1243 
1244                 case TAG_FMT_URATIONAL:
1245                         u_den = php_ifd_get32u(4+(char *)value, motorola_intel);
1246                         if (u_den == 0) {
1247                                 return 0;
1248                         } else {
1249                                 return (double)php_ifd_get32u(value, motorola_intel) / u_den;
1250                         }
1251 
1252                 case TAG_FMT_SRATIONAL:
1253                         s_den = php_ifd_get32s(4+(char *)value, motorola_intel);
1254                         if (s_den == 0) {
1255                                 return 0;
1256                         } else {
1257                                 return (double)php_ifd_get32s(value, motorola_intel) / s_den;
1258                         }
1259 
1260                 case TAG_FMT_SSHORT:    return (signed short)php_ifd_get16u(value, motorola_intel);
1261                 case TAG_FMT_SLONG:     return php_ifd_get32s(value, motorola_intel);
1262 
1263                 /* Not sure if this is correct (never seen float used in Exif format) */
1264                 case TAG_FMT_SINGLE:
1265 #ifdef EXIF_DEBUG
1266                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found value of type single");
1267 #endif
1268                         return (double)*(float *)value;
1269                 case TAG_FMT_DOUBLE:
1270 #ifdef EXIF_DEBUG
1271                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found value of type double");
1272 #endif
1273                         return *(double *)value;
1274         }
1275         return 0;
1276 }
1277 /* }}} */
1278 
1279 /* {{{ exif_convert_any_to_int
1280  * Evaluate number, be it int, rational, or float from directory. */
1281 static size_t exif_convert_any_to_int(void *value, int format, int motorola_intel TSRMLS_DC)
1282 {
1283         int             s_den;
1284         unsigned        u_den;
1285 
1286         switch(format) {
1287                 case TAG_FMT_SBYTE:     return *(signed char *)value;
1288                 case TAG_FMT_BYTE:      return *(uchar *)value;
1289 
1290                 case TAG_FMT_USHORT:    return php_ifd_get16u(value, motorola_intel);
1291                 case TAG_FMT_ULONG:     return php_ifd_get32u(value, motorola_intel);
1292 
1293                 case TAG_FMT_URATIONAL:
1294                         u_den = php_ifd_get32u(4+(char *)value, motorola_intel);
1295                         if (u_den == 0) {
1296                                 return 0;
1297                         } else {
1298                                 return php_ifd_get32u(value, motorola_intel) / u_den;
1299                         }
1300 
1301                 case TAG_FMT_SRATIONAL:
1302                         s_den = php_ifd_get32s(4+(char *)value, motorola_intel);
1303                         if (s_den == 0) {
1304                                 return 0;
1305                         } else {
1306                                 return php_ifd_get32s(value, motorola_intel) / s_den;
1307                         }
1308 
1309                 case TAG_FMT_SSHORT:    return php_ifd_get16u(value, motorola_intel);
1310                 case TAG_FMT_SLONG:     return php_ifd_get32s(value, motorola_intel);
1311 
1312                 /* Not sure if this is correct (never seen float used in Exif format) */
1313                 case TAG_FMT_SINGLE:
1314 #ifdef EXIF_DEBUG
1315                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found value of type single");
1316 #endif
1317                         return (size_t)*(float *)value;
1318                 case TAG_FMT_DOUBLE:
1319 #ifdef EXIF_DEBUG
1320                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found value of type double");
1321 #endif
1322                         return (size_t)*(double *)value;
1323         }
1324         return 0;
1325 }
1326 /* }}} */
1327 
1328 /* {{{ struct image_info_value, image_info_list
1329 */
1330 #ifndef WORD
1331 #define WORD unsigned short
1332 #endif
1333 #ifndef DWORD
1334 #define DWORD unsigned int
1335 #endif
1336 
1337 typedef struct {
1338         int             num;
1339         int             den;
1340 } signed_rational;
1341 
1342 typedef struct {
1343         unsigned int    num;
1344         unsigned int    den;
1345 } unsigned_rational;
1346 
1347 typedef union _image_info_value {
1348         char                            *s;
1349         unsigned            u;
1350         int                             i;
1351         float               f;
1352         double              d;
1353         signed_rational         sr;
1354         unsigned_rational       ur;
1355         union _image_info_value   *list;
1356 } image_info_value;
1357 
1358 typedef struct {
1359         WORD                tag;
1360         WORD                format;
1361         DWORD               length;
1362         DWORD               dummy;  /* value ptr of tiff directory entry */
1363         char                            *name;
1364         image_info_value    value;
1365 } image_info_data;
1366 
1367 typedef struct {
1368         int                 count;
1369         image_info_data         *list;
1370 } image_info_list;
1371 /* }}} */
1372 
1373 /* {{{ exif_get_sectionname
1374  Returns the name of a section
1375 */
1376 #define SECTION_FILE        0
1377 #define SECTION_COMPUTED    1
1378 #define SECTION_ANY_TAG     2
1379 #define SECTION_IFD0        3
1380 #define SECTION_THUMBNAIL   4
1381 #define SECTION_COMMENT     5
1382 #define SECTION_APP0        6
1383 #define SECTION_EXIF        7
1384 #define SECTION_FPIX        8
1385 #define SECTION_GPS         9
1386 #define SECTION_INTEROP     10
1387 #define SECTION_APP12       11
1388 #define SECTION_WINXP       12
1389 #define SECTION_MAKERNOTE   13
1390 #define SECTION_COUNT       14
1391 
1392 #define FOUND_FILE          (1<<SECTION_FILE)
1393 #define FOUND_COMPUTED      (1<<SECTION_COMPUTED)
1394 #define FOUND_ANY_TAG       (1<<SECTION_ANY_TAG)
1395 #define FOUND_IFD0          (1<<SECTION_IFD0)
1396 #define FOUND_THUMBNAIL     (1<<SECTION_THUMBNAIL)
1397 #define FOUND_COMMENT       (1<<SECTION_COMMENT)
1398 #define FOUND_APP0          (1<<SECTION_APP0)
1399 #define FOUND_EXIF          (1<<SECTION_EXIF)
1400 #define FOUND_FPIX          (1<<SECTION_FPIX)
1401 #define FOUND_GPS           (1<<SECTION_GPS)
1402 #define FOUND_INTEROP       (1<<SECTION_INTEROP)
1403 #define FOUND_APP12         (1<<SECTION_APP12)
1404 #define FOUND_WINXP         (1<<SECTION_WINXP)
1405 #define FOUND_MAKERNOTE     (1<<SECTION_MAKERNOTE)
1406 
1407 static char *exif_get_sectionname(int section)
1408 {
1409         switch(section) {
1410                 case SECTION_FILE:      return "FILE";
1411                 case SECTION_COMPUTED:  return "COMPUTED";
1412                 case SECTION_ANY_TAG:   return "ANY_TAG";
1413                 case SECTION_IFD0:      return "IFD0";
1414                 case SECTION_THUMBNAIL: return "THUMBNAIL";
1415                 case SECTION_COMMENT:   return "COMMENT";
1416                 case SECTION_APP0:      return "APP0";
1417                 case SECTION_EXIF:      return "EXIF";
1418                 case SECTION_FPIX:      return "FPIX";
1419                 case SECTION_GPS:       return "GPS";
1420                 case SECTION_INTEROP:   return "INTEROP";
1421                 case SECTION_APP12:     return "APP12";
1422                 case SECTION_WINXP:     return "WINXP";
1423                 case SECTION_MAKERNOTE: return "MAKERNOTE";
1424         }
1425         return "";
1426 }
1427 
1428 static tag_table_type exif_get_tag_table(int section)
1429 {
1430         switch(section) {
1431                 case SECTION_FILE:      return &tag_table_IFD[0];
1432                 case SECTION_COMPUTED:  return &tag_table_IFD[0];
1433                 case SECTION_ANY_TAG:   return &tag_table_IFD[0];
1434                 case SECTION_IFD0:      return &tag_table_IFD[0];
1435                 case SECTION_THUMBNAIL: return &tag_table_IFD[0];
1436                 case SECTION_COMMENT:   return &tag_table_IFD[0];
1437                 case SECTION_APP0:      return &tag_table_IFD[0];
1438                 case SECTION_EXIF:      return &tag_table_IFD[0];
1439                 case SECTION_FPIX:      return &tag_table_IFD[0];
1440                 case SECTION_GPS:       return &tag_table_GPS[0];
1441                 case SECTION_INTEROP:   return &tag_table_IOP[0];
1442                 case SECTION_APP12:     return &tag_table_IFD[0];
1443                 case SECTION_WINXP:     return &tag_table_IFD[0];
1444         }
1445         return &tag_table_IFD[0];
1446 }
1447 /* }}} */
1448 
1449 /* {{{ exif_get_sectionlist
1450    Return list of sectionnames specified by sectionlist. Return value must be freed
1451 */
1452 static char *exif_get_sectionlist(int sectionlist TSRMLS_DC)
1453 {
1454         int i, len, ml = 0;
1455         char *sections;
1456 
1457         for(i=0; i<SECTION_COUNT; i++) {
1458                 ml += strlen(exif_get_sectionname(i))+2;
1459         }
1460         sections = safe_emalloc(ml, 1, 1);
1461         sections[0] = '\0';
1462         len = 0;
1463         for(i=0; i<SECTION_COUNT; i++) {
1464                 if (sectionlist&(1<<i)) {
1465                         snprintf(sections+len, ml-len, "%s, ", exif_get_sectionname(i));
1466                         len = strlen(sections);
1467                 }
1468         }
1469         if (len>2)
1470                 sections[len-2] = '\0';
1471         return sections;
1472 }
1473 /* }}} */
1474 
1475 /* {{{ struct image_info_type
1476    This structure stores Exif header image elements in a simple manner
1477    Used to store camera data as extracted from the various ways that it can be
1478    stored in a nexif header
1479 */
1480 
1481 typedef struct {
1482         int     type;
1483         size_t  size;
1484         uchar   *data;
1485 } file_section;
1486 
1487 typedef struct {
1488         int             count;
1489         file_section    *list;
1490 } file_section_list;
1491 
1492 typedef struct {
1493         image_filetype  filetype;
1494         size_t          width, height;
1495         size_t          size;
1496         size_t          offset;
1497         char            *data;
1498 } thumbnail_data;
1499 
1500 typedef struct {
1501         char                    *value;
1502         size_t                  size;
1503         int                             tag;
1504 } xp_field_type;
1505 
1506 typedef struct {
1507         int             count;
1508         xp_field_type   *list;
1509 } xp_field_list;
1510 
1511 /* This structure is used to store a section of a Jpeg file. */
1512 typedef struct {
1513         php_stream      *infile;
1514         char            *FileName;
1515         time_t          FileDateTime;
1516         size_t          FileSize;
1517         image_filetype  FileType;
1518         int             Height, Width;
1519         int             IsColor;
1520 
1521         char            *make;
1522         char            *model;
1523 
1524         float           ApertureFNumber;
1525         float           ExposureTime;
1526         double          FocalplaneUnits;
1527         float           CCDWidth;
1528         double          FocalplaneXRes;
1529         size_t          ExifImageWidth;
1530         float           FocalLength;
1531         float           Distance;
1532 
1533         int             motorola_intel; /* 1 Motorola; 0 Intel */
1534 
1535         char            *UserComment;
1536         int             UserCommentLength;
1537         char            *UserCommentEncoding;
1538         char            *encode_unicode;
1539         char            *decode_unicode_be;
1540         char            *decode_unicode_le;
1541         char            *encode_jis;
1542         char            *decode_jis_be;
1543         char            *decode_jis_le;
1544         char            *Copyright;/* EXIF standard defines Copyright as "<Photographer> [ '\0' <Editor> ] ['\0']" */
1545         char            *CopyrightPhotographer;
1546         char            *CopyrightEditor;
1547 
1548         xp_field_list   xp_fields;
1549 
1550         thumbnail_data  Thumbnail;
1551         /* other */
1552         int             sections_found; /* FOUND_<marker> */
1553         image_info_list info_list[SECTION_COUNT];
1554         /* for parsing */
1555         int             read_thumbnail;
1556         int             read_all;
1557         int             ifd_nesting_level;
1558         /* internal */
1559         file_section_list       file;
1560 } image_info_type;
1561 /* }}} */
1562 
1563 /* {{{ exif_error_docref */
1564 static void exif_error_docref(const char *docref EXIFERR_DC, const image_info_type *ImageInfo, int type, const char *format, ...)
1565 {
1566         va_list args;
1567 
1568         va_start(args, format);
1569 #ifdef EXIF_DEBUG
1570         {
1571                 char *buf;
1572 
1573                 spprintf(&buf, 0, "%s(%d): %s", _file, _line, format);
1574                 php_verror(docref, ImageInfo->FileName?ImageInfo->FileName:"", type, buf, args TSRMLS_CC);
1575                 efree(buf);
1576         }
1577 #else
1578         php_verror(docref, ImageInfo->FileName?ImageInfo->FileName:"", type, format, args TSRMLS_CC);
1579 #endif
1580         va_end(args);
1581 }
1582 /* }}} */
1583 
1584 /* {{{ jpeg_sof_info
1585  */
1586 typedef struct {
1587         int     bits_per_sample;
1588         size_t  width;
1589         size_t  height;
1590         int     num_components;
1591 } jpeg_sof_info;
1592 /* }}} */
1593 
1594 /* {{{ exif_file_sections_add
1595  Add a file_section to image_info
1596  returns the used block or -1. if size>0 and data == NULL buffer of size is allocated
1597 */
1598 static int exif_file_sections_add(image_info_type *ImageInfo, int type, size_t size, uchar *data)
1599 {
1600         file_section    *tmp;
1601         int             count = ImageInfo->file.count;
1602 
1603         tmp = safe_erealloc(ImageInfo->file.list, (count+1), sizeof(file_section), 0);
1604         ImageInfo->file.list = tmp;
1605         ImageInfo->file.list[count].type = 0xFFFF;
1606         ImageInfo->file.list[count].data = NULL;
1607         ImageInfo->file.list[count].size = 0;
1608         ImageInfo->file.count = count+1;
1609         if (!size) {
1610                 data = NULL;
1611         } else if (data == NULL) {
1612                 data = safe_emalloc(size, 1, 0);
1613         }
1614         ImageInfo->file.list[count].type = type;
1615         ImageInfo->file.list[count].data = data;
1616         ImageInfo->file.list[count].size = size;
1617         return count;
1618 }
1619 /* }}} */
1620 
1621 /* {{{ exif_file_sections_realloc
1622  Reallocate a file section returns 0 on success and -1 on failure
1623 */
1624 static int exif_file_sections_realloc(image_info_type *ImageInfo, int section_index, size_t size TSRMLS_DC)
1625 {
1626         void *tmp;
1627 
1628         /* This is not a malloc/realloc check. It is a plausibility check for the
1629          * function parameters (requirements engineering).
1630          */
1631         if (section_index >= ImageInfo->file.count) {
1632                 EXIF_ERRLOG_FSREALLOC(ImageInfo)
1633                 return -1;
1634         }
1635         tmp = safe_erealloc(ImageInfo->file.list[section_index].data, 1, size, 0);
1636         ImageInfo->file.list[section_index].data = tmp;
1637         ImageInfo->file.list[section_index].size = size;
1638         return 0;
1639 }
1640 /* }}} */
1641 
1642 /* {{{ exif_file_section_free
1643    Discard all file_sections in ImageInfo
1644 */
1645 static int exif_file_sections_free(image_info_type *ImageInfo)
1646 {
1647         int i;
1648 
1649         if (ImageInfo->file.count) {
1650                 for (i=0; i<ImageInfo->file.count; i++) {
1651                         EFREE_IF(ImageInfo->file.list[i].data);
1652                 }
1653         }
1654         EFREE_IF(ImageInfo->file.list);
1655         ImageInfo->file.count = 0;
1656         return TRUE;
1657 }
1658 /* }}} */
1659 
1660 /* {{{ exif_iif_add_value
1661  Add a value to image_info
1662 */
1663 static void exif_iif_add_value(image_info_type *image_info, int section_index, char *name, int tag, int format, int length, void* value, int motorola_intel TSRMLS_DC)
1664 {
1665         size_t idex;
1666         void *vptr;
1667         image_info_value *info_value;
1668         image_info_data  *info_data;
1669         image_info_data  *list;
1670 
1671         if (length < 0) {
1672                 return;
1673         }
1674 
1675         list = safe_erealloc(image_info->info_list[section_index].list, (image_info->info_list[section_index].count+1), sizeof(image_info_data), 0);
1676         image_info->info_list[section_index].list = list;
1677 
1678         info_data  = &image_info->info_list[section_index].list[image_info->info_list[section_index].count];
1679         memset(info_data, 0, sizeof(image_info_data));
1680         info_data->tag    = tag;
1681         info_data->format = format;
1682         info_data->length = length;
1683         info_data->name   = estrdup(name);
1684         info_value        = &info_data->value;
1685 
1686         switch (format) {
1687                 case TAG_FMT_STRING:
1688                         if (value) {
1689                                 length = php_strnlen(value, length);
1690                                 info_value->s = estrndup(value, length);
1691                                 info_data->length = length;
1692                         } else {
1693                                 info_data->length = 0;
1694                                 info_value->s = estrdup("");
1695                         }
1696                         break;
1697 
1698                 default:
1699                         /* Standard says more types possible but skip them...
1700                          * but allow users to handle data if they know how to
1701                          * So not return but use type UNDEFINED
1702                          * return;
1703                          */
1704                         info_data->tag = TAG_FMT_UNDEFINED;/* otherwise not freed from memory */
1705                 case TAG_FMT_SBYTE:
1706                 case TAG_FMT_BYTE:
1707                 /* in contrast to strings bytes do not need to allocate buffer for NULL if length==0 */
1708                         if (!length)
1709                                 break;
1710                 case TAG_FMT_UNDEFINED:
1711                         if (value) {
1712                                 /* do not recompute length here */
1713                                 info_value->s = estrndup(value, length);
1714                                 info_data->length = length;
1715                         } else {
1716                                 info_data->length = 0;
1717                                 info_value->s = estrdup("");
1718                         }
1719                         break;
1720 
1721                 case TAG_FMT_USHORT:
1722                 case TAG_FMT_ULONG:
1723                 case TAG_FMT_URATIONAL:
1724                 case TAG_FMT_SSHORT:
1725                 case TAG_FMT_SLONG:
1726                 case TAG_FMT_SRATIONAL:
1727                 case TAG_FMT_SINGLE:
1728                 case TAG_FMT_DOUBLE:
1729                         if (length==0) {
1730                                 break;
1731                         } else
1732                         if (length>1) {
1733                                 info_value->list = safe_emalloc(length, sizeof(image_info_value), 0);
1734                         } else {
1735                                 info_value = &info_data->value;
1736                         }
1737                         for (idex=0,vptr=value; idex<(size_t)length; idex++,vptr=(char *) vptr + php_tiff_bytes_per_format[format]) {
1738                                 if (length>1) {
1739                                         info_value = &info_data->value.list[idex];
1740                                 }
1741                                 switch (format) {
1742                                         case TAG_FMT_USHORT:
1743                                                 info_value->u = php_ifd_get16u(vptr, motorola_intel);
1744                                                 break;
1745 
1746                                         case TAG_FMT_ULONG:
1747                                                 info_value->u = php_ifd_get32u(vptr, motorola_intel);
1748                                                 break;
1749 
1750                                         case TAG_FMT_URATIONAL:
1751                                                 info_value->ur.num = php_ifd_get32u(vptr, motorola_intel);
1752                                                 info_value->ur.den = php_ifd_get32u(4+(char *)vptr, motorola_intel);
1753                                                 break;
1754 
1755                                         case TAG_FMT_SSHORT:
1756                                                 info_value->i = php_ifd_get16s(vptr, motorola_intel);
1757                                                 break;
1758 
1759                                         case TAG_FMT_SLONG:
1760                                                 info_value->i = php_ifd_get32s(vptr, motorola_intel);
1761                                                 break;
1762 
1763                                         case TAG_FMT_SRATIONAL:
1764                                                 info_value->sr.num = php_ifd_get32u(vptr, motorola_intel);
1765                                                 info_value->sr.den = php_ifd_get32u(4+(char *)vptr, motorola_intel);
1766                                                 break;
1767 
1768                                         case TAG_FMT_SINGLE:
1769 #ifdef EXIF_DEBUG
1770                                                 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Found value of type single");
1771 #endif
1772                                                 info_value->f = *(float *)value;
1773 
1774                                         case TAG_FMT_DOUBLE:
1775 #ifdef EXIF_DEBUG
1776                                                 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Found value of type double");
1777 #endif
1778                                                 info_value->d = *(double *)value;
1779                                                 break;
1780                                 }
1781                         }
1782         }
1783         image_info->sections_found |= 1<<section_index;
1784         image_info->info_list[section_index].count++;
1785 }
1786 /* }}} */
1787 
1788 /* {{{ exif_iif_add_tag
1789  Add a tag from IFD to image_info
1790 */
1791 static void exif_iif_add_tag(image_info_type *image_info, int section_index, char *name, int tag, int format, size_t length, void* value TSRMLS_DC)
1792 {
1793         exif_iif_add_value(image_info, section_index, name, tag, format, (int)length, value, image_info->motorola_intel TSRMLS_CC);
1794 }
1795 /* }}} */
1796 
1797 /* {{{ exif_iif_add_int
1798  Add an int value to image_info
1799 */
1800 static void exif_iif_add_int(image_info_type *image_info, int section_index, char *name, int value TSRMLS_DC)
1801 {
1802         image_info_data  *info_data;
1803         image_info_data  *list;
1804 
1805         list = safe_erealloc(image_info->info_list[section_index].list, (image_info->info_list[section_index].count+1), sizeof(image_info_data), 0);
1806         image_info->info_list[section_index].list = list;
1807 
1808         info_data  = &image_info->info_list[section_index].list[image_info->info_list[section_index].count];
1809         info_data->tag    = TAG_NONE;
1810         info_data->format = TAG_FMT_SLONG;
1811         info_data->length = 1;
1812         info_data->name   = estrdup(name);
1813         info_data->value.i = value;
1814         image_info->sections_found |= 1<<section_index;
1815         image_info->info_list[section_index].count++;
1816 }
1817 /* }}} */
1818 
1819 /* {{{ exif_iif_add_str
1820  Add a string value to image_info MUST BE NUL TERMINATED
1821 */
1822 static void exif_iif_add_str(image_info_type *image_info, int section_index, char *name, char *value TSRMLS_DC)
1823 {
1824         image_info_data  *info_data;
1825         image_info_data  *list;
1826 
1827         if (value) {
1828                 list = safe_erealloc(image_info->info_list[section_index].list, (image_info->info_list[section_index].count+1), sizeof(image_info_data), 0);
1829                 image_info->info_list[section_index].list = list;
1830                 info_data  = &image_info->info_list[section_index].list[image_info->info_list[section_index].count];
1831                 info_data->tag    = TAG_NONE;
1832                 info_data->format = TAG_FMT_STRING;
1833                 info_data->length = 1;
1834                 info_data->name   = estrdup(name);
1835                 info_data->value.s = estrdup(value);
1836                 image_info->sections_found |= 1<<section_index;
1837                 image_info->info_list[section_index].count++;
1838         }
1839 }
1840 /* }}} */
1841 
1842 /* {{{ exif_iif_add_fmt
1843  Add a format string value to image_info MUST BE NUL TERMINATED
1844 */
1845 static void exif_iif_add_fmt(image_info_type *image_info, int section_index, char *name TSRMLS_DC, char *value, ...)
1846 {
1847         char             *tmp;
1848         va_list                  arglist;
1849 
1850         va_start(arglist, value);
1851         if (value) {
1852                 vspprintf(&tmp, 0, value, arglist);
1853                 exif_iif_add_str(image_info, section_index, name, tmp TSRMLS_CC);
1854                 efree(tmp);
1855         }
1856         va_end(arglist);
1857 }
1858 /* }}} */
1859 
1860 /* {{{ exif_iif_add_str
1861  Add a string value to image_info MUST BE NUL TERMINATED
1862 */
1863 static void exif_iif_add_buffer(image_info_type *image_info, int section_index, char *name, int length, char *value TSRMLS_DC)
1864 {
1865         image_info_data  *info_data;
1866         image_info_data  *list;
1867 
1868         if (value) {
1869                 list = safe_erealloc(image_info->info_list[section_index].list, (image_info->info_list[section_index].count+1), sizeof(image_info_data), 0);
1870                 image_info->info_list[section_index].list = list;
1871                 info_data  = &image_info->info_list[section_index].list[image_info->info_list[section_index].count];
1872                 info_data->tag    = TAG_NONE;
1873                 info_data->format = TAG_FMT_UNDEFINED;
1874                 info_data->length = length;
1875                 info_data->name   = estrdup(name);
1876                 info_data->value.s = safe_emalloc(length, 1, 1);
1877                 memcpy(info_data->value.s, value, length);
1878                 info_data->value.s[length] = 0;
1879                 image_info->sections_found |= 1<<section_index;
1880                 image_info->info_list[section_index].count++;
1881         }
1882 }
1883 /* }}} */
1884 
1885 /* {{{ exif_iif_free
1886  Free memory allocated for image_info
1887 */
1888 static void exif_iif_free(image_info_type *image_info, int section_index) {
1889         int  i;
1890         void *f; /* faster */
1891 
1892         if (image_info->info_list[section_index].count) {
1893                 for (i=0; i < image_info->info_list[section_index].count; i++) {
1894                         if ((f=image_info->info_list[section_index].list[i].name) != NULL) {
1895                                 efree(f);
1896                         }
1897                         switch(image_info->info_list[section_index].list[i].format) {
1898                                 case TAG_FMT_SBYTE:
1899                                 case TAG_FMT_BYTE:
1900                                         /* in contrast to strings bytes do not need to allocate buffer for NULL if length==0 */
1901                                         if (image_info->info_list[section_index].list[i].length<1)
1902                                                 break;
1903                                 default:
1904                                 case TAG_FMT_UNDEFINED:
1905                                 case TAG_FMT_STRING:
1906                                         if ((f=image_info->info_list[section_index].list[i].value.s) != NULL) {
1907                                                 efree(f);
1908                                         }
1909                                         break;
1910 
1911                                 case TAG_FMT_USHORT:
1912                                 case TAG_FMT_ULONG:
1913                                 case TAG_FMT_URATIONAL:
1914                                 case TAG_FMT_SSHORT:
1915                                 case TAG_FMT_SLONG:
1916                                 case TAG_FMT_SRATIONAL:
1917                                 case TAG_FMT_SINGLE:
1918                                 case TAG_FMT_DOUBLE:
1919                                         /* nothing to do here */
1920                                         if (image_info->info_list[section_index].list[i].length > 1) {
1921                                                 if ((f=image_info->info_list[section_index].list[i].value.list) != NULL) {
1922                                                         efree(f);
1923                                                 }
1924                                         }
1925                                         break;
1926                         }
1927                 }
1928         }
1929         EFREE_IF(image_info->info_list[section_index].list);
1930 }
1931 /* }}} */
1932 
1933 /* {{{ add_assoc_image_info
1934  * Add image_info to associative array value. */
1935 static void add_assoc_image_info(zval *value, int sub_array, image_info_type *image_info, int section_index TSRMLS_DC)
1936 {
1937         char    buffer[64], *val, *name, uname[64];
1938         int     i, ap, l, b, idx=0, unknown=0;
1939 #ifdef EXIF_DEBUG
1940         int     info_tag;
1941 #endif
1942         image_info_value *info_value;
1943         image_info_data  *info_data;
1944         zval                     *tmpi, *array = NULL;
1945 
1946 #ifdef EXIF_DEBUG
1947 /*              php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Adding %d infos from section %s", image_info->info_list[section_index].count, exif_get_sectionname(section_index));*/
1948 #endif
1949         if (image_info->info_list[section_index].count) {
1950                 if (sub_array) {
1951                         MAKE_STD_ZVAL(tmpi);
1952                         array_init(tmpi);
1953                 } else {
1954                         tmpi = value;
1955                 }
1956 
1957                 for(i=0; i<image_info->info_list[section_index].count; i++) {
1958                         info_data  = &image_info->info_list[section_index].list[i];
1959 #ifdef EXIF_DEBUG
1960                         info_tag   = info_data->tag; /* conversion */
1961 #endif
1962                         info_value = &info_data->value;
1963                         if (!(name = info_data->name)) {
1964                                 snprintf(uname, sizeof(uname), "%d", unknown++);
1965                                 name = uname;
1966                         }
1967 #ifdef EXIF_DEBUG
1968 /*              php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Adding infos: tag(0x%04X,%12s,L=0x%04X): %s", info_tag, exif_get_tagname(info_tag, buffer, -12, exif_get_tag_table(section_index) TSRMLS_CC), info_data->length, info_data->format==TAG_FMT_STRING?(info_value&&info_value->s?info_value->s:"<no data>"):exif_get_tagformat(info_data->format));*/
1969 #endif
1970                         if (info_data->length==0) {
1971                                 add_assoc_null(tmpi, name);
1972                         } else {
1973                                 switch (info_data->format) {
1974                                         default:
1975                                                 /* Standard says more types possible but skip them...
1976                                                  * but allow users to handle data if they know how to
1977                                                  * So not return but use type UNDEFINED
1978                                                  * return;
1979                                                  */
1980                                         case TAG_FMT_BYTE:
1981                                         case TAG_FMT_SBYTE:
1982                                         case TAG_FMT_UNDEFINED:
1983                                                 if (!info_value->s) {
1984                                                         add_assoc_stringl(tmpi, name, "", 0, 1);
1985                                                 } else {
1986                                                         add_assoc_stringl(tmpi, name, info_value->s, info_data->length, 1);
1987                                                 }
1988                                                 break;
1989 
1990                                         case TAG_FMT_STRING:
1991                                                 if (!(val = info_value->s)) {
1992                                                         val = "";
1993                                                 }
1994                                                 if (section_index==SECTION_COMMENT) {
1995                                                         add_index_string(tmpi, idx++, val, 1);
1996                                                 } else {
1997                                                         add_assoc_string(tmpi, name, val, 1);
1998                                                 }
1999                                                 break;
2000 
2001                                         case TAG_FMT_URATIONAL:
2002                                         case TAG_FMT_SRATIONAL:
2003                                         /*case TAG_FMT_BYTE:
2004                                         case TAG_FMT_SBYTE:*/
2005                                         case TAG_FMT_USHORT:
2006                                         case TAG_FMT_SSHORT:
2007                                         case TAG_FMT_SINGLE:
2008                                         case TAG_FMT_DOUBLE:
2009                                         case TAG_FMT_ULONG:
2010                                         case TAG_FMT_SLONG:
2011                                                 /* now the rest, first see if it becomes an array */
2012                                                 if ((l = info_data->length) > 1) {
2013                                                         array = NULL;
2014                                                         MAKE_STD_ZVAL(array);
2015                                                         array_init(array);
2016                                                 }
2017                                                 for(ap=0; ap<l; ap++) {
2018                                                         if (l>1) {
2019                                                                 info_value = &info_data->value.list[ap];
2020                                                         }
2021                                                         switch (info_data->format) {
2022                                                                 case TAG_FMT_BYTE:
2023                                                                         if (l>1) {
2024                                                                                 info_value = &info_data->value;
2025                                                                                 for (b=0;b<l;b++) {
2026                                                                                         add_index_long(array, b, (int)(info_value->s[b]));
2027                                                                                 }
2028                                                                                 break;
2029                                                                         }
2030                                                                 case TAG_FMT_USHORT:
2031                                                                 case TAG_FMT_ULONG:
2032                                                                         if (l==1) {
2033                                                                                 add_assoc_long(tmpi, name, (int)info_value->u);
2034                                                                         } else {
2035                                                                                 add_index_long(array, ap, (int)info_value->u);
2036                                                                         }
2037                                                                         break;
2038 
2039                                                                 case TAG_FMT_URATIONAL:
2040                                                                         snprintf(buffer, sizeof(buffer), "%i/%i", info_value->ur.num, info_value->ur.den);
2041                                                                         if (l==1) {
2042                                                                                 add_assoc_string(tmpi, name, buffer, 1);
2043                                                                         } else {
2044                                                                                 add_index_string(array, ap, buffer, 1);
2045                                                                         }
2046                                                                         break;
2047 
2048                                                                 case TAG_FMT_SBYTE:
2049                                                                         if (l>1) {
2050                                                                                 info_value = &info_data->value;
2051                                                                                 for (b=0;b<l;b++) {
2052                                                                                         add_index_long(array, ap, (int)info_value->s[b]);
2053                                                                                 }
2054                                                                                 break;
2055                                                                         }
2056                                                                 case TAG_FMT_SSHORT:
2057                                                                 case TAG_FMT_SLONG:
2058                                                                         if (l==1) {
2059                                                                                 add_assoc_long(tmpi, name, info_value->i);
2060                                                                         } else {
2061                                                                                 add_index_long(array, ap, info_value->i);
2062                                                                         }
2063                                                                         break;
2064 
2065                                                                 case TAG_FMT_SRATIONAL:
2066                                                                         snprintf(buffer, sizeof(buffer), "%i/%i", info_value->sr.num, info_value->sr.den);
2067                                                                         if (l==1) {
2068                                                                                 add_assoc_string(tmpi, name, buffer, 1);
2069                                                                         } else {
2070                                                                                 add_index_string(array, ap, buffer, 1);
2071                                                                         }
2072                                                                         break;
2073 
2074                                                                 case TAG_FMT_SINGLE:
2075                                                                         if (l==1) {
2076                                                                                 add_assoc_double(tmpi, name, info_value->f);
2077                                                                         } else {
2078                                                                                 add_index_double(array, ap, info_value->f);
2079                                                                         }
2080                                                                         break;
2081 
2082                                                                 case TAG_FMT_DOUBLE:
2083                                                                         if (l==1) {
2084                                                                                 add_assoc_double(tmpi, name, info_value->d);
2085                                                                         } else {
2086                                                                                 add_index_double(array, ap, info_value->d);
2087                                                                         }
2088                                                                         break;
2089                                                         }
2090                                                         info_value = &info_data->value.list[ap];
2091                                                 }
2092                                                 if (l>1) {
2093                                                         add_assoc_zval(tmpi, name, array);
2094                                                 }
2095                                                 break;
2096                                 }
2097                         }
2098                 }
2099                 if (sub_array) {
2100                         add_assoc_zval(value, exif_get_sectionname(section_index), tmpi);
2101                 }
2102         }
2103 }
2104 /* }}} */
2105 
2106 /* {{{ Markers
2107    JPEG markers consist of one or more 0xFF bytes, followed by a marker
2108    code byte (which is not an FF).  Here are the marker codes of interest
2109    in this program.  (See jdmarker.c for a more complete list.)
2110 */
2111 
2112 #define M_TEM   0x01    /* temp for arithmetic coding              */
2113 #define M_RES   0x02    /* reserved                                */
2114 #define M_SOF0  0xC0    /* Start Of Frame N                        */
2115 #define M_SOF1  0xC1    /* N indicates which compression process   */
2116 #define M_SOF2  0xC2    /* Only SOF0-SOF2 are now in common use    */
2117 #define M_SOF3  0xC3
2118 #define M_DHT   0xC4
2119 #define M_SOF5  0xC5    /* NB: codes C4 and CC are NOT SOF markers */
2120 #define M_SOF6  0xC6
2121 #define M_SOF7  0xC7
2122 #define M_JPEG  0x08    /* reserved for extensions                 */
2123 #define M_SOF9  0xC9
2124 #define M_SOF10 0xCA
2125 #define M_SOF11 0xCB
2126 #define M_DAC   0xCC    /* arithmetic table                         */
2127 #define M_SOF13 0xCD
2128 #define M_SOF14 0xCE
2129 #define M_SOF15 0xCF
2130 #define M_RST0  0xD0    /* restart segment                          */
2131 #define M_RST1  0xD1
2132 #define M_RST2  0xD2
2133 #define M_RST3  0xD3
2134 #define M_RST4  0xD4
2135 #define M_RST5  0xD5
2136 #define M_RST6  0xD6
2137 #define M_RST7  0xD7
2138 #define M_SOI   0xD8    /* Start Of Image (beginning of datastream) */
2139 #define M_EOI   0xD9    /* End Of Image (end of datastream)         */
2140 #define M_SOS   0xDA    /* Start Of Scan (begins compressed data)   */
2141 #define M_DQT   0xDB
2142 #define M_DNL   0xDC
2143 #define M_DRI   0xDD
2144 #define M_DHP   0xDE
2145 #define M_EXP   0xDF
2146 #define M_APP0  0xE0    /* JPEG: 'JFIFF' AND (additional 'JFXX')    */
2147 #define M_EXIF  0xE1    /* Exif Attribute Information               */
2148 #define M_APP2  0xE2    /* Flash Pix Extension Data?                */
2149 #define M_APP3  0xE3
2150 #define M_APP4  0xE4
2151 #define M_APP5  0xE5
2152 #define M_APP6  0xE6
2153 #define M_APP7  0xE7
2154 #define M_APP8  0xE8
2155 #define M_APP9  0xE9
2156 #define M_APP10 0xEA
2157 #define M_APP11 0xEB
2158 #define M_APP12 0xEC
2159 #define M_APP13 0xED    /* IPTC International Press Telecommunications Council */
2160 #define M_APP14 0xEE    /* Software, Copyright?                     */
2161 #define M_APP15 0xEF
2162 #define M_JPG0  0xF0
2163 #define M_JPG1  0xF1
2164 #define M_JPG2  0xF2
2165 #define M_JPG3  0xF3
2166 #define M_JPG4  0xF4
2167 #define M_JPG5  0xF5
2168 #define M_JPG6  0xF6
2169 #define M_JPG7  0xF7
2170 #define M_JPG8  0xF8
2171 #define M_JPG9  0xF9
2172 #define M_JPG10 0xFA
2173 #define M_JPG11 0xFB
2174 #define M_JPG12 0xFC
2175 #define M_JPG13 0xFD
2176 #define M_COM   0xFE    /* COMment                                  */
2177 
2178 #define M_PSEUDO 0x123  /* Extra value.                             */
2179 
2180 /* }}} */
2181 
2182 /* {{{ jpeg2000 markers
2183  */
2184 /* Markers x30 - x3F do not have a segment */
2185 /* Markers x00, x01, xFE, xC0 - xDF ISO/IEC 10918-1 -> M_<xx> */
2186 /* Markers xF0 - xF7 ISO/IEC 10918-3 */
2187 /* Markers xF7 - xF8 ISO/IEC 14495-1 */
2188 /* XY=Main/Tile-header:(R:required, N:not_allowed, O:optional, L:last_marker) */
2189 #define JC_SOC   0x4F   /* NN, Start of codestream                          */
2190 #define JC_SIZ   0x51   /* RN, Image and tile size                          */
2191 #define JC_COD   0x52   /* RO, Codeing style defaulte                       */
2192 #define JC_COC   0x53   /* OO, Coding style component                       */
2193 #define JC_TLM   0x55   /* ON, Tile part length main header                 */
2194 #define JC_PLM   0x57   /* ON, Packet length main header                    */
2195 #define JC_PLT   0x58   /* NO, Packet length tile part header               */
2196 #define JC_QCD   0x5C   /* RO, Quantization default                         */
2197 #define JC_QCC   0x5D   /* OO, Quantization component                       */
2198 #define JC_RGN   0x5E   /* OO, Region of interest                           */
2199 #define JC_POD   0x5F   /* OO, Progression order default                    */
2200 #define JC_PPM   0x60   /* ON, Packed packet headers main header            */
2201 #define JC_PPT   0x61   /* NO, Packet packet headers tile part header       */
2202 #define JC_CME   0x64   /* OO, Comment: "LL E <text>" E=0:binary, E=1:ascii */
2203 #define JC_SOT   0x90   /* NR, Start of tile                                */
2204 #define JC_SOP   0x91   /* NO, Start of packeter default                    */
2205 #define JC_EPH   0x92   /* NO, End of packet header                         */
2206 #define JC_SOD   0x93   /* NL, Start of data                                */
2207 #define JC_EOC   0xD9   /* NN, End of codestream                            */
2208 /* }}} */
2209 
2210 /* {{{ exif_process_COM
2211    Process a COM marker.
2212    We want to print out the marker contents as legible text;
2213    we must guard against random junk and varying newline representations.
2214 */
2215 static void exif_process_COM (image_info_type *image_info, char *value, size_t length TSRMLS_DC)
2216 {
2217         exif_iif_add_tag(image_info, SECTION_COMMENT, "Comment", TAG_COMPUTED_VALUE, TAG_FMT_STRING, length-2, value+2 TSRMLS_CC);
2218 }
2219 /* }}} */
2220 
2221 /* {{{ exif_process_CME
2222    Process a CME marker.
2223    We want to print out the marker contents as legible text;
2224    we must guard against random junk and varying newline representations.
2225 */
2226 #ifdef EXIF_JPEG2000
2227 static void exif_process_CME (image_info_type *image_info, char *value, size_t length TSRMLS_DC)
2228 {
2229         if (length>3) {
2230                 switch(value[2]) {
2231                         case 0:
2232                                 exif_iif_add_tag(image_info, SECTION_COMMENT, "Comment", TAG_COMPUTED_VALUE, TAG_FMT_UNDEFINED, length, value TSRMLS_CC);
2233                                 break;
2234                         case 1:
2235                                 exif_iif_add_tag(image_info, SECTION_COMMENT, "Comment", TAG_COMPUTED_VALUE, TAG_FMT_STRING, length, value);
2236                                 break;
2237                         default:
2238                                 php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Undefined JPEG2000 comment encoding");
2239                                 break;
2240                 }
2241         } else {
2242                 exif_iif_add_tag(image_info, SECTION_COMMENT, "Comment", TAG_COMPUTED_VALUE, TAG_FMT_UNDEFINED, 0, NULL);
2243                 php_error_docref(NULL TSRMLS_CC, E_NOTICE, "JPEG2000 comment section too small");
2244         }
2245 }
2246 #endif
2247 /* }}} */
2248 
2249 /* {{{ exif_process_SOFn
2250  * Process a SOFn marker.  This is useful for the image dimensions */
2251 static void exif_process_SOFn (uchar *Data, int marker, jpeg_sof_info *result)
2252 {
2253 /* 0xFF SOSn SectLen(2) Bits(1) Height(2) Width(2) Channels(1)  3*Channels (1)  */
2254         result->bits_per_sample = Data[2];
2255         result->height          = php_jpg_get16(Data+3);
2256         result->width           = php_jpg_get16(Data+5);
2257         result->num_components  = Data[7];
2258 
2259 /*      switch (marker) {
2260                 case M_SOF0:  process = "Baseline";  break;
2261                 case M_SOF1:  process = "Extended sequential";  break;
2262                 case M_SOF2:  process = "Progressive";  break;
2263                 case M_SOF3:  process = "Lossless";  break;
2264                 case M_SOF5:  process = "Differential sequential";  break;
2265                 case M_SOF6:  process = "Differential progressive";  break;
2266                 case M_SOF7:  process = "Differential lossless";  break;
2267                 case M_SOF9:  process = "Extended sequential, arithmetic coding";  break;
2268                 case M_SOF10: process = "Progressive, arithmetic coding";  break;
2269                 case M_SOF11: process = "Lossless, arithmetic coding";  break;
2270                 case M_SOF13: process = "Differential sequential, arithmetic coding";  break;
2271                 case M_SOF14: process = "Differential progressive, arithmetic coding"; break;
2272                 case M_SOF15: process = "Differential lossless, arithmetic coding";  break;
2273                 default:      process = "Unknown";  break;
2274         }*/
2275 }
2276 /* }}} */
2277 
2278 /* forward declarations */
2279 static int exif_process_IFD_in_JPEG(image_info_type *ImageInfo, char *dir_start, char *offset_base, size_t IFDlength, size_t displacement, int section_index TSRMLS_DC);
2280 static int exif_process_IFD_TAG(    image_info_type *ImageInfo, char *dir_entry, char *offset_base, size_t IFDlength, size_t displacement, int section_index, int ReadNextIFD, tag_table_type tag_table TSRMLS_DC);
2281 
2282 /* {{{ exif_get_markername
2283         Get name of marker */
2284 #ifdef EXIF_DEBUG
2285 static char * exif_get_markername(int marker)
2286 {
2287         switch(marker) {
2288                 case 0xC0: return "SOF0";
2289                 case 0xC1: return "SOF1";
2290                 case 0xC2: return "SOF2";
2291                 case 0xC3: return "SOF3";
2292                 case 0xC4: return "DHT";
2293                 case 0xC5: return "SOF5";
2294                 case 0xC6: return "SOF6";
2295                 case 0xC7: return "SOF7";
2296                 case 0xC9: return "SOF9";
2297                 case 0xCA: return "SOF10";
2298                 case 0xCB: return "SOF11";
2299                 case 0xCD: return "SOF13";
2300                 case 0xCE: return "SOF14";
2301                 case 0xCF: return "SOF15";
2302                 case 0xD8: return "SOI";
2303                 case 0xD9: return "EOI";
2304                 case 0xDA: return "SOS";
2305                 case 0xDB: return "DQT";
2306                 case 0xDC: return "DNL";
2307                 case 0xDD: return "DRI";
2308                 case 0xDE: return "DHP";
2309                 case 0xDF: return "EXP";
2310                 case 0xE0: return "APP0";
2311                 case 0xE1: return "EXIF";
2312                 case 0xE2: return "FPIX";
2313                 case 0xE3: return "APP3";
2314                 case 0xE4: return "APP4";
2315                 case 0xE5: return "APP5";
2316                 case 0xE6: return "APP6";
2317                 case 0xE7: return "APP7";
2318                 case 0xE8: return "APP8";
2319                 case 0xE9: return "APP9";
2320                 case 0xEA: return "APP10";
2321                 case 0xEB: return "APP11";
2322                 case 0xEC: return "APP12";
2323                 case 0xED: return "APP13";
2324                 case 0xEE: return "APP14";
2325                 case 0xEF: return "APP15";
2326                 case 0xF0: return "JPG0";
2327                 case 0xFD: return "JPG13";
2328                 case 0xFE: return "COM";
2329                 case 0x01: return "TEM";
2330         }
2331         return "Unknown";
2332 }
2333 #endif
2334 /* }}} */
2335 
2336 /* {{{ proto string exif_tagname(index)
2337         Get headername for index or false if not defined */
2338 PHP_FUNCTION(exif_tagname)
2339 {
2340         long tag;
2341         char *szTemp;
2342 
2343         if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &tag) == FAILURE) {
2344                 return;
2345         }
2346 
2347         szTemp = exif_get_tagname(tag, NULL, 0, tag_table_IFD TSRMLS_CC);
2348 
2349         if (tag < 0 || !szTemp || !szTemp[0]) {
2350                 RETURN_FALSE;
2351         }
2352 
2353         RETURN_STRING(szTemp, 1)
2354 }
2355 /* }}} */
2356 
2357 /* {{{ exif_ifd_make_value
2358  * Create a value for an ifd from an info_data pointer */
2359 static void* exif_ifd_make_value(image_info_data *info_data, int motorola_intel TSRMLS_DC) {
2360         size_t  byte_count;
2361         char    *value_ptr, *data_ptr;
2362         size_t  i;
2363 
2364         image_info_value  *info_value;
2365 
2366         byte_count = php_tiff_bytes_per_format[info_data->format] * info_data->length;
2367         value_ptr = safe_emalloc(max(byte_count, 4), 1, 0);
2368         memset(value_ptr, 0, 4);
2369         if (!info_data->length) {
2370                 return value_ptr;
2371         }
2372         if (info_data->format == TAG_FMT_UNDEFINED || info_data->format == TAG_FMT_STRING
2373           || (byte_count>1 && (info_data->format == TAG_FMT_BYTE || info_data->format == TAG_FMT_SBYTE))
2374         ) {
2375                 memmove(value_ptr, info_data->value.s, byte_count);
2376                 return value_ptr;
2377         } else if (info_data->format == TAG_FMT_BYTE) {
2378                 *value_ptr = info_data->value.u;
2379                 return value_ptr;
2380         } else if (info_data->format == TAG_FMT_SBYTE) {
2381                 *value_ptr = info_data->value.i;
2382                 return value_ptr;
2383         } else {
2384                 data_ptr = value_ptr;
2385                 for(i=0; i<info_data->length; i++) {
2386                         if (info_data->length==1) {
2387                                 info_value = &info_data->value;
2388                         } else {
2389                                 info_value = &info_data->value.list[i];
2390                         }
2391                         switch(info_data->format) {
2392                                 case TAG_FMT_USHORT:
2393                                         php_ifd_set16u(data_ptr, info_value->u, motorola_intel);
2394                                         data_ptr += 2;
2395                                         break;
2396                                 case TAG_FMT_ULONG:
2397                                         php_ifd_set32u(data_ptr, info_value->u, motorola_intel);
2398                                         data_ptr += 4;
2399                                         break;
2400                                 case TAG_FMT_SSHORT:
2401                                         php_ifd_set16u(data_ptr, info_value->i, motorola_intel);
2402                                         data_ptr += 2;
2403                                         break;
2404                                 case TAG_FMT_SLONG:
2405                                         php_ifd_set32u(data_ptr, info_value->i, motorola_intel);
2406                                         data_ptr += 4;
2407                                         break;
2408                                 case TAG_FMT_URATIONAL:
2409                                         php_ifd_set32u(data_ptr,   info_value->sr.num, motorola_intel);
2410                                         php_ifd_set32u(data_ptr+4, info_value->sr.den, motorola_intel);
2411                                         data_ptr += 8;
2412                                         break;
2413                                 case TAG_FMT_SRATIONAL:
2414                                         php_ifd_set32u(data_ptr,   info_value->ur.num, motorola_intel);
2415                                         php_ifd_set32u(data_ptr+4, info_value->ur.den, motorola_intel);
2416                                         data_ptr += 8;
2417                                         break;
2418                                 case TAG_FMT_SINGLE:
2419                                         memmove(data_ptr, &info_value->f, 4);
2420                                         data_ptr += 4;
2421                                         break;
2422                                 case TAG_FMT_DOUBLE:
2423                                         memmove(data_ptr, &info_value->d, 8);
2424                                         data_ptr += 8;
2425                                         break;
2426                         }
2427                 }
2428         }
2429         return value_ptr;
2430 }
2431 /* }}} */
2432 
2433 /* {{{ exif_thumbnail_build
2434  * Check and build thumbnail */
2435 static void exif_thumbnail_build(image_info_type *ImageInfo TSRMLS_DC) {
2436         size_t            new_size, new_move, new_value;
2437         char              *new_data;
2438         void              *value_ptr;
2439         int               i, byte_count;
2440         image_info_list   *info_list;
2441         image_info_data   *info_data;
2442 #ifdef EXIF_DEBUG
2443         char              tagname[64];
2444 #endif
2445 
2446         if (!ImageInfo->read_thumbnail || !ImageInfo->Thumbnail.offset || !ImageInfo->Thumbnail.size) {
2447                 return; /* ignore this call */
2448         }
2449 #ifdef EXIF_DEBUG
2450         exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail: filetype = %d", ImageInfo->Thumbnail.filetype);
2451 #endif
2452         switch(ImageInfo->Thumbnail.filetype) {
2453                 default:
2454                 case IMAGE_FILETYPE_JPEG:
2455                         /* done */
2456                         break;
2457                 case IMAGE_FILETYPE_TIFF_II:
2458                 case IMAGE_FILETYPE_TIFF_MM:
2459                         info_list = &ImageInfo->info_list[SECTION_THUMBNAIL];
2460                         new_size  = 8 + 2 + info_list->count * 12 + 4;
2461 #ifdef EXIF_DEBUG
2462                         exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail: size of signature + directory(%d): 0x%02X", info_list->count, new_size);
2463 #endif
2464                         new_value= new_size; /* offset for ifd values outside ifd directory */
2465                         for (i=0; i<info_list->count; i++) {
2466                                 info_data  = &info_list->list[i];
2467                                 byte_count = php_tiff_bytes_per_format[info_data->format] * info_data->length;
2468                                 if (byte_count > 4) {
2469                                         new_size += byte_count;
2470                                 }
2471                         }
2472                         new_move = new_size;
2473                         new_data = safe_erealloc(ImageInfo->Thumbnail.data, 1, ImageInfo->Thumbnail.size, new_size);
2474                         ImageInfo->Thumbnail.data = new_data;
2475                         memmove(ImageInfo->Thumbnail.data + new_move, ImageInfo->Thumbnail.data, ImageInfo->Thumbnail.size);
2476                         ImageInfo->Thumbnail.size += new_size;
2477                         /* fill in data */
2478                         if (ImageInfo->motorola_intel) {
2479                                 memmove(new_data, "MM\x00\x2a\x00\x00\x00\x08", 8);
2480                         } else {
2481                                 memmove(new_data, "II\x2a\x00\x08\x00\x00\x00", 8);
2482                         }
2483                         new_data += 8;
2484                         php_ifd_set16u(new_data, info_list->count, ImageInfo->motorola_intel);
2485                         new_data += 2;
2486                         for (i=0; i<info_list->count; i++) {
2487                                 info_data  = &info_list->list[i];
2488                                 byte_count = php_tiff_bytes_per_format[info_data->format] * info_data->length;
2489 #ifdef EXIF_DEBUG
2490                                 exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail: process tag(x%04X=%s): %s%s (%d bytes)", info_data->tag, exif_get_tagname(info_data->tag, tagname, -12, tag_table_IFD TSRMLS_CC), (info_data->length>1)&&info_data->format!=TAG_FMT_UNDEFINED&&info_data->format!=TAG_FMT_STRING?"ARRAY OF ":"", exif_get_tagformat(info_data->format), byte_count);
2491 #endif
2492                                 if (info_data->tag==TAG_STRIP_OFFSETS || info_data->tag==TAG_JPEG_INTERCHANGE_FORMAT) {
2493                                         php_ifd_set16u(new_data + 0, info_data->tag,    ImageInfo->motorola_intel);
2494                                         php_ifd_set16u(new_data + 2, TAG_FMT_ULONG,     ImageInfo->motorola_intel);
2495                                         php_ifd_set32u(new_data + 4, 1,                 ImageInfo->motorola_intel);
2496                                         php_ifd_set32u(new_data + 8, new_move,          ImageInfo->motorola_intel);
2497                                 } else {
2498                                         php_ifd_set16u(new_data + 0, info_data->tag,    ImageInfo->motorola_intel);
2499                                         php_ifd_set16u(new_data + 2, info_data->format, ImageInfo->motorola_intel);
2500                                         php_ifd_set32u(new_data + 4, info_data->length, ImageInfo->motorola_intel);
2501                                         value_ptr  = exif_ifd_make_value(info_data, ImageInfo->motorola_intel TSRMLS_CC);
2502                                         if (byte_count <= 4) {
2503                                                 memmove(new_data+8, value_ptr, 4);
2504                                         } else {
2505                                                 php_ifd_set32u(new_data+8, new_value, ImageInfo->motorola_intel);
2506 #ifdef EXIF_DEBUG
2507                                                 exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail: writing with value offset: 0x%04X + 0x%02X", new_value, byte_count);
2508 #endif
2509                                                 memmove(ImageInfo->Thumbnail.data+new_value, value_ptr, byte_count);
2510                                                 new_value += byte_count;
2511                                         }
2512                                         efree(value_ptr);
2513                                 }
2514                                 new_data += 12;
2515                         }
2516                         memset(new_data, 0, 4); /* next ifd pointer */
2517 #ifdef EXIF_DEBUG
2518                         exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail: created");
2519 #endif
2520                         break;
2521         }
2522 }
2523 /* }}} */
2524 
2525 /* {{{ exif_thumbnail_extract
2526  * Grab the thumbnail, corrected */
2527 static void exif_thumbnail_extract(image_info_type *ImageInfo, char *offset, size_t length TSRMLS_DC) {
2528         if (ImageInfo->Thumbnail.data) {
2529                 exif_error_docref("exif_read_data#error_mult_thumb" EXIFERR_CC, ImageInfo, E_WARNING, "Multiple possible thumbnails");
2530                 return; /* Should not happen */
2531         }
2532         if (!ImageInfo->read_thumbnail) {
2533                 return; /* ignore this call */
2534         }
2535         /* according to exif2.1, the thumbnail is not supposed to be greater than 64K */
2536         if (ImageInfo->Thumbnail.size >= 65536
2537          || ImageInfo->Thumbnail.size <= 0
2538          || ImageInfo->Thumbnail.offset <= 0
2539         ) {
2540                 exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Illegal thumbnail size/offset");
2541                 return;
2542         }
2543         /* Check to make sure we are not going to go past the ExifLength */
2544         if ((ImageInfo->Thumbnail.offset + ImageInfo->Thumbnail.size) > length) {
2545                 EXIF_ERRLOG_THUMBEOF(ImageInfo)
2546                 return;
2547         }
2548         ImageInfo->Thumbnail.data = estrndup(offset + ImageInfo->Thumbnail.offset, ImageInfo->Thumbnail.size);
2549         exif_thumbnail_build(ImageInfo TSRMLS_CC);
2550 }
2551 /* }}} */
2552 
2553 /* {{{ exif_process_undefined
2554  * Copy a string/buffer in Exif header to a character string and return length of allocated buffer if any. */
2555 static int exif_process_undefined(char **result, char *value, size_t byte_count TSRMLS_DC) {
2556         /* we cannot use strlcpy - here the problem is that we have to copy NUL
2557          * chars up to byte_count, we also have to add a single NUL character to
2558          * force end of string.
2559          * estrndup does not return length
2560          */
2561         if (byte_count) {
2562                 (*result) = estrndup(value, byte_count); /* NULL @ byte_count!!! */
2563                 return byte_count+1;
2564         }
2565         return 0;
2566 }
2567 /* }}} */
2568 
2569 /* {{{ exif_process_string_raw
2570  * Copy a string in Exif header to a character string returns length of allocated buffer if any. */
2571 static int exif_process_string_raw(char **result, char *value, size_t byte_count) {
2572         /* we cannot use strlcpy - here the problem is that we have to copy NUL
2573          * chars up to byte_count, we also have to add a single NUL character to
2574          * force end of string.
2575          */
2576         if (byte_count) {
2577                 (*result) = safe_emalloc(byte_count, 1, 1);
2578                 memcpy(*result, value, byte_count);
2579                 (*result)[byte_count] = '\0';
2580                 return byte_count+1;
2581         }
2582         return 0;
2583 }
2584 /* }}} */
2585 
2586 /* {{{ exif_process_string
2587  * Copy a string in Exif header to a character string and return length of allocated buffer if any.
2588  * In contrast to exif_process_string this function does always return a string buffer */
2589 static int exif_process_string(char **result, char *value, size_t byte_count TSRMLS_DC) {
2590         /* we cannot use strlcpy - here the problem is that we cannot use strlen to
2591          * determin length of string and we cannot use strlcpy with len=byte_count+1
2592          * because then we might get into an EXCEPTION if we exceed an allocated
2593          * memory page...so we use php_strnlen in conjunction with memcpy and add the NUL
2594          * char.
2595          * estrdup would sometimes allocate more memory and does not return length
2596          */
2597         if ((byte_count=php_strnlen(value, byte_count)) > 0) {
2598                 return exif_process_undefined(result, value, byte_count TSRMLS_CC);
2599         }
2600         (*result) = estrndup("", 1); /* force empty string */
2601         return byte_count+1;
2602 }
2603 /* }}} */
2604 
2605 /* {{{ exif_process_user_comment
2606  * Process UserComment in IFD. */
2607 static int exif_process_user_comment(image_info_type *ImageInfo, char **pszInfoPtr, char **pszEncoding, char *szValuePtr, int ByteCount TSRMLS_DC)
2608 {
2609         int   a;
2610         char  *decode;
2611         size_t len;;
2612 
2613         *pszEncoding = NULL;
2614         /* Copy the comment */
2615         if (ByteCount>=8) {
2616                 if (!memcmp(szValuePtr, "UNICODE\0", 8)) {
2617                         *pszEncoding = estrdup((const char*)szValuePtr);
2618                         szValuePtr = szValuePtr+8;
2619                         ByteCount -= 8;
2620                         /* First try to detect BOM: ZERO WIDTH NOBREAK SPACE (FEFF 16)
2621                          * since we have no encoding support for the BOM yet we skip that.
2622                          */
2623                         if (!memcmp(szValuePtr, "\xFE\xFF", 2)) {
2624                                 decode = "UCS-2BE";
2625                                 szValuePtr = szValuePtr+2;
2626                                 ByteCount -= 2;
2627                         } else if (!memcmp(szValuePtr, "\xFF\xFE", 2)) {
2628                                 decode = "UCS-2LE";
2629                                 szValuePtr = szValuePtr+2;
2630                                 ByteCount -= 2;
2631                         } else if (ImageInfo->motorola_intel) {
2632                                 decode = ImageInfo->decode_unicode_be;
2633                         } else {
2634                                 decode = ImageInfo->decode_unicode_le;
2635                         }
2636                         /* XXX this will fail again if encoding_converter returns on error something different than SIZE_MAX   */
2637                         if (zend_multibyte_encoding_converter(
2638                                         (unsigned char**)pszInfoPtr,
2639                                         &len,
2640                                         (unsigned char*)szValuePtr,
2641                                         ByteCount,
2642                                         zend_multibyte_fetch_encoding(ImageInfo->encode_unicode TSRMLS_CC),
2643                                         zend_multibyte_fetch_encoding(decode TSRMLS_CC)
2644                                         TSRMLS_CC) == (size_t)-1) {
2645                                 len = exif_process_string_raw(pszInfoPtr, szValuePtr, ByteCount);
2646                         }
2647                         return len;
2648                 } else if (!memcmp(szValuePtr, "ASCII\0\0\0", 8)) {
2649                         *pszEncoding = estrdup((const char*)szValuePtr);
2650                         szValuePtr = szValuePtr+8;
2651                         ByteCount -= 8;
2652                 } else if (!memcmp(szValuePtr, "JIS\0\0\0\0\0", 8)) {
2653                         /* JIS should be tanslated to MB or we leave it to the user - leave it to the user */
2654                         *pszEncoding = estrdup((const char*)szValuePtr);
2655                         szValuePtr = szValuePtr+8;
2656                         ByteCount -= 8;
2657                         /* XXX this will fail again if encoding_converter returns on error something different than SIZE_MAX   */
2658                         if (zend_multibyte_encoding_converter(
2659                                         (unsigned char**)pszInfoPtr,
2660                                         &len,
2661                                         (unsigned char*)szValuePtr,
2662                                         ByteCount,
2663                                         zend_multibyte_fetch_encoding(ImageInfo->encode_jis TSRMLS_CC),
2664                                         zend_multibyte_fetch_encoding(ImageInfo->motorola_intel ? ImageInfo->decode_jis_be : ImageInfo->decode_jis_le TSRMLS_CC)
2665                                         TSRMLS_CC) == (size_t)-1) {
2666                                 len = exif_process_string_raw(pszInfoPtr, szValuePtr, ByteCount);
2667                         }
2668                         return len;
2669                 } else if (!memcmp(szValuePtr, "\0\0\0\0\0\0\0\0", 8)) {
2670                         /* 8 NULL means undefined and should be ASCII... */
2671                         *pszEncoding = estrdup("UNDEFINED");
2672                         szValuePtr = szValuePtr+8;
2673                         ByteCount -= 8;
2674                 }
2675         }
2676 
2677         /* Olympus has this padded with trailing spaces.  Remove these first. */
2678         if (ByteCount>0) {
2679                 for (a=ByteCount-1;a && szValuePtr[a]==' ';a--) {
2680                         (szValuePtr)[a] = '\0';
2681                 }
2682         }
2683 
2684         /* normal text without encoding */
2685         exif_process_string(pszInfoPtr, szValuePtr, ByteCount TSRMLS_CC);
2686         return strlen(*pszInfoPtr);
2687 }
2688 /* }}} */
2689 
2690 /* {{{ exif_process_unicode
2691  * Process unicode field in IFD. */
2692 static int exif_process_unicode(image_info_type *ImageInfo, xp_field_type *xp_field, int tag, char *szValuePtr, int ByteCount TSRMLS_DC)
2693 {
2694         xp_field->tag = tag;
2695         xp_field->value = NULL;
2696         /* XXX this will fail again if encoding_converter returns on error something different than SIZE_MAX   */
2697         if (zend_multibyte_encoding_converter(
2698                         (unsigned char**)&xp_field->value,
2699                         &xp_field->size,
2700                         (unsigned char*)szValuePtr,
2701                         ByteCount,
2702                         zend_multibyte_fetch_encoding(ImageInfo->encode_unicode TSRMLS_CC),
2703                         zend_multibyte_fetch_encoding(ImageInfo->motorola_intel ? ImageInfo->decode_unicode_be : ImageInfo->decode_unicode_le TSRMLS_CC)
2704                         TSRMLS_CC) == (size_t)-1) {
2705                 xp_field->size = exif_process_string_raw(&xp_field->value, szValuePtr, ByteCount);
2706         }
2707         return xp_field->size;
2708 }
2709 /* }}} */
2710 
2711 /* {{{ exif_process_IFD_in_MAKERNOTE
2712  * Process nested IFDs directories in Maker Note. */
2713 static int exif_process_IFD_in_MAKERNOTE(image_info_type *ImageInfo, char * value_ptr, int value_len, char *offset_base, size_t IFDlength, size_t displacement TSRMLS_DC)
2714 {
2715         int de, i=0, section_index = SECTION_MAKERNOTE;
2716         int NumDirEntries, old_motorola_intel, offset_diff;
2717         const maker_note_type *maker_note;
2718         char *dir_start;
2719 
2720         for (i=0; i<=sizeof(maker_note_array)/sizeof(maker_note_type); i++) {
2721                 if (i==sizeof(maker_note_array)/sizeof(maker_note_type))
2722                         return FALSE;
2723                 maker_note = maker_note_array+i;
2724 
2725                 /*exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "check (%s,%s)", maker_note->make?maker_note->make:"", maker_note->model?maker_note->model:"");*/
2726                 if (maker_note->make && (!ImageInfo->make || strcmp(maker_note->make, ImageInfo->make)))
2727                         continue;
2728                 if (maker_note->model && (!ImageInfo->model || strcmp(maker_note->model, ImageInfo->model)))
2729                         continue;
2730                 if (maker_note->id_string && strncmp(maker_note->id_string, value_ptr, maker_note->id_string_len))
2731                         continue;
2732                 break;
2733         }
2734 
2735         dir_start = value_ptr + maker_note->offset;
2736 
2737 #ifdef EXIF_DEBUG
2738         exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process %s @x%04X + 0x%04X=%d: %s", exif_get_sectionname(section_index), (int)dir_start-(int)offset_base+maker_note->offset+displacement, value_len, value_len, exif_char_dump(value_ptr, value_len, (int)dir_start-(int)offset_base+maker_note->offset+displacement));
2739 #endif
2740 
2741         ImageInfo->sections_found |= FOUND_MAKERNOTE;
2742 
2743         old_motorola_intel = ImageInfo->motorola_intel;
2744         switch (maker_note->byte_order) {
2745                 case MN_ORDER_INTEL:
2746                         ImageInfo->motorola_intel = 0;
2747                         break;
2748                 case MN_ORDER_MOTOROLA:
2749                         ImageInfo->motorola_intel = 1;
2750                         break;
2751                 default:
2752                 case MN_ORDER_NORMAL:
2753                         break;
2754         }
2755 
2756         NumDirEntries = php_ifd_get16u(dir_start, ImageInfo->motorola_intel);
2757 
2758         switch (maker_note->offset_mode) {
2759                 case MN_OFFSET_MAKER:
2760                         offset_base = value_ptr;
2761                         break;
2762                 case MN_OFFSET_GUESS:
2763                         offset_diff = 2 + NumDirEntries*12 + 4 - php_ifd_get32u(dir_start+10, ImageInfo->motorola_intel);
2764 #ifdef EXIF_DEBUG
2765                         exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Using automatic offset correction: 0x%04X", ((int)dir_start-(int)offset_base+maker_note->offset+displacement) + offset_diff);
2766 #endif
2767                         offset_base = value_ptr + offset_diff;
2768                         break;
2769                 default:
2770                 case MN_OFFSET_NORMAL:
2771                         break;
2772         }
2773 
2774         if ((2+NumDirEntries*12) > value_len) {
2775                 exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Illegal IFD size: 2 + x%04X*12 = x%04X > x%04X", NumDirEntries, 2+NumDirEntries*12, value_len);
2776                 return FALSE;
2777         }
2778 
2779         for (de=0;de<NumDirEntries;de++) {
2780                 if (!exif_process_IFD_TAG(ImageInfo, dir_start + 2 + 12 * de,
2781                                                                   offset_base, IFDlength, displacement, section_index, 0, maker_note->tag_table TSRMLS_CC)) {
2782                         return FALSE;
2783                 }
2784         }
2785         ImageInfo->motorola_intel = old_motorola_intel;
2786 /*      NextDirOffset (must be NULL) = php_ifd_get32u(dir_start+2+12*de, ImageInfo->motorola_intel);*/
2787 #ifdef EXIF_DEBUG
2788         exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Subsection %s done", exif_get_sectionname(SECTION_MAKERNOTE));
2789 #endif
2790         return TRUE;
2791 }
2792 /* }}} */
2793 
2794 /* {{{ exif_process_IFD_TAG
2795  * Process one of the nested IFDs directories. */
2796 static int exif_process_IFD_TAG(image_info_type *ImageInfo, char *dir_entry, char *offset_base, size_t IFDlength, size_t displacement, int section_index, int ReadNextIFD, tag_table_type tag_table TSRMLS_DC)
2797 {
2798         size_t length;
2799         int tag, format, components;
2800         char *value_ptr, tagname[64], cbuf[32], *outside=NULL;
2801         size_t byte_count, offset_val, fpos, fgot;
2802         int64_t byte_count_signed;
2803         xp_field_type *tmp_xp;
2804 #ifdef EXIF_DEBUG
2805         char *dump_data;
2806         int dump_free;
2807 #endif /* EXIF_DEBUG */
2808 
2809         /* Protect against corrupt headers */
2810         if (ImageInfo->ifd_nesting_level > MAX_IFD_NESTING_LEVEL) {
2811                 exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "corrupt EXIF header: maximum directory nesting level reached");
2812                 return FALSE;
2813         }
2814         ImageInfo->ifd_nesting_level++;
2815 
2816         tag = php_ifd_get16u(dir_entry, ImageInfo->motorola_intel);
2817         format = php_ifd_get16u(dir_entry+2, ImageInfo->motorola_intel);
2818         components = php_ifd_get32u(dir_entry+4, ImageInfo->motorola_intel);
2819 
2820         if (!format || format > NUM_FORMATS) {
2821                 /* (-1) catches illegal zero case as unsigned underflows to positive large. */
2822                 exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal format code 0x%04X, suppose BYTE", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), format);
2823                 format = TAG_FMT_BYTE;
2824                 /*return TRUE;*/
2825         }
2826 
2827         if (components < 0) {
2828                 exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal components(%ld)", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), components);
2829                 return FALSE;
2830         }
2831 
2832         byte_count_signed = (int64_t)components * php_tiff_bytes_per_format[format];
2833 
2834         if (byte_count_signed < 0 || (byte_count_signed > INT32_MAX)) {
2835                 exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal byte_count", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC));
2836                 return FALSE;
2837         }
2838 
2839         byte_count = (size_t)byte_count_signed;
2840 
2841         if (byte_count > 4) {
2842                 offset_val = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel);
2843                 /* If its bigger than 4 bytes, the dir entry contains an offset. */
2844                 value_ptr = offset_base+offset_val;
2845         /*
2846             dir_entry is ImageInfo->file.list[sn].data+2+i*12
2847             offset_base is ImageInfo->file.list[sn].data-dir_offset
2848             dir_entry - offset_base is dir_offset+2+i*12
2849         */
2850                 if (byte_count > IFDlength || offset_val > IFDlength-byte_count || value_ptr < dir_entry || offset_val < (size_t)(dir_entry-offset_base)) {
2851                         /* It is important to check for IMAGE_FILETYPE_TIFF
2852                          * JPEG does not use absolute pointers instead its pointers are
2853                          * relative to the start of the TIFF header in APP1 section. */
2854                         if (byte_count > ImageInfo->FileSize || offset_val>ImageInfo->FileSize-byte_count || (ImageInfo->FileType!=IMAGE_FILETYPE_TIFF_II && ImageInfo->FileType!=IMAGE_FILETYPE_TIFF_MM && ImageInfo->FileType!=IMAGE_FILETYPE_JPEG)) {
2855                                 if (value_ptr < dir_entry) {
2856                                         /* we can read this if offset_val > 0 */
2857                                         /* some files have their values in other parts of the file */
2858                                         exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal pointer offset(x%04X < x%04X)", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), offset_val, dir_entry);
2859                                 } else {
2860                                         /* this is for sure not allowed */
2861                                         /* exception are IFD pointers */
2862                                         exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal pointer offset(x%04X + x%04X = x%04X > x%04X)", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), offset_val, byte_count, offset_val+byte_count, IFDlength);
2863                                 }
2864                                 return FALSE;
2865                         }
2866                         if (byte_count>sizeof(cbuf)) {
2867                                 /* mark as outside range and get buffer */
2868                                 value_ptr = safe_emalloc(byte_count, 1, 0);
2869                                 outside = value_ptr;
2870                         } else {
2871                                 /* In most cases we only access a small range so
2872                                  * it is faster to use a static buffer there
2873                                  * BUT it offers also the possibility to have
2874                                  * pointers read without the need to free them
2875                                  * explicitley before returning. */
2876                                 memset(&cbuf, 0, sizeof(cbuf));
2877                                 value_ptr = cbuf;
2878                         }
2879 
2880                         fpos = php_stream_tell(ImageInfo->infile);
2881                         php_stream_seek(ImageInfo->infile, offset_val, SEEK_SET);
2882                         fgot = php_stream_tell(ImageInfo->infile);
2883                         if (fgot!=offset_val) {
2884                                 EFREE_IF(outside);
2885                                 exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Wrong file pointer: 0x%08X != 0x%08X", fgot, offset_val);
2886                                 return FALSE;
2887                         }
2888                         fgot = php_stream_read(ImageInfo->infile, value_ptr, byte_count);
2889                         php_stream_seek(ImageInfo->infile, fpos, SEEK_SET);
2890                         if (fgot<byte_count) {
2891                                 EFREE_IF(outside);
2892                                 EXIF_ERRLOG_FILEEOF(ImageInfo)
2893                                 return FALSE;
2894                         }
2895                 }
2896         } else {
2897                 /* 4 bytes or less and value is in the dir entry itself */
2898                 value_ptr = dir_entry+8;
2899                 offset_val= value_ptr-offset_base;
2900         }
2901 
2902         ImageInfo->sections_found |= FOUND_ANY_TAG;
2903 #ifdef EXIF_DEBUG
2904         dump_data = exif_dump_data(&dump_free, format, components, length, ImageInfo->motorola_intel, value_ptr TSRMLS_CC);
2905         exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process tag(x%04X=%s,@x%04X + x%04X(=%d)): %s%s %s", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), offset_val+displacement, byte_count, byte_count, (components>1)&&format!=TAG_FMT_UNDEFINED&&format!=TAG_FMT_STRING?"ARRAY OF ":"", exif_get_tagformat(format), dump_data);
2906         if (dump_free) {
2907                 efree(dump_data);
2908         }
2909 #endif
2910 
2911         if (section_index==SECTION_THUMBNAIL) {
2912                 if (!ImageInfo->Thumbnail.data) {
2913                         switch(tag) {
2914                                 case TAG_IMAGEWIDTH:
2915                                 case TAG_COMP_IMAGE_WIDTH:
2916                                         ImageInfo->Thumbnail.width = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
2917                                         break;
2918 
2919                                 case TAG_IMAGEHEIGHT:
2920                                 case TAG_COMP_IMAGE_HEIGHT:
2921                                         ImageInfo->Thumbnail.height = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
2922                                         break;
2923 
2924                                 case TAG_STRIP_OFFSETS:
2925                                 case TAG_JPEG_INTERCHANGE_FORMAT:
2926                                         /* accept both formats */
2927                                         ImageInfo->Thumbnail.offset = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
2928                                         break;
2929 
2930                                 case TAG_STRIP_BYTE_COUNTS:
2931                                         if (ImageInfo->FileType == IMAGE_FILETYPE_TIFF_II || ImageInfo->FileType == IMAGE_FILETYPE_TIFF_MM) {
2932                                                 ImageInfo->Thumbnail.filetype = ImageInfo->FileType;
2933                                         } else {
2934                                                 /* motorola is easier to read */
2935                                                 ImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_TIFF_MM;
2936                                         }
2937                                         ImageInfo->Thumbnail.size = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
2938                                         break;
2939 
2940                                 case TAG_JPEG_INTERCHANGE_FORMAT_LEN:
2941                                         if (ImageInfo->Thumbnail.filetype == IMAGE_FILETYPE_UNKNOWN) {
2942                                                 ImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_JPEG;
2943                                                 ImageInfo->Thumbnail.size = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
2944                                         }
2945                                         break;
2946                         }
2947                 }
2948         } else {
2949                 if (section_index==SECTION_IFD0 || section_index==SECTION_EXIF)
2950                 switch(tag) {
2951                         case TAG_COPYRIGHT:
2952                                 /* check for "<photographer> NUL <editor> NUL" */
2953                                 if (byte_count>1 && (length=php_strnlen(value_ptr, byte_count)) > 0) {
2954                                         if (length<byte_count-1) {
2955                                                 /* When there are any characters after the first NUL */
2956                                                 ImageInfo->CopyrightPhotographer  = estrdup(value_ptr);
2957                                                 ImageInfo->CopyrightEditor        = estrndup(value_ptr+length+1, byte_count-length-1);
2958                                                 spprintf(&ImageInfo->Copyright, 0, "%s, %s", value_ptr, value_ptr+length+1);
2959                                                 /* format = TAG_FMT_UNDEFINED; this musn't be ASCII         */
2960                                                 /* but we are not supposed to change this                   */
2961                                                 /* keep in mind that image_info does not store editor value */
2962                                         } else {
2963                                                 ImageInfo->Copyright = estrndup(value_ptr, byte_count);
2964                                         }
2965                                 }
2966                                 break;
2967 
2968                         case TAG_USERCOMMENT:
2969                                 ImageInfo->UserCommentLength = exif_process_user_comment(ImageInfo, &(ImageInfo->UserComment), &(ImageInfo->UserCommentEncoding), value_ptr, byte_count TSRMLS_CC);
2970                                 break;
2971 
2972                         case TAG_XP_TITLE:
2973                         case TAG_XP_COMMENTS:
2974                         case TAG_XP_AUTHOR:
2975                         case TAG_XP_KEYWORDS:
2976                         case TAG_XP_SUBJECT:
2977                                 tmp_xp = (xp_field_type*)safe_erealloc(ImageInfo->xp_fields.list, (ImageInfo->xp_fields.count+1), sizeof(xp_field_type), 0);
2978                                 ImageInfo->sections_found |= FOUND_WINXP;
2979                                 ImageInfo->xp_fields.list = tmp_xp;
2980                                 ImageInfo->xp_fields.count++;
2981                                 exif_process_unicode(ImageInfo, &(ImageInfo->xp_fields.list[ImageInfo->xp_fields.count-1]), tag, value_ptr, byte_count TSRMLS_CC);
2982                                 break;
2983 
2984                         case TAG_FNUMBER:
2985                                 /* Simplest way of expressing aperture, so I trust it the most.
2986                                    (overwrite previously computed value if there is one) */
2987                                 ImageInfo->ApertureFNumber = (float)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
2988                                 break;
2989 
2990                         case TAG_APERTURE:
2991                         case TAG_MAX_APERTURE:
2992                                 /* More relevant info always comes earlier, so only use this field if we don't
2993                                    have appropriate aperture information yet. */
2994                                 if (ImageInfo->ApertureFNumber == 0) {
2995                                         ImageInfo->ApertureFNumber
2996                                                 = (float)exp(exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC)*log(2)*0.5);
2997                                 }
2998                                 break;
2999 
3000                         case TAG_SHUTTERSPEED:
3001                                 /* More complicated way of expressing exposure time, so only use
3002                                    this value if we don't already have it from somewhere else.
3003                                    SHUTTERSPEED comes after EXPOSURE TIME
3004                                   */
3005                                 if (ImageInfo->ExposureTime == 0) {
3006                                         ImageInfo->ExposureTime
3007                                                 = (float)(1/exp(exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC)*log(2)));
3008                                 }
3009                                 break;
3010                         case TAG_EXPOSURETIME:
3011                                 ImageInfo->ExposureTime = -1;
3012                                 break;
3013 
3014                         case TAG_COMP_IMAGE_WIDTH:
3015                                 ImageInfo->ExifImageWidth = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
3016                                 break;
3017 
3018                         case TAG_FOCALPLANE_X_RES:
3019                                 ImageInfo->FocalplaneXRes = exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
3020                                 break;
3021 
3022                         case TAG_SUBJECT_DISTANCE:
3023                                 /* Inidcates the distacne the autofocus camera is focused to.
3024                                    Tends to be less accurate as distance increases. */
3025                                 ImageInfo->Distance = (float)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
3026                                 break;
3027 
3028                         case TAG_FOCALPLANE_RESOLUTION_UNIT:
3029                                 switch((int)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC)) {
3030                                         case 1: ImageInfo->FocalplaneUnits = 25.4; break; /* inch */
3031                                         case 2:
3032                                                 /* According to the information I was using, 2 measn meters.
3033                                                    But looking at the Cannon powershot's files, inches is the only
3034                                                    sensible value. */
3035                                                 ImageInfo->FocalplaneUnits = 25.4;
3036                                                 break;
3037 
3038                                         case 3: ImageInfo->FocalplaneUnits = 10;   break;  /* centimeter */
3039                                         case 4: ImageInfo->FocalplaneUnits = 1;    break;  /* milimeter  */
3040                                         case 5: ImageInfo->FocalplaneUnits = .001; break;  /* micrometer */
3041                                 }
3042                                 break;
3043 
3044                         case TAG_SUB_IFD:
3045                                 if (format==TAG_FMT_IFD) {
3046                                         /* If this is called we are either in a TIFFs thumbnail or a JPEG where we cannot handle it */
3047                                         /* TIFF thumbnail: our data structure cannot store a thumbnail of a thumbnail */
3048                                         /* JPEG do we have the data area and what to do with it */
3049                                         exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Skip SUB IFD");
3050                                 }
3051                                 break;
3052 
3053                         case TAG_MAKE:
3054                                 ImageInfo->make = estrndup(value_ptr, byte_count);
3055                                 break;
3056                         case TAG_MODEL:
3057                                 ImageInfo->model = estrndup(value_ptr, byte_count);
3058                                 break;
3059 
3060                         case TAG_MAKER_NOTE:
3061                                 exif_process_IFD_in_MAKERNOTE(ImageInfo, value_ptr, byte_count, offset_base, IFDlength, displacement TSRMLS_CC);
3062                                 break;
3063 
3064                         case TAG_EXIF_IFD_POINTER:
3065                         case TAG_GPS_IFD_POINTER:
3066                         case TAG_INTEROP_IFD_POINTER:
3067                                 if (ReadNextIFD) {
3068                                         char *Subdir_start;
3069                                         int sub_section_index = 0;
3070                                         switch(tag) {
3071                                                 case TAG_EXIF_IFD_POINTER:
3072 #ifdef EXIF_DEBUG
3073                                                         exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Found EXIF");
3074 #endif
3075                                                         ImageInfo->sections_found |= FOUND_EXIF;
3076                                                         sub_section_index = SECTION_EXIF;
3077                                                         break;
3078                                                 case TAG_GPS_IFD_POINTER:
3079 #ifdef EXIF_DEBUG
3080                                                         exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Found GPS");
3081 #endif
3082                                                         ImageInfo->sections_found |= FOUND_GPS;
3083                                                         sub_section_index = SECTION_GPS;
3084                                                         break;
3085                                                 case TAG_INTEROP_IFD_POINTER:
3086 #ifdef EXIF_DEBUG
3087                                                         exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Found INTEROPERABILITY");
3088 #endif
3089                                                         ImageInfo->sections_found |= FOUND_INTEROP;
3090                                                         sub_section_index = SECTION_INTEROP;
3091                                                         break;
3092                                         }
3093                                         Subdir_start = offset_base + php_ifd_get32u(value_ptr, ImageInfo->motorola_intel);
3094                                         if (Subdir_start < offset_base || Subdir_start > offset_base+IFDlength) {
3095                                                 exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Illegal IFD Pointer");
3096                                                 return FALSE;
3097                                         }
3098                                         if (!exif_process_IFD_in_JPEG(ImageInfo, Subdir_start, offset_base, IFDlength, displacement, sub_section_index TSRMLS_CC)) {
3099                                                 return FALSE;
3100                                         }
3101 #ifdef EXIF_DEBUG
3102                                         exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Subsection %s done", exif_get_sectionname(sub_section_index));
3103 #endif
3104                                 }
3105                 }
3106         }
3107         exif_iif_add_tag(ImageInfo, section_index, exif_get_tagname(tag, tagname, sizeof(tagname), tag_table TSRMLS_CC), tag, format, components, value_ptr TSRMLS_CC);
3108         EFREE_IF(outside);
3109         return TRUE;
3110 }
3111 /* }}} */
3112 
3113 /* {{{ exif_process_IFD_in_JPEG
3114  * Process one of the nested IFDs directories. */
3115 static int exif_process_IFD_in_JPEG(image_info_type *ImageInfo, char *dir_start, char *offset_base, size_t IFDlength, size_t displacement, int section_index TSRMLS_DC)
3116 {
3117         int de;
3118         int NumDirEntries;
3119         int NextDirOffset;
3120 
3121 #ifdef EXIF_DEBUG
3122         exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process %s (x%04X(=%d))", exif_get_sectionname(section_index), IFDlength, IFDlength);
3123 #endif
3124 
3125         ImageInfo->sections_found |= FOUND_IFD0;
3126 
3127         NumDirEntries = php_ifd_get16u(dir_start, ImageInfo->motorola_intel);
3128 
3129         if ((dir_start+2+NumDirEntries*12) > (offset_base+IFDlength)) {
3130                 exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Illegal IFD size: x%04X + 2 + x%04X*12 = x%04X > x%04X", (int)((size_t)dir_start+2-(size_t)offset_base), NumDirEntries, (int)((size_t)dir_start+2+NumDirEntries*12-(size_t)offset_base), IFDlength);
3131                 return FALSE;
3132         }
3133 
3134         for (de=0;de<NumDirEntries;de++) {
3135                 if (!exif_process_IFD_TAG(ImageInfo, dir_start + 2 + 12 * de,
3136                                                                   offset_base, IFDlength, displacement, section_index, 1, exif_get_tag_table(section_index) TSRMLS_CC)) {
3137                         return FALSE;
3138                 }
3139         }
3140         /*
3141          * Ignore IFD2 if it purportedly exists
3142          */
3143         if (section_index == SECTION_THUMBNAIL) {
3144                 return TRUE;
3145         }
3146         /*
3147          * Hack to make it process IDF1 I hope
3148          * There are 2 IDFs, the second one holds the keys (0x0201 and 0x0202) to the thumbnail
3149          */
3150         NextDirOffset = php_ifd_get32u(dir_start+2+12*de, ImageInfo->motorola_intel);
3151         if (NextDirOffset) {
3152                 /* the next line seems false but here IFDlength means length of all IFDs */
3153                 if (offset_base + NextDirOffset < offset_base || offset_base + NextDirOffset > offset_base+IFDlength) {
3154                         exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Illegal IFD offset");
3155                         return FALSE;
3156                 }
3157                 /* That is the IFD for the first thumbnail */
3158 #ifdef EXIF_DEBUG
3159                 exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Expect next IFD to be thumbnail");
3160 #endif
3161                 if (exif_process_IFD_in_JPEG(ImageInfo, offset_base + NextDirOffset, offset_base, IFDlength, displacement, SECTION_THUMBNAIL TSRMLS_CC)) {
3162 #ifdef EXIF_DEBUG
3163                         exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail size: 0x%04X", ImageInfo->Thumbnail.size);
3164 #endif
3165                         if (ImageInfo->Thumbnail.filetype != IMAGE_FILETYPE_UNKNOWN
3166                         &&  ImageInfo->Thumbnail.size
3167                         &&  ImageInfo->Thumbnail.offset
3168                         &&  ImageInfo->read_thumbnail
3169                         ) {
3170                                 exif_thumbnail_extract(ImageInfo, offset_base, IFDlength TSRMLS_CC);
3171                         }
3172                         return TRUE;
3173                 } else {
3174                         return FALSE;
3175                 }
3176         }
3177         return TRUE;
3178 }
3179 /* }}} */
3180 
3181 /* {{{ exif_process_TIFF_in_JPEG
3182    Process a TIFF header in a JPEG file
3183 */
3184 static void exif_process_TIFF_in_JPEG(image_info_type *ImageInfo, char *CharBuf, size_t length, size_t displacement TSRMLS_DC)
3185 {
3186         unsigned exif_value_2a, offset_of_ifd;
3187 
3188         /* set the thumbnail stuff to nothing so we can test to see if they get set up */
3189         if (memcmp(CharBuf, "II", 2) == 0) {
3190                 ImageInfo->motorola_intel = 0;
3191         } else if (memcmp(CharBuf, "MM", 2) == 0) {
3192                 ImageInfo->motorola_intel = 1;
3193         } else {
3194                 exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Invalid TIFF alignment marker");
3195                 return;
3196         }
3197 
3198         /* Check the next two values for correctness. */
3199         exif_value_2a = php_ifd_get16u(CharBuf+2, ImageInfo->motorola_intel);
3200         offset_of_ifd = php_ifd_get32u(CharBuf+4, ImageInfo->motorola_intel);
3201         if ( exif_value_2a != 0x2a || offset_of_ifd < 0x08) {
3202                 exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Invalid TIFF start (1)");
3203                 return;
3204         }
3205         if (offset_of_ifd > length) {
3206                 exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Invalid IFD start");
3207                 return;
3208         }
3209 
3210         ImageInfo->sections_found |= FOUND_IFD0;
3211         /* First directory starts at offset 8. Offsets starts at 0. */
3212         exif_process_IFD_in_JPEG(ImageInfo, CharBuf+offset_of_ifd, CharBuf, length/*-14*/, displacement, SECTION_IFD0 TSRMLS_CC);
3213 
3214 #ifdef EXIF_DEBUG
3215         exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process TIFF in JPEG done");
3216 #endif
3217 
3218         /* Compute the CCD width, in milimeters. */
3219         if (ImageInfo->FocalplaneXRes != 0) {
3220                 ImageInfo->CCDWidth = (float)(ImageInfo->ExifImageWidth * ImageInfo->FocalplaneUnits / ImageInfo->FocalplaneXRes);
3221         }
3222 }
3223 /* }}} */
3224 
3225 /* {{{ exif_process_APP1
3226    Process an JPEG APP1 block marker
3227    Describes all the drivel that most digital cameras include...
3228 */
3229 static void exif_process_APP1(image_info_type *ImageInfo, char *CharBuf, size_t length, size_t displacement TSRMLS_DC)
3230 {
3231         /* Check the APP1 for Exif Identifier Code */
3232         static const uchar ExifHeader[] = {0x45, 0x78, 0x69, 0x66, 0x00, 0x00};
3233         if (length <= 8 || memcmp(CharBuf+2, ExifHeader, 6)) {
3234                 exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Incorrect APP1 Exif Identifier Code");
3235                 return;
3236         }
3237         exif_process_TIFF_in_JPEG(ImageInfo, CharBuf + 8, length - 8, displacement+8 TSRMLS_CC);
3238 #ifdef EXIF_DEBUG
3239         exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process APP1/EXIF done");
3240 #endif
3241 }
3242 /* }}} */
3243 
3244 /* {{{ exif_process_APP12
3245    Process an JPEG APP12 block marker used by OLYMPUS
3246 */
3247 static void exif_process_APP12(image_info_type *ImageInfo, char *buffer, size_t length TSRMLS_DC)
3248 {
3249         size_t l1, l2=0;
3250 
3251         if ((l1 = php_strnlen(buffer+2, length-2)) > 0) {
3252                 exif_iif_add_tag(ImageInfo, SECTION_APP12, "Company", TAG_NONE, TAG_FMT_STRING, l1, buffer+2 TSRMLS_CC);
3253                 if (length > 2+l1+1) {
3254                         l2 = php_strnlen(buffer+2+l1+1, length-2-l1-1);
3255                         exif_iif_add_tag(ImageInfo, SECTION_APP12, "Info", TAG_NONE, TAG_FMT_STRING, l2, buffer+2+l1+1 TSRMLS_CC);
3256                 }
3257         }
3258 #ifdef EXIF_DEBUG
3259         exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process section APP12 with l1=%d, l2=%d done", l1, l2);
3260 #endif
3261 }
3262 /* }}} */
3263 
3264 /* {{{ exif_scan_JPEG_header
3265  * Parse the marker stream until SOS or EOI is seen; */
3266 static int exif_scan_JPEG_header(image_info_type *ImageInfo TSRMLS_DC)
3267 {
3268         int section, sn;
3269         int marker = 0, last_marker = M_PSEUDO, comment_correction=1;
3270         unsigned int ll, lh;
3271         uchar *Data;
3272         size_t fpos, size, got, itemlen;
3273         jpeg_sof_info  sof_info;
3274 
3275         for(section=0;;section++) {
3276 #ifdef EXIF_DEBUG
3277                 fpos = php_stream_tell(ImageInfo->infile);
3278                 exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Needing section %d @ 0x%08X", ImageInfo->file.count, fpos);
3279 #endif
3280 
3281                 /* get marker byte, swallowing possible padding                           */
3282                 /* some software does not count the length bytes of COM section           */
3283                 /* one company doing so is very much envolved in JPEG... so we accept too */
3284                 if (last_marker==M_COM && comment_correction) {
3285                         comment_correction = 2;
3286                 }
3287                 do {
3288                         if ((marker = php_stream_getc(ImageInfo->infile)) == EOF) {
3289                                 EXIF_ERRLOG_CORRUPT(ImageInfo)
3290                                 return FALSE;
3291                         }
3292                         if (last_marker==M_COM && comment_correction>0) {
3293                                 if (marker!=0xFF) {
3294                                         marker = 0xff;
3295                                         comment_correction--;
3296                                 } else  {
3297                                         last_marker = M_PSEUDO; /* stop skipping 0 for M_COM */
3298                                 }
3299                         }
3300                 } while (marker == 0xff);
3301                 if (last_marker==M_COM && !comment_correction) {
3302                         exif_error_docref("exif_read_data#error_mcom" EXIFERR_CC, ImageInfo, E_NOTICE, "Image has corrupt COM section: some software set wrong length information");
3303                 }
3304                 if (last_marker==M_COM && comment_correction)
3305                         return M_EOI; /* ah illegal: char after COM section not 0xFF */
3306 
3307                 fpos = php_stream_tell(ImageInfo->infile);
3308 
3309                 if (marker == 0xff) {
3310                         /* 0xff is legal padding, but if we get that many, something's wrong. */
3311                         exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "To many padding bytes");
3312                         return FALSE;
3313                 }
3314 
3315                 /* Read the length of the section. */
3316                 if ((lh = php_stream_getc(ImageInfo->infile)) == EOF) {
3317                         EXIF_ERRLOG_CORRUPT(ImageInfo)
3318                         return FALSE;
3319                 }
3320                 if ((ll = php_stream_getc(ImageInfo->infile)) == EOF) {
3321                         EXIF_ERRLOG_CORRUPT(ImageInfo)
3322                         return FALSE;
3323                 }
3324 
3325                 itemlen = (lh << 8) | ll;
3326 
3327                 if (itemlen < 2) {
3328 #ifdef EXIF_DEBUG
3329                         exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "%s, Section length: 0x%02X%02X", EXIF_ERROR_CORRUPT, lh, ll);
3330 #else
3331                         EXIF_ERRLOG_CORRUPT(ImageInfo)
3332 #endif
3333                         return FALSE;
3334                 }
3335 
3336                 sn = exif_file_sections_add(ImageInfo, marker, itemlen+1, NULL);
3337                 Data = ImageInfo->file.list[sn].data;
3338 
3339                 /* Store first two pre-read bytes. */
3340                 Data[0] = (uchar)lh;
3341                 Data[1] = (uchar)ll;
3342 
3343                 got = php_stream_read(ImageInfo->infile, (char*)(Data+2), itemlen-2); /* Read the whole section. */
3344                 if (got != itemlen-2) {
3345                         exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Error reading from file: got=x%04X(=%d) != itemlen-2=x%04X(=%d)", got, got, itemlen-2, itemlen-2);
3346                         return FALSE;
3347                 }
3348 
3349 #ifdef EXIF_DEBUG
3350                 exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process section(x%02X=%s) @ x%04X + x%04X(=%d)", marker, exif_get_markername(marker), fpos, itemlen, itemlen);
3351 #endif
3352                 switch(marker) {
3353                         case M_SOS:   /* stop before hitting compressed data  */
3354                                 /* If reading entire image is requested, read the rest of the data. */
3355                                 if (ImageInfo->read_all) {
3356                                         /* Determine how much file is left. */
3357                                         fpos = php_stream_tell(ImageInfo->infile);
3358                                         size = ImageInfo->FileSize - fpos;
3359                                         sn = exif_file_sections_add(ImageInfo, M_PSEUDO, size, NULL);
3360                                         Data = ImageInfo->file.list[sn].data;
3361                                         got = php_stream_read(ImageInfo->infile, (char*)Data, size);
3362                                         if (got != size) {
3363                                                 EXIF_ERRLOG_FILEEOF(ImageInfo)
3364                                                 return FALSE;
3365                                         }
3366                                 }
3367                                 return TRUE;
3368 
3369                         case M_EOI:   /* in case it's a tables-only JPEG stream */
3370                                 exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "No image in jpeg!");
3371                                 return (ImageInfo->sections_found&(~FOUND_COMPUTED)) ? TRUE : FALSE;
3372 
3373                         case M_COM: /* Comment section */
3374                                 exif_process_COM(ImageInfo, (char *)Data, itemlen TSRMLS_CC);
3375                                 break;
3376 
3377                         case M_EXIF:
3378                                 if (!(ImageInfo->sections_found&FOUND_IFD0)) {
3379                                         /*ImageInfo->sections_found |= FOUND_EXIF;*/
3380                                         /* Seen files from some 'U-lead' software with Vivitar scanner
3381                                            that uses marker 31 later in the file (no clue what for!) */
3382                                         exif_process_APP1(ImageInfo, (char *)Data, itemlen, fpos TSRMLS_CC);
3383                                 }
3384                                 break;
3385 
3386                         case M_APP12:
3387                                 exif_process_APP12(ImageInfo, (char *)Data, itemlen TSRMLS_CC);
3388                                 break;
3389 
3390 
3391                         case M_SOF0:
3392                         case M_SOF1:
3393                         case M_SOF2:
3394                         case M_SOF3:
3395                         case M_SOF5:
3396                         case M_SOF6:
3397                         case M_SOF7:
3398                         case M_SOF9:
3399                         case M_SOF10:
3400                         case M_SOF11:
3401                         case M_SOF13:
3402                         case M_SOF14:
3403                         case M_SOF15:
3404                                 if ((itemlen - 2) < 6) {
3405                                         return FALSE;
3406                                 }
3407 
3408                                 exif_process_SOFn(Data, marker, &sof_info);
3409                                 ImageInfo->Width  = sof_info.width;
3410                                 ImageInfo->Height = sof_info.height;
3411                                 if (sof_info.num_components == 3) {
3412                                         ImageInfo->IsColor = 1;
3413                                 } else {
3414                                         ImageInfo->IsColor = 0;
3415                                 }
3416                                 break;
3417                         default:
3418                                 /* skip any other marker silently. */
3419                                 break;
3420                 }
3421 
3422                 /* keep track of last marker */
3423                 last_marker = marker;
3424         }
3425 #ifdef EXIF_DEBUG
3426         exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Done");
3427 #endif
3428         return TRUE;
3429 }
3430 /* }}} */
3431 
3432 /* {{{ exif_scan_thumbnail
3433  * scan JPEG in thumbnail (memory) */
3434 static int exif_scan_thumbnail(image_info_type *ImageInfo TSRMLS_DC)
3435 {
3436         uchar           c, *data = (uchar*)ImageInfo->Thumbnail.data;
3437         int             n, marker;
3438         size_t          length=2, pos=0;
3439         jpeg_sof_info   sof_info;
3440 
3441         if (!data) {
3442                 return FALSE; /* nothing to do here */
3443         }
3444         if (memcmp(data, "\xFF\xD8\xFF", 3)) {
3445                 if (!ImageInfo->Thumbnail.width && !ImageInfo->Thumbnail.height) {
3446                         exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Thumbnail is not a JPEG image");
3447                 }
3448                 return FALSE;
3449         }
3450         for (;;) {
3451                 pos += length;
3452                 if (pos>=ImageInfo->Thumbnail.size)
3453                         return FALSE;
3454                 c = data[pos++];
3455                 if (pos>=ImageInfo->Thumbnail.size)
3456                         return FALSE;
3457                 if (c != 0xFF) {
3458                         return FALSE;
3459                 }
3460                 n = 8;
3461                 while ((c = data[pos++]) == 0xFF && n--) {
3462                         if (pos+3>=ImageInfo->Thumbnail.size)
3463                                 return FALSE;
3464                         /* +3 = pos++ of next check when reaching marker + 2 bytes for length */
3465                 }
3466                 if (c == 0xFF)
3467                         return FALSE;
3468                 marker = c;
3469                 length = php_jpg_get16(data+pos);
3470                 if (pos+length>=ImageInfo->Thumbnail.size) {
3471                         return FALSE;
3472                 }
3473 #ifdef EXIF_DEBUG
3474                 exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail: process section(x%02X=%s) @ x%04X + x%04X", marker, exif_get_markername(marker), pos, length);
3475 #endif
3476                 switch (marker) {
3477                         case M_SOF0:
3478                         case M_SOF1:
3479                         case M_SOF2:
3480                         case M_SOF3:
3481                         case M_SOF5:
3482                         case M_SOF6:
3483                         case M_SOF7:
3484                         case M_SOF9:
3485                         case M_SOF10:
3486                         case M_SOF11:
3487                         case M_SOF13:
3488                         case M_SOF14:
3489                         case M_SOF15:
3490                                 /* handle SOFn block */
3491                                 exif_process_SOFn(data+pos, marker, &sof_info);
3492                                 ImageInfo->Thumbnail.height   = sof_info.height;
3493                                 ImageInfo->Thumbnail.width    = sof_info.width;
3494 #ifdef EXIF_DEBUG
3495                                 exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail: size: %d * %d", sof_info.width, sof_info.height);
3496 #endif
3497                                 return TRUE;
3498 
3499                         case M_SOS:
3500                         case M_EOI:
3501                                 exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Could not compute size of thumbnail");
3502                                 return FALSE;
3503                                 break;
3504 
3505                         default:
3506                                 /* just skip */
3507                                 break;
3508                 }
3509         }
3510 
3511         exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Could not compute size of thumbnail");
3512         return FALSE;
3513 }
3514 /* }}} */
3515 
3516 /* {{{ exif_process_IFD_in_TIFF
3517  * Parse the TIFF header; */
3518 static int exif_process_IFD_in_TIFF(image_info_type *ImageInfo, size_t dir_offset, int section_index TSRMLS_DC)
3519 {
3520         int i, sn, num_entries, sub_section_index = 0;
3521         unsigned char *dir_entry;
3522         char tagname[64];
3523         size_t ifd_size, dir_size, entry_offset, next_offset, entry_length, entry_value=0, fgot;
3524         int entry_tag , entry_type;
3525         tag_table_type tag_table = exif_get_tag_table(section_index);
3526 
3527         if (ImageInfo->ifd_nesting_level > MAX_IFD_NESTING_LEVEL) {
3528                 return FALSE;
3529         }
3530 
3531         if (ImageInfo->FileSize >= dir_offset+2) {
3532                 sn = exif_file_sections_add(ImageInfo, M_PSEUDO, 2, NULL);
3533 #ifdef EXIF_DEBUG
3534                 exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Read from TIFF: filesize(x%04X), IFD dir(x%04X + x%04X)", ImageInfo->FileSize, dir_offset, 2);
3535 #endif
3536                 php_stream_seek(ImageInfo->infile, dir_offset, SEEK_SET); /* we do not know the order of sections */
3537                 php_stream_read(ImageInfo->infile, (char*)ImageInfo->file.list[sn].data, 2);
3538                 num_entries = php_ifd_get16u(ImageInfo->file.list[sn].data, ImageInfo->motorola_intel);
3539                 dir_size = 2/*num dir entries*/ +12/*length of entry*/*num_entries +4/* offset to next ifd (points to thumbnail or NULL)*/;
3540                 if (ImageInfo->FileSize >= dir_offset+dir_size) {
3541 #ifdef EXIF_DEBUG
3542                         exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Read from TIFF: filesize(x%04X), IFD dir(x%04X + x%04X), IFD entries(%d)", ImageInfo->FileSize, dir_offset+2, dir_size-2, num_entries);
3543 #endif
3544                         if (exif_file_sections_realloc(ImageInfo, sn, dir_size TSRMLS_CC)) {
3545                                 return FALSE;
3546                         }
3547                         php_stream_read(ImageInfo->infile, (char*)(ImageInfo->file.list[sn].data+2), dir_size-2);
3548                         /*exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Dump: %s", exif_char_dump(ImageInfo->file.list[sn].data, dir_size, 0));*/
3549                         next_offset = php_ifd_get32u(ImageInfo->file.list[sn].data + dir_size - 4, ImageInfo->motorola_intel);
3550 #ifdef EXIF_DEBUG
3551                         exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Read from TIFF done, next offset x%04X", next_offset);
3552 #endif
3553                         /* now we have the directory we can look how long it should be */
3554                         ifd_size = dir_size;
3555                         for(i=0;i<num_entries;i++) {
3556                                 dir_entry        = ImageInfo->file.list[sn].data+2+i*12;
3557                                 entry_tag    = php_ifd_get16u(dir_entry+0, ImageInfo->motorola_intel);
3558                                 entry_type   = php_ifd_get16u(dir_entry+2, ImageInfo->motorola_intel);
3559                                 if (entry_type > NUM_FORMATS) {
3560                                         exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Read from TIFF: tag(0x%04X,%12s): Illegal format code 0x%04X, switching to BYTE", entry_tag, exif_get_tagname(entry_tag, tagname, -12, tag_table TSRMLS_CC), entry_type);
3561                                         /* Since this is repeated in exif_process_IFD_TAG make it a notice here */
3562                                         /* and make it a warning in the exif_process_IFD_TAG which is called    */
3563                                         /* elsewhere. */
3564                                         entry_type = TAG_FMT_BYTE;
3565                                         /*The next line would break the image on writeback: */
3566                                         /* php_ifd_set16u(dir_entry+2, entry_type, ImageInfo->motorola_intel);*/
3567                                 }
3568                                 entry_length = php_ifd_get32u(dir_entry+4, ImageInfo->motorola_intel) * php_tiff_bytes_per_format[entry_type];
3569                                 if (entry_length <= 4) {
3570                                         switch(entry_type) {
3571                                                 case TAG_FMT_USHORT:
3572                                                         entry_value  = php_ifd_get16u(dir_entry+8, ImageInfo->motorola_intel);
3573                                                         break;
3574                                                 case TAG_FMT_SSHORT:
3575                                                         entry_value  = php_ifd_get16s(dir_entry+8, ImageInfo->motorola_intel);
3576                                                         break;
3577                                                 case TAG_FMT_ULONG:
3578                                                         entry_value  = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel);
3579                                                         break;
3580                                                 case TAG_FMT_SLONG:
3581                                                         entry_value  = php_ifd_get32s(dir_entry+8, ImageInfo->motorola_intel);
3582                                                         break;
3583                                         }
3584                                         switch(entry_tag) {
3585                                                 case TAG_IMAGEWIDTH:
3586                                                 case TAG_COMP_IMAGE_WIDTH:
3587                                                         ImageInfo->Width  = entry_value;
3588                                                         break;
3589                                                 case TAG_IMAGEHEIGHT:
3590                                                 case TAG_COMP_IMAGE_HEIGHT:
3591                                                         ImageInfo->Height = entry_value;
3592                                                         break;
3593                                                 case TAG_PHOTOMETRIC_INTERPRETATION:
3594                                                         switch (entry_value) {
3595                                                                 case PMI_BLACK_IS_ZERO:
3596                                                                 case PMI_WHITE_IS_ZERO:
3597                                                                 case PMI_TRANSPARENCY_MASK:
3598                                                                         ImageInfo->IsColor = 0;
3599                                                                         break;
3600                                                                 case PMI_RGB:
3601                                                                 case PMI_PALETTE_COLOR:
3602                                                                 case PMI_SEPARATED:
3603                                                                 case PMI_YCBCR:
3604                                                                 case PMI_CIELAB:
3605                                                                         ImageInfo->IsColor = 1;
3606                                                                         break;
3607                                                         }
3608                                                         break;
3609                                         }
3610                                 } else {
3611                                         entry_offset = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel);
3612                                         /* if entry needs expading ifd cache and entry is at end of current ifd cache. */
3613                                         /* otherwise there may be huge holes between two entries */
3614                                         if (entry_offset + entry_length > dir_offset + ifd_size
3615                                           && entry_offset == dir_offset + ifd_size) {
3616                                                 ifd_size = entry_offset + entry_length - dir_offset;
3617 #ifdef EXIF_DEBUG
3618                                                 exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Resize struct: x%04X + x%04X - x%04X = x%04X", entry_offset, entry_length, dir_offset, ifd_size);
3619 #endif
3620                                         }
3621                                 }
3622                         }
3623                         if (ImageInfo->FileSize >= dir_offset + ImageInfo->file.list[sn].size) {
3624                                 if (ifd_size > dir_size) {
3625                                         if (dir_offset + ifd_size > ImageInfo->FileSize) {
3626                                                 exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Error in TIFF: filesize(x%04X) less than size of IFD(x%04X + x%04X)", ImageInfo->FileSize, dir_offset, ifd_size);
3627                                                 return FALSE;
3628                                         }
3629                                         if (exif_file_sections_realloc(ImageInfo, sn, ifd_size TSRMLS_CC)) {
3630                                                 return FALSE;
3631                                         }
3632                                         /* read values not stored in directory itself */
3633 #ifdef EXIF_DEBUG
3634                                         exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Read from TIFF: filesize(x%04X), IFD(x%04X + x%04X)", ImageInfo->FileSize, dir_offset, ifd_size);
3635 #endif
3636                                         php_stream_read(ImageInfo->infile, (char*)(ImageInfo->file.list[sn].data+dir_size), ifd_size-dir_size);
3637 #ifdef EXIF_DEBUG
3638                                         exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Read from TIFF, done");
3639 #endif
3640                                 }
3641                                 /* now process the tags */
3642                                 for(i=0;i<num_entries;i++) {
3643                                         dir_entry        = ImageInfo->file.list[sn].data+2+i*12;
3644                                         entry_tag    = php_ifd_get16u(dir_entry+0, ImageInfo->motorola_intel);
3645                                         entry_type   = php_ifd_get16u(dir_entry+2, ImageInfo->motorola_intel);
3646                                         /*entry_length = php_ifd_get32u(dir_entry+4, ImageInfo->motorola_intel);*/
3647                                         if (entry_tag == TAG_EXIF_IFD_POINTER ||
3648                                                 entry_tag == TAG_INTEROP_IFD_POINTER ||
3649                                                 entry_tag == TAG_GPS_IFD_POINTER ||
3650                                                 entry_tag == TAG_SUB_IFD
3651                                         ) {
3652                                                 switch(entry_tag) {
3653                                                         case TAG_EXIF_IFD_POINTER:
3654                                                                 ImageInfo->sections_found |= FOUND_EXIF;
3655                                                                 sub_section_index = SECTION_EXIF;
3656                                                                 break;
3657                                                         case TAG_GPS_IFD_POINTER:
3658                                                                 ImageInfo->sections_found |= FOUND_GPS;
3659                                                                 sub_section_index = SECTION_GPS;
3660                                                                 break;
3661                                                         case TAG_INTEROP_IFD_POINTER:
3662                                                                 ImageInfo->sections_found |= FOUND_INTEROP;
3663                                                                 sub_section_index = SECTION_INTEROP;
3664                                                                 break;
3665                                                         case TAG_SUB_IFD:
3666                                                                 ImageInfo->sections_found |= FOUND_THUMBNAIL;
3667                                                                 sub_section_index = SECTION_THUMBNAIL;
3668                                                                 break;
3669                                                 }
3670                                                 entry_offset = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel);
3671 #ifdef EXIF_DEBUG
3672                                                 exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Next IFD: %s @x%04X", exif_get_sectionname(sub_section_index), entry_offset);
3673 #endif
3674                                                 ImageInfo->ifd_nesting_level++;
3675                                                 exif_process_IFD_in_TIFF(ImageInfo, entry_offset, sub_section_index TSRMLS_CC);
3676                                                 if (section_index!=SECTION_THUMBNAIL && entry_tag==TAG_SUB_IFD) {
3677                                                         if (ImageInfo->Thumbnail.filetype != IMAGE_FILETYPE_UNKNOWN
3678                                                         &&  ImageInfo->Thumbnail.size
3679                                                         &&  ImageInfo->Thumbnail.offset
3680                                                         &&  ImageInfo->read_thumbnail
3681                                                         ) {
3682 #ifdef EXIF_DEBUG
3683                                                                 exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "%s THUMBNAIL @0x%04X + 0x%04X", ImageInfo->Thumbnail.data ? "Ignore" : "Read", ImageInfo->Thumbnail.offset, ImageInfo->Thumbnail.size);
3684 #endif
3685                                                                 if (!ImageInfo->Thumbnail.data) {
3686                                                                         ImageInfo->Thumbnail.data = safe_emalloc(ImageInfo->Thumbnail.size, 1, 0);
3687                                                                         php_stream_seek(ImageInfo->infile, ImageInfo->Thumbnail.offset, SEEK_SET);
3688                                                                         fgot = php_stream_read(ImageInfo->infile, ImageInfo->Thumbnail.data, ImageInfo->Thumbnail.size);
3689                                                                         if (fgot < ImageInfo->Thumbnail.size) {
3690                                                                                 EXIF_ERRLOG_THUMBEOF(ImageInfo)
3691                                                                         }
3692                                                                         exif_thumbnail_build(ImageInfo TSRMLS_CC);
3693                                                                 }
3694                                                         }
3695                                                 }
3696 #ifdef EXIF_DEBUG
3697                                                 exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Next IFD: %s done", exif_get_sectionname(sub_section_index));
3698 #endif
3699                                         } else {
3700                                                 if (!exif_process_IFD_TAG(ImageInfo, (char*)dir_entry,
3701                                                                                                   (char*)(ImageInfo->file.list[sn].data-dir_offset),
3702                                                                                                   ifd_size, 0, section_index, 0, tag_table TSRMLS_CC)) {
3703                                                         return FALSE;
3704                                                 }
3705                                         }
3706                                 }
3707                                 /* If we had a thumbnail in a SUB_IFD we have ANOTHER image in NEXT IFD */
3708                                 if (next_offset && section_index != SECTION_THUMBNAIL) {
3709                                         /* this should be a thumbnail IFD */
3710                                         /* the thumbnail itself is stored at Tag=StripOffsets */
3711 #ifdef EXIF_DEBUG
3712                                         exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Read next IFD (THUMBNAIL) at x%04X", next_offset);
3713 #endif
3714                                         ImageInfo->ifd_nesting_level++;
3715                                         exif_process_IFD_in_TIFF(ImageInfo, next_offset, SECTION_THUMBNAIL TSRMLS_CC);
3716 #ifdef EXIF_DEBUG
3717                                         exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "%s THUMBNAIL @0x%04X + 0x%04X", ImageInfo->Thumbnail.data ? "Ignore" : "Read", ImageInfo->Thumbnail.offset, ImageInfo->Thumbnail.size);
3718 #endif
3719                                         if (!ImageInfo->Thumbnail.data && ImageInfo->Thumbnail.offset && ImageInfo->Thumbnail.size && ImageInfo->read_thumbnail) {
3720                                                 ImageInfo->Thumbnail.data = safe_emalloc(ImageInfo->Thumbnail.size, 1, 0);
3721                                                 php_stream_seek(ImageInfo->infile, ImageInfo->Thumbnail.offset, SEEK_SET);
3722                                                 fgot = php_stream_read(ImageInfo->infile, ImageInfo->Thumbnail.data, ImageInfo->Thumbnail.size);
3723                                                 if (fgot < ImageInfo->Thumbnail.size) {
3724                                                         EXIF_ERRLOG_THUMBEOF(ImageInfo)
3725                                                 }
3726                                                 exif_thumbnail_build(ImageInfo TSRMLS_CC);
3727                                         }
3728 #ifdef EXIF_DEBUG
3729                                         exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Read next IFD (THUMBNAIL) done");
3730 #endif
3731                                 }
3732                                 return TRUE;
3733                         } else {
3734                                 exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Error in TIFF: filesize(x%04X) less than size of IFD(x%04X)", ImageInfo->FileSize, dir_offset+ImageInfo->file.list[sn].size);
3735                                 return FALSE;
3736                         }
3737                 } else {
3738                         exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Error in TIFF: filesize(x%04X) less than size of IFD dir(x%04X)", ImageInfo->FileSize, dir_offset+dir_size);
3739                         return FALSE;
3740                 }
3741         } else {
3742                 exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Error in TIFF: filesize(x%04X) less than start of IFD dir(x%04X)", ImageInfo->FileSize, dir_offset+2);
3743                 return FALSE;
3744         }
3745 }
3746 /* }}} */
3747 
3748 /* {{{ exif_scan_FILE_header
3749  * Parse the marker stream until SOS or EOI is seen; */
3750 static int exif_scan_FILE_header(image_info_type *ImageInfo TSRMLS_DC)
3751 {
3752         unsigned char file_header[8];
3753         int ret = FALSE;
3754 
3755         ImageInfo->FileType = IMAGE_FILETYPE_UNKNOWN;
3756 
3757         if (ImageInfo->FileSize >= 2) {
3758                 php_stream_seek(ImageInfo->infile, 0, SEEK_SET);
3759                 if (php_stream_read(ImageInfo->infile, (char*)file_header, 2) != 2) {
3760                         return FALSE;
3761                 }
3762                 if ((file_header[0]==0xff) && (file_header[1]==M_SOI)) {
3763                         ImageInfo->FileType = IMAGE_FILETYPE_JPEG;
3764                         if (exif_scan_JPEG_header(ImageInfo TSRMLS_CC)) {
3765                                 ret = TRUE;
3766                         } else {
3767                                 exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Invalid JPEG file");
3768                         }
3769                 } else if (ImageInfo->FileSize >= 8) {
3770                         if (php_stream_read(ImageInfo->infile, (char*)(file_header+2), 6) != 6) {
3771                                 return FALSE;
3772                         }
3773                         if (!memcmp(file_header, "II\x2A\x00", 4)) {
3774                                 ImageInfo->FileType = IMAGE_FILETYPE_TIFF_II;
3775                                 ImageInfo->motorola_intel = 0;
3776 #ifdef EXIF_DEBUG
3777                                 exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "File has TIFF/II format");
3778 #endif
3779                                 ImageInfo->sections_found |= FOUND_IFD0;
3780                                 if (exif_process_IFD_in_TIFF(ImageInfo,
3781                                                                                          php_ifd_get32u(file_header + 4, ImageInfo->motorola_intel),
3782                                                                                          SECTION_IFD0 TSRMLS_CC)) {
3783                                         ret = TRUE;
3784                                 } else {
3785                                         exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Invalid TIFF file");
3786                                 }
3787                         } else if (!memcmp(file_header, "MM\x00\x2a", 4)) {
3788                                 ImageInfo->FileType = IMAGE_FILETYPE_TIFF_MM;
3789                                 ImageInfo->motorola_intel = 1;
3790 #ifdef EXIF_DEBUG
3791                                 exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "File has TIFF/MM format");
3792 #endif
3793                                 ImageInfo->sections_found |= FOUND_IFD0;
3794                                 if (exif_process_IFD_in_TIFF(ImageInfo,
3795                                                                                          php_ifd_get32u(file_header + 4, ImageInfo->motorola_intel),
3796                                                                                          SECTION_IFD0 TSRMLS_CC)) {
3797                                         ret = TRUE;
3798                                 } else {
3799                                         exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Invalid TIFF file");
3800                                 }
3801                         } else {
3802                                 exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "File not supported");
3803                                 return FALSE;
3804                         }
3805                 }
3806         } else {
3807                 exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "File too small (%d)", ImageInfo->FileSize);
3808         }
3809         return ret;
3810 }
3811 /* }}} */
3812 
3813 /* {{{ exif_discard_imageinfo
3814    Discard data scanned by exif_read_file.
3815 */
3816 static int exif_discard_imageinfo(image_info_type *ImageInfo)
3817 {
3818         int i;
3819 
3820         EFREE_IF(ImageInfo->FileName);
3821         EFREE_IF(ImageInfo->UserComment);
3822         EFREE_IF(ImageInfo->UserCommentEncoding);
3823         EFREE_IF(ImageInfo->Copyright);
3824         EFREE_IF(ImageInfo->CopyrightPhotographer);
3825         EFREE_IF(ImageInfo->CopyrightEditor);
3826         EFREE_IF(ImageInfo->Thumbnail.data);
3827         EFREE_IF(ImageInfo->encode_unicode);
3828         EFREE_IF(ImageInfo->decode_unicode_be);
3829         EFREE_IF(ImageInfo->decode_unicode_le);
3830         EFREE_IF(ImageInfo->encode_jis);
3831         EFREE_IF(ImageInfo->decode_jis_be);
3832         EFREE_IF(ImageInfo->decode_jis_le);
3833         EFREE_IF(ImageInfo->make);
3834         EFREE_IF(ImageInfo->model);
3835         for (i=0; i<ImageInfo->xp_fields.count; i++) {
3836                 EFREE_IF(ImageInfo->xp_fields.list[i].value);
3837         }
3838         EFREE_IF(ImageInfo->xp_fields.list);
3839         for (i=0; i<SECTION_COUNT; i++) {
3840                 exif_iif_free(ImageInfo, i);
3841         }
3842         exif_file_sections_free(ImageInfo);
3843         memset(ImageInfo, 0, sizeof(*ImageInfo));
3844         return TRUE;
3845 }
3846 /* }}} */
3847 
3848 /* {{{ exif_read_file
3849  */
3850 static int exif_read_file(image_info_type *ImageInfo, char *FileName, int read_thumbnail, int read_all TSRMLS_DC)
3851 {
3852         int ret;
3853         struct stat st;
3854 
3855         /* Start with an empty image information structure. */
3856         memset(ImageInfo, 0, sizeof(*ImageInfo));
3857 
3858         ImageInfo->motorola_intel = -1; /* flag as unknown */
3859 
3860         ImageInfo->infile = php_stream_open_wrapper(FileName, "rb", STREAM_MUST_SEEK|IGNORE_PATH, NULL);
3861         if (!ImageInfo->infile) {
3862                 exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Unable to open file");
3863                 return FALSE;
3864         }
3865 
3866         if (php_stream_is(ImageInfo->infile, PHP_STREAM_IS_STDIO)) {
3867                 if (VCWD_STAT(FileName, &st) >= 0) {
3868                         if ((st.st_mode & S_IFMT) != S_IFREG) {
3869                                 exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Not a file");
3870                                 php_stream_close(ImageInfo->infile);
3871                                 return FALSE;
3872                         }
3873 
3874                         /* Store file date/time. */
3875                         ImageInfo->FileDateTime = st.st_mtime;
3876                         ImageInfo->FileSize = st.st_size;
3877                         /*exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Opened stream is file: %d", ImageInfo->FileSize);*/
3878                 }
3879         } else {
3880                 if (!ImageInfo->FileSize) {
3881                         php_stream_seek(ImageInfo->infile, 0, SEEK_END);
3882                         ImageInfo->FileSize = php_stream_tell(ImageInfo->infile);
3883                         php_stream_seek(ImageInfo->infile, 0, SEEK_SET);
3884                 }
3885         }
3886 
3887         php_basename(FileName, strlen(FileName), NULL, 0, &(ImageInfo->FileName), NULL TSRMLS_CC);
3888         ImageInfo->read_thumbnail = read_thumbnail;
3889         ImageInfo->read_all = read_all;
3890         ImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_UNKNOWN;
3891 
3892         ImageInfo->encode_unicode    = safe_estrdup(EXIF_G(encode_unicode));
3893         ImageInfo->decode_unicode_be = safe_estrdup(EXIF_G(decode_unicode_be));
3894         ImageInfo->decode_unicode_le = safe_estrdup(EXIF_G(decode_unicode_le));
3895         ImageInfo->encode_jis        = safe_estrdup(EXIF_G(encode_jis));
3896         ImageInfo->decode_jis_be     = safe_estrdup(EXIF_G(decode_jis_be));
3897         ImageInfo->decode_jis_le     = safe_estrdup(EXIF_G(decode_jis_le));
3898 
3899 
3900         ImageInfo->ifd_nesting_level = 0;
3901 
3902         /* Scan the JPEG headers. */
3903         ret = exif_scan_FILE_header(ImageInfo TSRMLS_CC);
3904 
3905         php_stream_close(ImageInfo->infile);
3906         return ret;
3907 }
3908 /* }}} */
3909 
3910 /* {{{ proto array exif_read_data(string filename [, sections_needed [, sub_arrays[, read_thumbnail]]])
3911    Reads header data from the JPEG/TIFF image filename and optionally reads the internal thumbnails */
3912 PHP_FUNCTION(exif_read_data)
3913 {
3914         char *p_name, *p_sections_needed = NULL;
3915         int p_name_len, p_sections_needed_len = 0;
3916         zend_bool sub_arrays=0, read_thumbnail=0, read_all=0;
3917 
3918         int i, ret, sections_needed=0;
3919         image_info_type ImageInfo;
3920         char tmp[64], *sections_str, *s;
3921 
3922         if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p|sbb", &p_name, &p_name_len, &p_sections_needed, &p_sections_needed_len, &sub_arrays, &read_thumbnail) == FAILURE) {
3923                 return;
3924         }
3925 
3926         memset(&ImageInfo, 0, sizeof(ImageInfo));
3927 
3928         if (p_sections_needed) {
3929                 spprintf(&sections_str, 0, ",%s,", p_sections_needed);
3930                 /* sections_str DOES start with , and SPACES are NOT allowed in names */
3931                 s = sections_str;
3932                 while (*++s) {
3933                         if (*s == ' ') {
3934                                 *s = ',';
3935                         }
3936                 }
3937 
3938                 for (i = 0; i < SECTION_COUNT; i++) {
3939                         snprintf(tmp, sizeof(tmp), ",%s,", exif_get_sectionname(i));
3940                         if (strstr(sections_str, tmp)) {
3941                                 sections_needed |= 1<<i;
3942                         }
3943                 }
3944                 EFREE_IF(sections_str);
3945                 /* now see what we need */
3946 #ifdef EXIF_DEBUG
3947                 sections_str = exif_get_sectionlist(sections_needed TSRMLS_CC);
3948                 if (!sections_str) {
3949                         RETURN_FALSE;
3950                 }
3951                 exif_error_docref(NULL EXIFERR_CC, &ImageInfo, E_NOTICE, "Sections needed: %s", sections_str[0] ? sections_str : "None");
3952                 EFREE_IF(sections_str);
3953 #endif
3954         }
3955 
3956         ret = exif_read_file(&ImageInfo, p_name, read_thumbnail, read_all TSRMLS_CC);
3957         sections_str = exif_get_sectionlist(ImageInfo.sections_found TSRMLS_CC);
3958 
3959 #ifdef EXIF_DEBUG
3960         if (sections_str)
3961                 exif_error_docref(NULL EXIFERR_CC, &ImageInfo, E_NOTICE, "Sections found: %s", sections_str[0] ? sections_str : "None");
3962 #endif
3963 
3964         ImageInfo.sections_found |= FOUND_COMPUTED|FOUND_FILE;/* do not inform about in debug*/
3965 
3966         if (ret == FALSE || (sections_needed && !(sections_needed&ImageInfo.sections_found))) {
3967                 /* array_init must be checked at last! otherwise the array must be freed if a later test fails. */
3968                 exif_discard_imageinfo(&ImageInfo);
3969                 EFREE_IF(sections_str);
3970                 RETURN_FALSE;
3971         }
3972 
3973         array_init(return_value);
3974 
3975 #ifdef EXIF_DEBUG
3976         exif_error_docref(NULL EXIFERR_CC, &ImageInfo, E_NOTICE, "Generate section FILE");
3977 #endif
3978 
3979         /* now we can add our information */
3980         exif_iif_add_str(&ImageInfo, SECTION_FILE, "FileName",      ImageInfo.FileName TSRMLS_CC);
3981         exif_iif_add_int(&ImageInfo, SECTION_FILE, "FileDateTime",  ImageInfo.FileDateTime TSRMLS_CC);
3982         exif_iif_add_int(&ImageInfo, SECTION_FILE, "FileSize",      ImageInfo.FileSize TSRMLS_CC);
3983         exif_iif_add_int(&ImageInfo, SECTION_FILE, "FileType",      ImageInfo.FileType TSRMLS_CC);
3984         exif_iif_add_str(&ImageInfo, SECTION_FILE, "MimeType",      (char*)php_image_type_to_mime_type(ImageInfo.FileType) TSRMLS_CC);
3985         exif_iif_add_str(&ImageInfo, SECTION_FILE, "SectionsFound", sections_str ? sections_str : "NONE" TSRMLS_CC);
3986 
3987 #ifdef EXIF_DEBUG
3988         exif_error_docref(NULL EXIFERR_CC, &ImageInfo, E_NOTICE, "Generate section COMPUTED");
3989 #endif
3990 
3991         if (ImageInfo.Width>0 &&  ImageInfo.Height>0) {
3992                 exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "html"    TSRMLS_CC, "width=\"%d\" height=\"%d\"", ImageInfo.Width, ImageInfo.Height);
3993                 exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "Height", ImageInfo.Height TSRMLS_CC);
3994                 exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "Width",  ImageInfo.Width TSRMLS_CC);
3995         }
3996         exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "IsColor", ImageInfo.IsColor TSRMLS_CC);
3997         if (ImageInfo.motorola_intel != -1) {
3998                 exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "ByteOrderMotorola", ImageInfo.motorola_intel TSRMLS_CC);
3999         }
4000         if (ImageInfo.FocalLength) {
4001                 exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "FocalLength" TSRMLS_CC, "%4.1Fmm", ImageInfo.FocalLength);
4002                 if(ImageInfo.CCDWidth) {
4003                         exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "35mmFocalLength" TSRMLS_CC, "%dmm", (int)(ImageInfo.FocalLength/ImageInfo.CCDWidth*35+0.5));
4004                 }
4005         }
4006         if(ImageInfo.CCDWidth) {
4007                 exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "CCDWidth" TSRMLS_CC, "%dmm", (int)ImageInfo.CCDWidth);
4008         }
4009         if(ImageInfo.ExposureTime>0) {
4010                 if(ImageInfo.ExposureTime <= 0.5) {
4011                         exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "ExposureTime" TSRMLS_CC, "%0.3F s (1/%d)", ImageInfo.ExposureTime, (int)(0.5 + 1/ImageInfo.ExposureTime));
4012                 } else {
4013                         exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "ExposureTime" TSRMLS_CC, "%0.3F s", ImageInfo.ExposureTime);
4014                 }
4015         }
4016         if(ImageInfo.ApertureFNumber) {
4017                 exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "ApertureFNumber" TSRMLS_CC, "f/%.1F", ImageInfo.ApertureFNumber);
4018         }
4019         if(ImageInfo.Distance) {
4020                 if(ImageInfo.Distance<0) {
4021                         exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "FocusDistance", "Infinite" TSRMLS_CC);
4022                 } else {
4023                         exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "FocusDistance" TSRMLS_CC, "%0.2Fm", ImageInfo.Distance);
4024                 }
4025         }
4026         if (ImageInfo.UserComment) {
4027                 exif_iif_add_buffer(&ImageInfo, SECTION_COMPUTED, "UserComment", ImageInfo.UserCommentLength, ImageInfo.UserComment TSRMLS_CC);
4028                 if (ImageInfo.UserCommentEncoding && strlen(ImageInfo.UserCommentEncoding)) {
4029                         exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "UserCommentEncoding", ImageInfo.UserCommentEncoding TSRMLS_CC);
4030                 }
4031         }
4032 
4033         exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "Copyright",              ImageInfo.Copyright TSRMLS_CC);
4034         exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "Copyright.Photographer", ImageInfo.CopyrightPhotographer TSRMLS_CC);
4035         exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "Copyright.Editor",       ImageInfo.CopyrightEditor TSRMLS_CC);
4036 
4037         for (i=0; i<ImageInfo.xp_fields.count; i++) {
4038                 exif_iif_add_str(&ImageInfo, SECTION_WINXP, exif_get_tagname(ImageInfo.xp_fields.list[i].tag, NULL, 0, exif_get_tag_table(SECTION_WINXP) TSRMLS_CC), ImageInfo.xp_fields.list[i].value TSRMLS_CC);
4039         }
4040         if (ImageInfo.Thumbnail.size) {
4041                 if (read_thumbnail) {
4042                         /* not exif_iif_add_str : this is a buffer */
4043                         exif_iif_add_tag(&ImageInfo, SECTION_THUMBNAIL, "THUMBNAIL", TAG_NONE, TAG_FMT_UNDEFINED, ImageInfo.Thumbnail.size, ImageInfo.Thumbnail.data TSRMLS_CC);
4044                 }
4045                 if (!ImageInfo.Thumbnail.width || !ImageInfo.Thumbnail.height) {
4046                         /* try to evaluate if thumbnail data is present */
4047                         exif_scan_thumbnail(&ImageInfo TSRMLS_CC);
4048                 }
4049                 exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "Thumbnail.FileType", ImageInfo.Thumbnail.filetype TSRMLS_CC);
4050                 exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "Thumbnail.MimeType", (char*)php_image_type_to_mime_type(ImageInfo.Thumbnail.filetype) TSRMLS_CC);
4051         }
4052         if (ImageInfo.Thumbnail.width && ImageInfo.Thumbnail.height) {
4053                 exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "Thumbnail.Height", ImageInfo.Thumbnail.height TSRMLS_CC);
4054                 exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "Thumbnail.Width",  ImageInfo.Thumbnail.width TSRMLS_CC);
4055         }
4056         EFREE_IF(sections_str);
4057 
4058 #ifdef EXIF_DEBUG
4059         exif_error_docref(NULL EXIFERR_CC, &ImageInfo, E_NOTICE, "Adding image infos");
4060 #endif
4061 
4062         add_assoc_image_info(return_value, sub_arrays, &ImageInfo, SECTION_FILE       TSRMLS_CC);
4063         add_assoc_image_info(return_value, 1,          &ImageInfo, SECTION_COMPUTED   TSRMLS_CC);
4064         add_assoc_image_info(return_value, sub_arrays, &ImageInfo, SECTION_ANY_TAG    TSRMLS_CC);
4065         add_assoc_image_info(return_value, sub_arrays, &ImageInfo, SECTION_IFD0       TSRMLS_CC);
4066         add_assoc_image_info(return_value, 1,          &ImageInfo, SECTION_THUMBNAIL  TSRMLS_CC);
4067         add_assoc_image_info(return_value, 1,          &ImageInfo, SECTION_COMMENT    TSRMLS_CC);
4068         add_assoc_image_info(return_value, sub_arrays, &ImageInfo, SECTION_EXIF       TSRMLS_CC);
4069         add_assoc_image_info(return_value, sub_arrays, &ImageInfo, SECTION_GPS        TSRMLS_CC);
4070         add_assoc_image_info(return_value, sub_arrays, &ImageInfo, SECTION_INTEROP    TSRMLS_CC);
4071         add_assoc_image_info(return_value, sub_arrays, &ImageInfo, SECTION_FPIX       TSRMLS_CC);
4072         add_assoc_image_info(return_value, sub_arrays, &ImageInfo, SECTION_APP12      TSRMLS_CC);
4073         add_assoc_image_info(return_value, sub_arrays, &ImageInfo, SECTION_WINXP      TSRMLS_CC);
4074         add_assoc_image_info(return_value, sub_arrays, &ImageInfo, SECTION_MAKERNOTE  TSRMLS_CC);
4075 
4076 #ifdef EXIF_DEBUG
4077         exif_error_docref(NULL EXIFERR_CC, &ImageInfo, E_NOTICE, "Discarding info");
4078 #endif
4079 
4080         exif_discard_imageinfo(&ImageInfo);
4081 
4082 #ifdef EXIF_DEBUG
4083         php_error_docref1(NULL TSRMLS_CC, Z_STRVAL_PP(p_name), E_NOTICE, "done");
4084 #endif
4085 }
4086 /* }}} */
4087 
4088 /* {{{ proto string exif_thumbnail(string filename [, &width, &height [, &imagetype]])
4089    Reads the embedded thumbnail */
4090 PHP_FUNCTION(exif_thumbnail)
4091 {
4092         zval *p_width = 0, *p_height = 0, *p_imagetype = 0;
4093         char *p_name;
4094         int p_name_len, ret, arg_c = ZEND_NUM_ARGS();
4095         image_info_type ImageInfo;
4096 
4097         memset(&ImageInfo, 0, sizeof(ImageInfo));
4098 
4099         if (arg_c!=1 && arg_c!=3 && arg_c!=4) {
4100                 WRONG_PARAM_COUNT;
4101         }
4102 
4103         if (zend_parse_parameters(arg_c TSRMLS_CC, "p|z/z/z/", &p_name, &p_name_len, &p_width, &p_height, &p_imagetype) == FAILURE) {
4104                 return;
4105         }
4106 
4107         ret = exif_read_file(&ImageInfo, p_name, 1, 0 TSRMLS_CC);
4108         if (ret==FALSE) {
4109                 exif_discard_imageinfo(&ImageInfo);
4110                 RETURN_FALSE;
4111         }
4112 
4113 #ifdef EXIF_DEBUG
4114         exif_error_docref(NULL EXIFERR_CC, &ImageInfo, E_NOTICE, "Thumbnail data %d %d %d, %d x %d", ImageInfo.Thumbnail.data, ImageInfo.Thumbnail.size, ImageInfo.Thumbnail.filetype, ImageInfo.Thumbnail.width, ImageInfo.Thumbnail.height);
4115 #endif
4116         if (!ImageInfo.Thumbnail.data || !ImageInfo.Thumbnail.size) {
4117                 exif_discard_imageinfo(&ImageInfo);
4118                 RETURN_FALSE;
4119         }
4120 
4121 #ifdef EXIF_DEBUG
4122         exif_error_docref(NULL EXIFERR_CC, &ImageInfo, E_NOTICE, "Returning thumbnail(%d)", ImageInfo.Thumbnail.size);
4123 #endif
4124 
4125         ZVAL_STRINGL(return_value, ImageInfo.Thumbnail.data, ImageInfo.Thumbnail.size, 1);
4126         if (arg_c >= 3) {
4127                 if (!ImageInfo.Thumbnail.width || !ImageInfo.Thumbnail.height) {
4128                         exif_scan_thumbnail(&ImageInfo TSRMLS_CC);
4129                 }
4130                 zval_dtor(p_width);
4131                 zval_dtor(p_height);
4132                 ZVAL_LONG(p_width,  ImageInfo.Thumbnail.width);
4133                 ZVAL_LONG(p_height, ImageInfo.Thumbnail.height);
4134         }
4135         if (arg_c >= 4) {
4136                 zval_dtor(p_imagetype);
4137                 ZVAL_LONG(p_imagetype, ImageInfo.Thumbnail.filetype);
4138         }
4139 
4140 #ifdef EXIF_DEBUG
4141         exif_error_docref(NULL EXIFERR_CC, &ImageInfo, E_NOTICE, "Discarding info");
4142 #endif
4143 
4144         exif_discard_imageinfo(&ImageInfo);
4145 
4146 #ifdef EXIF_DEBUG
4147         php_error_docref1(NULL TSRMLS_CC, p_name, E_NOTICE, "Done");
4148 #endif
4149 }
4150 /* }}} */
4151 
4152 /* {{{ proto int exif_imagetype(string imagefile)
4153    Get the type of an image */
4154 PHP_FUNCTION(exif_imagetype)
4155 {
4156         char *imagefile;
4157         int imagefile_len;
4158         php_stream * stream;
4159         int itype = 0;
4160 
4161         if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &imagefile, &imagefile_len) == FAILURE) {
4162                 return;
4163         }
4164 
4165         stream = php_stream_open_wrapper(imagefile, "rb", IGNORE_PATH|REPORT_ERRORS, NULL);
4166 
4167         if (stream == NULL) {
4168                 RETURN_FALSE;
4169         }
4170 
4171         itype = php_getimagetype(stream, NULL TSRMLS_CC);
4172 
4173         php_stream_close(stream);
4174 
4175         if (itype == IMAGE_FILETYPE_UNKNOWN) {
4176                 RETURN_FALSE;
4177         } else {
4178                 ZVAL_LONG(return_value, itype);
4179         }
4180 }
4181 /* }}} */
4182 
4183 #endif
4184 
4185 /*
4186  * Local variables:
4187  * tab-width: 4
4188  * c-basic-offset: 4
4189  * End:
4190  * vim600: sw=4 ts=4 tw=78 fdm=marker
4191  * vim<600: sw=4 ts=4 tw=78
4192  */

/* [<][>][^][v][top][bottom][index][help] */