erso /protected/extensions/tiny_mce/assets/plugins/images/connector/php/exifReader.php

Language PHP Lines 1704
MD5 Hash 9cf98776969b7fad3ff869f4c9f7cd60 Estimated Cost $29,519 (why?)
Repository https://bitbucket.org/graaaf/erso.git View Raw File View Project SPDX
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
<?php
/**
 * PHP Class to read EXIF information
 * that most of the digital camera produce
 *
 * This class is based on jhead (in C) by Matthias Wandel
 *
 * Vinay Yadav (vinayRas) < vinay@sanisoft.com >
 * http://www.sanisoft.com/phpexifrw/
 *
 * For more information on EXIF
 * http://www.exif.org/
 *
 * Features:
 *   - Read Exif Information
 *   - Extract and display emdedded thumbnails
 *
 *  Tested With

        - Sony
            - Cybershot (Sony)
            - DSC-D700
            - PowerShotA5
			- Sony P71
        - SANYO Electric Co.,Ltd
            - SR6
            - SX113
        - OLYMPUS OPTICAL CO.,LTD
            - C960Z, D460Z
			- C3000Z
        - Canon
            PowerShot A40 (Canon)
            Canon DIGITAL IXUS
			Canon 300D
        - RICOH
            - Caplio RR30
            - RDC-5300
        - NIKON
            - D100 (NIKON CORPORATION)
            - E5700 (NIKON)
            - E950
        - CASIO QV-8000SX
        - KODAK
            - DC290 Zoom Digital Camera (V01.00) [Eastman Kodak Company]
            - DC210 Zoom (V05.00) [Eastman Kodak Company]
            - KODAK DC240 ZOOM DIGITAL CAMERA
        - FujiFilm
            DX10
            FinePix40i
            MX-1700ZOOM
 *
 *
 */

/** * Start Of Frame N */
define("M_SOF0",0xC0);
/** * N indicates which compression process */
define("M_SOF1",0xC1);
/** * Only SOF0-SOF2 are now in common use */
define("M_SOF2",0xC2);
/** *  */
define("M_SOF3",0xC3);
/** * NB: codes C4 and CC are NOT SOF markers */
define("M_SOF5",0xC5);
/** *  */
define("M_SOF6",0xC6);
/** *  */
define("M_SOF7",0xC7);
/** *  */
define("M_SOF9",0xC9);
/** *  */
define("M_SOF10",0xCA);
/** *  */
define("M_SOF11",0xCB);
/** *  */
define("M_SOF13",0xCD);
/** *  */
define("M_SOF14",0xCE);
/** *  */
define("M_SOF15",0xCF);
/** * Start Of Image (beginning of datastream) */
define("M_SOI",0xD8);
/** * End Of Image (end of datastream) */
define("M_EOI",0xD9);
/** * Start Of Scan (begins compressed data) */
define("M_SOS",0xDA);
/** * Jfif marker */
define("M_JFIF",0xE0);
/** * Exif marker */
define("M_EXIF",0xE1);

define("M_EXIF_EXT",0xE2); // 226 - Exif Extended Data
define("M_QUANTA",0xDB); // 219 - Quantisation Table Definition
define("M_HUFF",0xC4); // (DEC=196) - Huffman Table Definition
/** * Image Title -- */
define("M_COM",0xFE);

define("NUM_FORMATS","12");

/** * Tag Data Format */
define("FMT_BYTE","1");
/** * ASCII */
define("FMT_STRING","2");
/** * Short */
define("FMT_USHORT","3");
/** * Long */
define("FMT_ULONG","4");
/** * Rational */
define("FMT_URATIONAL","5");
/** * Byte */
define("FMT_SBYTE","6");
/** * Undefined */
define("FMT_UNDEFINED","7");
/** * Short */
define("FMT_SSHORT","8");
/** * Long */
define("FMT_SLONG","9");
/** * Rational */
define("FMT_SRATIONAL","10");
/** * Single */
define("FMT_SINGLE","11");
/** * Double */
define("FMT_DOUBLE","12");

/** * Exif IFD */
define("TAG_EXIF_OFFSET","0x8769");
/** * Interoperability tag */
define("TAG_INTEROP_OFFSET","0xa005");
/** * Image input equipment manufacturer */
define("TAG_MAKE","0x010F");
/** * Image input equipment model */
define("TAG_MODEL","0x0110");
/** * Orientation of image */
define("TAG_ORIENTATION","0x0112");
/** * Exposure Time */
define("TAG_EXPOSURETIME","0x829A");
/** * F Number */
define("TAG_FNUMBER","0x829D");
/** * Shutter Speed */
define("TAG_SHUTTERSPEED","0x9201");
/** * Aperture */
define("TAG_APERTURE","0x9202");
/** * Aperture */
define("TAG_MAXAPERTURE","0x9205");
/** * Lens Focal Length */
define("TAG_FOCALLENGTH","0x920A");
/** * The date and time when the original image data was generated. */
define("TAG_DATETIME_ORIGINAL","0x9003");
/** * User Comments */
define("TAG_USERCOMMENT","0x9286");
/** * subject Location */
define("TAG_SUBJECT_DISTANCE","0x9206");
/** * Flash */
define("TAG_FLASH","0x9209");
/** * Focal Plane X Resolution */
define("TAG_FOCALPLANEXRES","0xa20E");
/** * Focal Plane Resolution Units */
define("TAG_FOCALPLANEUNITS","0xa210");
/** * Image Width */
define("TAG_EXIF_IMAGEWIDTH","0xA002");
/** * Image Height */
define("TAG_EXIF_IMAGELENGTH","0xA003");
/** * Exposure Bias */
define("TAG_EXPOSURE_BIAS","0x9204");
/** * Light Source */
define("TAG_WHITEBALANCE","0x9208");
/** * Metering Mode */
define("TAG_METERING_MODE","0x9207");
/** * Exposure Program */
define("TAG_EXPOSURE_PROGRAM","0x8822");
/** * ISO Equivalent Speed Rating */
define("TAG_ISO_EQUIVALENT","0x8827");
/** * Compressed Bits Per Pixel */
define("TAG_COMPRESSION_LEVEL","0x9102");
/** * Thumbnail Start Offset */
define("TAG_THUMBNAIL_OFFSET","0x0201");
/** * Thumbnail Length */
define("TAG_THUMBNAIL_LENGTH","0x0202");
/** * Image Marker */
define("PSEUDO_IMAGE_MARKER",0x123);
/** * Max Image Title Length */
define("MAX_COMMENT",2000);

define("TAG_ARTIST","0x013B");
define("TAG_COPYRIGHT","0x8298");

//--------------------------------

define("TAG_IMAGE_WD","0x0100"); // image width
define("TAG_IMAGE_HT","0x0101"); // image height
define("TAG_IMAGE_BPS","0x0102"); // Bits Per sample

define("TAG_IMAGE_PHOTO_INT","0x0106"); // photometricinterpretation
define("TAG_IMAGE_SOFFSET","0x0111"); // stripoffsets

define("TAG_IMAGE_SPP","0x0115"); // Samples per pixel - 277
define("TAG_IMAGE_RPS","0x0116"); // RowsPerStrip - 278
define("TAG_IMAGE_SBC","0x0117"); // StripByteCounts - 279

define("TAG_IMAGE_P_CONFIG","0x011C"); // Planar Configuration - 284

define("TAG_IMAGE_DESC","0x010E"); // image title
define("TAG_X_RESOLUTION","0x011A"); // Image resolution in width direction
define("TAG_Y_RESOLUTION","0x011B"); // Image resolution in height direction
define("TAG_RESOLUTION_UNIT","0x0128"); // Unit of X and Y resolution
define("TAG_SOFTWARE","0x0131"); // Software used
define("TAG_FILE_MODDATE","0x0132"); // DateTime File change date and time
define("TAG_YCBCR_POSITIONING","0x0213"); // Y and C positioning
define("TAG_EXIF_VERSION","0x9000"); // Exif version
define("TAG_DATE_TIME_DIGITIZED","0x9004"); // Date and time of digital data
define("TAG_COMPONENT_CONFIG","0x9101"); // Component configuration
define("TAG_MAKER_NOTE","0x927C");
define("TAG_SUB_SEC_TIME","0x9290");
define("TAG_SUB_SEC_TIME_ORIG","0x9291");
define("TAG_SUB_SEC_TIME_DIGITIZED","0x9292");
define("TAG_FLASHPIX_VER","0xA000"); //FlashPixVersion
define("TAG_COLOR_SPACE","0xA001"); //ColorSpace
define("TAG_RELATED_SOUND_FILE","0xA004"); //Related audio file

define("TAG_GPS_LATITUDE_REF","0x0001"); //
define("TAG_GPS_LATITUDE","0x0002"); //

define("TAG_GPS_LONGITUDE_REF","0x0003"); //
define("TAG_GPS_LONGITUDE","0x0004"); //

define("TAG_GPS_TrackRef","0x000E"); //
define("TAG_GPS_GPSTrack","0x000F"); //
define("TAG_GPS_GPSImgDirectionRef","0x0010"); //
define("TAG_GPS_GPSImgDirection","0x0011"); //
define("TAG_GPS_GPSMapDatum","0x0012"); //
define("TAG_GPS_GPSDestLatitudeRef","0x0013"); //
define("TAG_GPS_GPSDestLatitude","0x0014"); //
define("TAG_GPS_GPSDestLongitudeRef","0x0015"); //
define("TAG_GPS_GPSDestLongitude","0x0016"); //
define("TAG_GPS_GPSDestBearingRef","0x0017"); //
define("TAG_GPS_GPSDestBearing","0x0018"); //
define("TAG_GPS_GPSDestDistanceRef","0x0019"); //
define("TAG_GPS_GPSDestDistance","0x001A"); //
define("TAG_GPS_GPSProcessingMethod","0x001B"); //
define("TAG_GPS_GPSAreaInformation","0x001C"); //
define("TAG_GPS_GPSDateStamp","0x001D"); //
define("TAG_GPS_GPSDifferential","0x001E"); //

define("TAG_AUDIO_IMA_ADPCM_DESC","0x0028"); //  IMA-ADPCM Audio File Description Example - 40
define("TAG_AUDIO_MU_LAW_DESC","0x0032"); //  µ-Law Audio File Description Sample - 50

define("TAG_AUDIO_MU_LAW","0x0086"); // (This File µ-LAW Sample) - 134


define("TAG_EXPOSURE_INDEX","0xA215"); // Exposure index

define("TAG_SENSING_METHOD","0xA217"); // SensingMethod

define("TAG_SOUCE_TYPE","0xA300"); // FileSource
define("TAG_SCENE_TYPE","0xA301"); // SceneType

define("TAG_CFA_PATTERN","0xA302"); // CFA Pattern

/** Tags in EXIF 2.2 Only */
define("TAG_COMPRESS_SCHEME","0x0103"); //
define("TAG_CUSTOM_RENDERED","0xA401"); //  CustomRendered
define("TAG_EXPOSURE_MODE","0xA402"); // Exposure mode      ExposureMode
define("TAG_WHITE_BALANCE","0xA403"); // White balance      WhiteBalance
define("TAG_DIGITAL_ZOOM_RATIO","0xA404"); // Digital zoom ratio      DigitalZoomRatio
define("TAG_FLENGTH_IN35MM","0xA405"); // Focal length in 35 mm film      FocalLengthIn35mmFilm
define("TAG_SCREEN_CAP_TYPE","0xA406"); // Scene capture type      SceneCaptureType
define("TAG_GAIN_CONTROL","0xA407"); //Gain control
define("TAG_CONTRAST","0xA408"); // Contrast
define("TAG_SATURATION","0xA409"); // Saturation
define("TAG_SHARPNESS","0xA40A"); // Sharpness
define("TAG_DEVICE_SETTING_DESC","0xA40B"); // SDevice settings description      DeviceSettingDescription
define("TAG_DIST_RANGE","0xA40C"); //Subject distance range SubjectDistanceRange

define("TAG_FOCALPLANE_YRESOL","0xA20F");; //FocalPlaneYResolution
define("TAG_BRIGHTNESS","0x9203");; //Brightness
//--------------------------------
/** error Description  */
/**
  1 - File does not exists!
  2 -
  3 - Filename not provided

  10 - too many padding bytes
  11 - "invalid marker"
  12 - Premature end of file?


  51 - "Illegal subdirectory link"
  52 - "NOT EXIF FORMAT"
  53 - "Invalid Exif alignment marker.\n"
  54 - "Invalid Exif start (1)"

*/


/**
 * PHP Class to read, write and transfer EXIF information
 * that most of the digital camera produces
 * Currenty it can only read JPEG file.
 */
 /**
 * @author Vinay Yadav (vinayRas) < vinay@sanisoft.com >
 *
 * @todo Writing exif information to the file.
 * @todo Add EXIF audio reading methods (I think it exists!)
 * @todo Support of additional tags.
 * @todo Handling Unicode character in UserComment tag of EXif Information.
 *
 * @version 0.5
 * @licence http://opensource.org/licenses/lgpl-license.php GNU LGPL
 */
class phpExifReader {

    /***
    * Array containg all Exif and JPEG image attributes
    * into regular expressions for themselves.
    * $ImageInfo[TAG] = TAG_VALUE;
    *
    * @var       array
    * @access    private
    *
    */
    var $ImageInfo = array();

    var $MotorolaOrder = 0;
    var $ExifImageWidth = 0; //
    var $FocalplaneXRes = 0; //
    var $FocalplaneUnits = 0; //
    var $sections = array();
    var $currSection = 0;  /** Stores total number fo Sections */

    var $BytesPerFormat = array(0,1,1,2,4,8,1,1,2,4,8,4,8);

    var $ReadMode = array(
                            "READ_EXIF" => 1,
                            "READ_IMAGE" => 2,
                            "READ_ALL" => 3
                        );

    var $ImageReadMode = 3; /** related to $RealMode arrays values */
    var $file =  "";     /** JPEG file to parse for EXIF data */
    var $newFile = 1;   /** flag to check if the current file has been parsed or not. */

    var $thumbnail = ""; /* Name of thumbnail */
    var $thumbnailURL = ""; /* */

    var $exifSection = -1;   // market the exif section index oout of all sections

    var $errno = 0;
    var $errstr = "";

    var $debug = false;

    // Caching ralated variables
    var $caching = false; /* Should cacheing of image thumnails be allowed? */
    var $cacheDir = ""; /* Checkout constructor for default path. */

    /**
     * Constructor
     * @param string File name to be parsed.
     *
     */
    function phpExifReader($file = "") {
      $this->timeStart = $this->getmicrotime();
      if(!empty($file)) {
        $this->file = $file;
      }

      /**
      * Initialize some variables. Avoid lots of errors with fulll error_reporting
      */
      $this->ExifImageLength       = 0;
      $this->ImageInfo['h']["resolutionUnit"] = 0;

      $this->ImageInfo[TAG_MAXAPERTURE] = 0;
      $this->ImageInfo[TAG_ISO_EQUIVALENT] = 0;
      $this->ImageInfo[TAG_ORIENTATION] = 0;

      $this->ThumbnailSize = 0;

      if($this->caching) {
        $this->cacheDir = dirname(__FILE__)."/.cache_thumbs";

        /**
        * If Cache directory does not exists then attempt to create it.
        */
        if(!is_dir($this->cacheDir)) {
             mkdir($this->cacheDir);
        }

          // Prepare the ame of thumbnail
          if(is_dir($this->cacheDir)) {
            $this->thumbnail = $this->cacheDir."/".basename($this->file);
            $this->thumbnailURL = ".cache_thumbs/".basename($this->file);
          }
      }

      /** check if file exists! */
      if(!file_exists($this->file)) {
         $this->errno = 1;
         $this->errstr = "File '".$this->file."' does not exists!";
      }
      $this->currSection = 0;

      $this->processFile();
    }

    /**
     * Show Debugging information
     *
     * @param   string     Debugging message to display
     * @param   int   Type of error (0 - Warning, 1 - Error)
     * @return    void
     *
     */
    function debug($str,$TYPE = 0,$file="",$line=0) {
       if($this->debug) {
        echo "<br>[$file:$line:".($this->getDiffTime())."]$str";
        flush();
        if($TYPE == 1) {
           exit;
        }
       }
    }

    /**
     * Processes the whole file.
     *
     */
    function processFile() {
        /** dont reparse the whole file. */
        if(!$this->newFile) return true;
        
        if(!file_exists($this->file)) {
            echo "<br>Error: File ".($this->file)."does not exists!";
            exit;
        }

        $this->debug("Stating Processing of ".$this->newFile,0,__FILE__,__LINE__);

        $i = 0; $exitAll = 0;
        /** Open the JPEG in binary safe reading mode */
        $fp = fopen($this->file,"rb");

        $this->ImageInfo["h"]["FileName"] = $this->file;
        $this->ImageInfo["h"]["FileSize"] = filesize($this->file); /** Size of the File */
        $this->ImageInfo["h"]["FileDateTime"] = filectime($this->file); /** File node change time */

        /** check whether jped image or not */
        $a = fgetc($fp);
        if (ord($a) != 0xff || ord(fgetc($fp)) != M_SOI){
                $this->debug("Not a JPEG FILE",1);
                $this->errorno = 1;
                $this->errorstr = "File '".$this->file."' is not a JPEG File!";
        }
        $tmpTestLevel = 0;
        /** Examines each byte one-by-one */
        while(!feof($fp)) {
            $data = array();
                for ($a=0;$a<7;$a++){
                        $marker = fgetc($fp);
                        if (ord($marker) != 0xff) break;
                        if ($a >= 6){
                                $this->errno = 10;
                                $this->errstr = "too many padding bytes!";
                                $this->debug($this->errstr,1);
                                return false;
                        }
                }

                if (ord($marker) == 0xff){
                    // 0xff is legal padding, but if we get that many, something's wrong.
                    $this->errno = 10;
                    $this->errstr = "too many padding bytes!";
                    $this->debug($this->errstr,1);
                }

        $marker = ord($marker);
        $this->sections[$this->currSection]["type"] = $marker;

        // Read the length of the section.
        $lh = ord(fgetc($fp));
        $ll = ord(fgetc($fp));

        $itemlen = ($lh << 8) | $ll;

        if ($itemlen < 2){
                $this->errno = 11;
                $this->errstr = "invalid marker";
                $this->debug($this->errstr,1);
        }
        $this->sections[$this->currSection]["size"] = $itemlen;

        $tmpDataArr = array();  /** Temporary Array */

        $tmpStr = fread($fp,$itemlen-2);
        /*
        $tmpDataArr[] = chr($lh);
        $tmpDataArr[] = chr($ll);

        $chars = preg_split('//', $tmpStr, -1, PREG_SPLIT_NO_EMPTY);
        $tmpDataArr = array_merge($tmpDataArr,$chars);

        $data = $tmpDataArr;
        */
        $data = chr($lh).chr($ll).$tmpStr;

        //$this->sections[$this->currSection]["data"] = $data;

        $this->debug("<hr><h1>".$this->currSection.":</h1>");
        //print_r($data);
        $this->debug("<hr>");

        //if(count($data) != $itemlen) {
        if(strlen($data) != $itemlen) {
            $this->errno = 12;
            $this->errstr = "Premature end of file?";
            $this->debug($this->errstr,1);
        }

        $this->currSection++; /** */

        switch($marker) {
                case M_SOS:
                    $this->debug("<br>Found '".M_SOS."' Section, Prcessing it... <br>");;
                        // If reading entire image is requested, read the rest of the data.
                        if ($this->ImageReadMode & $this->ReadMode["READ_IMAGE"]){
                        // Determine how much file is left.
                                $cp = ftell($fp);
                                fseek($fp,0, SEEK_END);
                                $ep = ftell($fp);
                                fseek($fp, $cp, SEEK_SET);

                        $size = $ep-$cp;
                        $got = fread($fp, $size);

                        $this->sections[$this->currSection]["data"] = $got;
                        $this->sections[$this->currSection]["size"] = $size;
                        $this->sections[$this->currSection]["type"] = PSEUDO_IMAGE_MARKER;
                        $this->currSection++;
                        $HaveAll = 1;
                        $exitAll =1;
                        }
                        $this->debug("<br>'".M_SOS."' Section, PROCESSED<br>");
                    break;
                case M_COM: // Comment section
                        $this->debug("<br>Found '".M_COM."'(Comment) Section, Processing<br>");
                        $this->process_COM($data, $itemlen);
                        $this->debug("<br>'".M_COM."'(Comment) Section, PROCESSED<br>");

                        $tmpTestLevel++;
                    break;
                case M_SOI:
                        $this->debug(" <br> === START OF IMAGE =====<br>");
                break;
                case M_EOI:
                        $this->debug(" <br>=== END OF IMAGE =====<br> ");
                break;
                case M_JFIF:
                        // Regular jpegs always have this tag, exif images have the exif
                        // marker instead, althogh ACDsee will write images with both markers.
                        // this program will re-create this marker on absence of exif marker.
                        // hence no need to keep the copy from the file.
                        //echo " <br> === M_JFIF =====<br>";
                        $this->sections[--$this->currSection]["data"] = "";
                        break;
                case M_EXIF:
                        // Seen files from some 'U-lead' software with Vivitar scanner
                        // that uses marker 31 for non exif stuff.  Thus make sure
                        // it says 'Exif' in the section before treating it as exif.
                        $this->debug("<br>Found '".M_EXIF."'(Exif) Section, Proccessing<br>");
                        $this->exifSection = $this->currSection-1;
                        if (($this->ImageReadMode & $this->ReadMode["READ_EXIF"]) && ($data[2].$data[3].$data[4].$data[5]) == "Exif"){
                                $this->process_EXIF($data, $itemlen);
                        }else{
                                // Discard this section.
                                $this->sections[--$this->currSection]["data"] = "";
                        }
                        $this->debug("<br>'".M_EXIF."'(Exif) Section, PROCESSED<br>");
                        $tmpTestLevel++;
                break;
                case M_SOF0:
                case M_SOF1:
                case M_SOF2:
                case M_SOF3:
                case M_SOF5:
                case M_SOF6:
                case M_SOF7:
                case M_SOF9:
                case M_SOF10:
                case M_SOF11:
                case M_SOF13:
                case M_SOF14:
                case M_SOF15:
                        $this->debug("<br>Found M_SOFn Section, Processing<br>");
                        $this->process_SOFn($data,$marker);
                        $this->debug("<br>M_SOFn Section, PROCESSED<br>");
                break;
				case M_EXIF_EXT: // 226 - Exif Extended Data
				    $this->debug("<br><b>Found 'Exif Extended Data' Section, Processing</b><br>-------------------------------<br>");
                    $this->process_EXT_EXIF($data, $itemlen);
					$this->debug("<br>--------------------------PROCESSED<br>");
					break;

				case M_QUANTA: // 219 - Quantisation Table Definition
				    $this->debug("<br><b>Found 'Quantisation Table Definition' Section, Processing</b><br>-------------------------------<br>");
					$this->debug("<br>--------------------------PROCESSED<br>");
					break;

				case M_HUFF: // Huffman Table
				    $this->debug("<br><b>Found 'Huffman Table' Section, Processing</b><br>-------------------------------<br>");
					$this->debug("<br>--------------------------PROCESSED<br>");
					break;

                default:
                        $this->debug("DEFAULT: Jpeg section marker 0x$marker x size $itemlen\n");
        }
        $i++;
        if($exitAll == 1)  break;
            //if($tmpTestLevel == 2)  break;
        }
        fclose($fp);
        $this->newFile = 0;
    }

    /**
     * Changing / Assiging new file
     * @param   string    JPEG file to process
     *
     */
    function assign($file) {

      if(!empty($file)) {
        $this->file = $file;
      }

      /** check for existance of file! */
      if(!file_exists($this->file)) {
         $this->errorno = 1;
         $this->errorstr = "File '".$this->file."' does not exists!";
      }
      $this->newFile = 1;
    }

    /**
     * Process SOFn section of Image
     * @param  array    An array containing whole section.
     * @param   hex  Marker to specify the type of section.
     *
     */
    function process_SOFn($data,$marker) {
        $data_precision = 0;
        $num_components = 0;

        $data_precision = ord($data[2]);

        if($this->debug) {
          print("Image Dimension Calculation:");
          print("((ord($data[3]) << 8) | ord($data[4]));");
        }
        $this->ImageInfo["h"]["Height"] = ((ord($data[3]) << 8) | ord($data[4]));
        $this->ImageInfo["h"]["Width"] = ((ord($data[5]) << 8) | ord($data[6]));

        $num_components = ord($data[7]);

        if ($num_components == 3){
            $this->ImageInfo["h"]["IsColor"] = 1;
        }else{
            $this->ImageInfo["h"]["IsColor"] = 0;
        }

        $this->ImageInfo["h"]["Process"] = $marker;
        $this->debug("JPEG image is ".$this->ImageInfo["h"]["Width"]." * ".$this->ImageInfo["h"]["Height"].", $num_components color components, $data_precision bits per sample\n");
    }

    /**
     * Process Comments
     * @param   array    Section data
     * @param   int  Length of the section
     *
     */
    function process_COM($data,$length) {
        if ($length > MAX_COMMENT) $length = MAX_COMMENT;
            /** Truncate if it won't fit in our structure. */

        $nch = 0; $Comment = "";
        for ($a=2;$a<$length;$a++){
            $ch = $data[$a];
            if ($ch == '\r' && $data[$a+1] == '\n') continue; // Remove cr followed by lf.

            $Comment .= $ch;
        }
        //$this->ImageInfo[M_COM] = $Comment;
        $this->ImageInfo["h"]["imageComment"] = $this->string_format($Comment);
        $this->debug("COM marker comment: $Comment\n");
    }
    /**
     * Process one of the nested EXIF directories.
     * @param   string        All directory information
     * @param   string     whole Section
     * @param   int  Length of exif section
     *
    */
    function ProcessExifDir($DirStart, $OffsetBase, $ExifLength) {

        $NumDirEntries = 0;
        $ValuePtr = array();

        $NumDirEntries = $this->Get16u($DirStart[0],$DirStart[1]);


        $this->debug("<br>Directory with $NumDirEntries entries\n");

        for ($de=0;$de<$NumDirEntries;$de++){
            //$DirEntry = array_slice($DirStart,2+12*$de);
            $DirEntry = substr($DirStart,2+12*$de);

            $Tag = $this->Get16u($DirEntry[0],$DirEntry[1]);
            $Format = $this->Get16u($DirEntry[2],$DirEntry[3]);
            $Components = $this->Get32u($DirEntry[4],$DirEntry[5],$DirEntry[6],$DirEntry[7]);

            /**
            if ((Format-1) >= NUM_FORMATS) {
                // (-1) catches illegal zero case as unsigned underflows to positive large.
                ErrNonfatal("Illegal number format %d for tag %04x", Format, Tag);
                continue;
            }
            */

            $ByteCount = $Components * $this->BytesPerFormat[$Format];

            if ($ByteCount > 4){
                $OffsetVal = $this->Get32u($DirEntry[8],$DirEntry[9],$DirEntry[10],$DirEntry[11]);
                if ($OffsetVal+$ByteCount > $ExifLength){
                    $this->debug("Illegal value pointer($OffsetVal) for tag $Tag",1);
                }
                //$ValuePtr = array_slice($OffsetBase,$OffsetVal);
                $ValuePtr = substr($OffsetBase,$OffsetVal);
            } else {
                //$ValuePtr = array_slice($DirEntry,8);
                $ValuePtr = substr($DirEntry,8);
            }

            switch($Tag){

                case TAG_MAKE:
                    $this->ImageInfo["h"]["make"] = $this->string_format(substr($ValuePtr,0,$ByteCount));
                    break;

                case TAG_MODEL:
                    $this->ImageInfo["h"]["model"] = $this->string_format(substr($ValuePtr,0,$ByteCount));
                    break;

                case TAG_DATETIME_ORIGINAL:
                    $this->ImageInfo[TAG_DATETIME_ORIGINAL] =  $this->string_format(substr($ValuePtr,0,$ByteCount));
                    $this->ImageInfo["h"]["DateTime"]  = $this->string_format(substr($ValuePtr,0,$ByteCount));
                    break;

                case TAG_USERCOMMENT:
                    // Olympus has this padded with trailing spaces.  Remove these first.
                    for ($a=$ByteCount;;){
                        $a--;
                        if ($ValuePtr[$a] == ' '){
                            //$ValuePtr[$a] = '\0';
                        } else {
                            break;
                        }
                        if ($a == 0) break;
                    }

                    // Copy the comment
                    if (($ValuePtr[0].$ValuePtr[1].$ValuePtr[2].$ValuePtr[3].$ValuePtr[4]) == "ASCII"){
                        for ($a=5;$a<10;$a++){
                            $c = $ValuePtr[$a];
                            if ($c != '\0' && $c != ' '){
                                $tmp = substr($ValuePtr,0,$ByteCount);
                                    break;
                            }
                        }
                    } else if (($ValuePtr[0].$ValuePtr[1].$ValuePtr[2].$ValuePtr[3].$ValuePtr[4].$ValuePtr[5].$ValuePtr[6]) == "Unicode"){
                        $tmp = substr($ValuePtr,0,$ByteCount);
                        //  * Handle Unicode characters here...
                    } else {
                        //$this->ImageInfo[TAG_USERCOMMENT] = implode("",array_slice($ValuePtr,0,$ByteCount));
                        $tmp = substr($ValuePtr,0,$ByteCount);
                    }
                    $this->ImageInfo['h']["exifComment"] = $this->string_format($tmp);
                    break;

				case TAG_ARTIST:
                    $this->ImageInfo['h']["artist"] = $this->string_format(substr($ValuePtr,0,$ByteCount));
					break;

				case TAG_COPYRIGHT:
                    $this->ImageInfo['h']["copyright"] = htmlentities(substr($ValuePtr,0,$ByteCount));
					break;

                case TAG_FNUMBER:
                    // Simplest way of expressing aperture, so I trust it the most.
                    // (overwrite previously computd value if there is one)
                    $tmp = $this->ConvertAnyFormat(substr($ValuePtr,0), $Format);
                    $this->ImageInfo['h']["fnumber"] = sprintf("f/%3.1f",(double)$tmp[0]);
                    break;

                case TAG_APERTURE:
                case TAG_MAXAPERTURE:
                    // More relevant info always comes earlier, so only use this field if we don't
                    // have appropriate aperture information yet.
                    if (!isset($this->ImageInfo['h']["aperture"])){
                        $tmpArr =  $this->ConvertAnyFormat($ValuePtr, $Format);
                        $this->ImageInfo['h']["aperture"] = exp($tmpArr[0]*log(2)*0.5);
                    }
                    break;

                case TAG_FOCALLENGTH:
                    // Nice digital cameras actually save the focal length as a function
                    // of how farthey are zoomed in.
                    $tmp = $this->ConvertAnyFormat($ValuePtr, $Format);
                    $this->ImageInfo['h']["focalLength"] = sprintf("%4.2f (%d/%d)",(double)$tmp[0],$tmp[1][0],$tmp[1][1]);
                    if (isset($this->ImageInfo['h']["CCDWidth"])){
                        $this->ImageInfo['h']["focalLength"] .= sprintf("(35mm equivalent: %dmm)",(int)($tmp[0]/$this->ImageInfo['h']["CCDWidth"]*36 + 0.5));
                    }
                    break;

                case TAG_SUBJECT_DISTANCE:
                    // Inidcates the distacne the autofocus camera is focused to.
                    // Tends to be less accurate as distance increases.
                    //$this->ImageInfo["h"]["Distance"] =  $this->ConvertAnyFormat($ValuePtr, $Format);
                    $tmp = $this->ConvertAnyFormat($ValuePtr, $Format);
                    $this->ImageInfo['h']["Distance"] = sprintf("%4.2f (%d/%d)",(double)$tmp[0],$tmp[1][0],$tmp[1][1]);
                    if ($this->ImageInfo['h']["Distance"] < 0){
                            $this->ImageInfo['h']["focusDistance"] = "Infinite";
                    } else {
                            $this->ImageInfo['h']["focusDistance"] = sprintf("%4.2fm",(double)$this->ImageInfo['h']["Distance"]);
                    }


                    break;

                case TAG_EXPOSURETIME:
                    // Simplest way of expressing exposure time, so I trust it most.
                    // (overwrite previously computd value if there is one)
                    $tmp = $this->ConvertAnyFormat($ValuePtr, $Format);
                    $this->ImageInfo['h']["exposureTime"] = sprintf("%6.3f s (%d/%d)",(double)$tmp[0],$tmp[1][0],$tmp[1][1]);
                    if ($tmp[0] <= 0.5){
                            $this->ImageInfo['h']["exposureTime"] .= sprintf(" (1/%d)",(int)(0.5 + 1/$tmp[0]));
                    }
                    break;

                case TAG_SHUTTERSPEED:
                    // More complicated way of expressing exposure time, so only use
                    // this value if we don't already have it from somewhere else.
                    if ($this->ImageInfo[TAG_EXPOSURETIME] == 0){
                        $sp = $this->ConvertAnyFormat($ValuePtr, $Format);
                        $this->ImageInfo[TAG_SHUTTERSPEED] = (1/exp($sp[0]*log(2)));
                    }
                    break;

                case TAG_FLASH:
                    $this->ImageInfo["h"]["flashUsed"] = "No";
                    if ($this->ConvertAnyFormat($ValuePtr, $Format) & 7){
                        $this->ImageInfo["h"]["flashUsed"] = "Yes";
                    }
                    break;

                case TAG_ORIENTATION:
                    $this->ImageInfo[TAG_ORIENTATION] = $this->ConvertAnyFormat($ValuePtr, $Format);
                    if ($this->ImageInfo[TAG_ORIENTATION] < 1 || $this->ImageInfo[TAG_ORIENTATION] > 8){
                            $this->debug(sprintf("Undefined rotation value %d", $this->ImageInfo[TAG_ORIENTATION], 0),1);
                        $this->ImageInfo[TAG_ORIENTATION] = 0;
                    }
                    break;

                case TAG_EXIF_IMAGELENGTH:
                    //       * Image height
                    $a = (int) $this->ConvertAnyFormat($ValuePtr, $Format);
                    if ($this->ExifImageLength < $a) $this->ExifImageLength = $a;
                    $this->ImageInfo[TAG_EXIF_IMAGELENGTH] = $this->ExifImageLength;
                    $this->ImageInfo["h"]["Height"] = $this->ExifImageLength;
                    break;
                case TAG_EXIF_IMAGEWIDTH:
                    // Use largest of height and width to deal with images that have been
                    // rotated to portrait format.
                    $a = (int) $this->ConvertAnyFormat($ValuePtr, $Format);
                    if ($this->ExifImageWidth < $a) $this->ExifImageWidth = $a;
                    $this->ImageInfo[TAG_EXIF_IMAGEWIDTH] = $this->ExifImageWidth;
                    $this->ImageInfo["h"]["Width"] = $this->ExifImageWidth;

                    break;

                case TAG_FOCALPLANEXRES:
                    $this->FocalplaneXRes = $this->ConvertAnyFormat($ValuePtr, $Format);
                    $this->FocalplaneXRes = $this->FocalplaneXRes[0];
                    $this->ImageInfo[TAG_FOCALPLANEXRES] = $this->FocalplaneXRes[0];
                    break;

                case TAG_FOCALPLANEUNITS:
                    switch($this->ConvertAnyFormat($ValuePtr, $Format)){
                        case 1: $this->FocalplaneUnits = 25.4; break; // inch
                        case 2:
                            // According to the information I was using, 2 means meters.
                            // But looking at the Cannon powershot's files, inches is the only
                            // sensible value.
                            $this->FocalplaneUnits = 25.4;
                            break;

                        case 3: $this->FocalplaneUnits = 10;   break;  // centimeter
                        case 4: $this->FocalplaneUnits = 1;    break;  // milimeter
                        case 5: $this->FocalplaneUnits = .001; break;  // micrometer
                    }
                    $this->ImageInfo[TAG_FOCALPLANEUNITS] = $this->FocalplaneUnits;
                    break;

                    // Remaining cases contributed by: Volker C. Schoech (schoech@gmx.de)

                case TAG_EXPOSURE_BIAS:
                    $tmp = $this->ConvertAnyFormat($ValuePtr, $Format);
                    $this->ImageInfo['h']["exposureBias"] = sprintf("%4.2f (%d/%d)",(double)$tmp[0],$tmp[1][0],$tmp[1][1]);
                    break;

                case TAG_WHITEBALANCE:
                    $tmp = (int) $this->ConvertAnyFormat($ValuePtr, $Format);
                    $tmpArr = array("1"=>"Sunny","2"=>"fluorescent","3"=>"incandescent");
                    $this->ImageInfo['h']["whiteBalance"] =
                        (isset($tmpArr["$tmp"]) ? $tmpArr["$tmp"] : "Cloudy");
                    break;

                case TAG_METERING_MODE:
                    $tmp = (int) $this->ConvertAnyFormat($ValuePtr, $Format);

                    $tmpArr = array("2"=>"center weight","3"=>"spot","5"=>"matrix");
                    $this->ImageInfo['h']["meteringMode"] =
                        (isset($tmpArr["$tmp"]) ? $tmpArr["$tmp"] : "Reserved");
                    break;

                case TAG_EXPOSURE_PROGRAM:
                    $tmp = (int) $this->ConvertAnyFormat($ValuePtr, $Format);
                    $tmpArr = array("2"=>"program (auto)","3"=>"aperture priority (semi-auto)","4"=>"shutter priority (semi-auto)");
                    $this->ImageInfo['h']["exposure"] =
                        (isset($tmpArr["$tmp"]) ? $tmpArr["$tmp"] : "Reserved");

                    break;

                case TAG_ISO_EQUIVALENT:
                    $tmp = (int) $this->ConvertAnyFormat($ValuePtr, $Format);
                    if ( $tmp < 50 ) $tmp *= 200;
                    $this->ImageInfo['h']["isoEquiv"] = sprintf("%2d",(int)$tmp);
                    break;

                case TAG_COMPRESSION_LEVEL:
                    $tmp = (int) $this->ConvertAnyFormat($ValuePtr, $Format);
                    $tmpArr = array("1"=>"Basic","2"=>"Normal","4"=>"Fine");
                    $this->ImageInfo['h']["jpegQuality"] =
                        (isset($tmpArr["$tmp"]) ? $tmpArr["$tmp"] : "Reserved");
                    break;

                case TAG_THUMBNAIL_OFFSET:
                    //$this->ThumbnailOffset = $this->ConvertAnyFormat($ValuePtr, $Format);
                    //$this->DirWithThumbnailPtrs = $DirStart;
                    break;

                case TAG_THUMBNAIL_LENGTH:
                    //$this->ThumbnailSize = $this->ConvertAnyFormat($ValuePtr, $Format);
                    //$this->ImageInfo[TAG_THUMBNAIL_LENGTH] = $this->ThumbnailSize;
                    break;

                //----------------------------------------------
                case TAG_IMAGE_DESC:
                        $this->ImageInfo['h']["imageDesc"] = $this->string_format(substr($ValuePtr,0,$ByteCount));
                        break;
                case TAG_X_RESOLUTION:
                        $tmp = $this->ConvertAnyFormat($ValuePtr, $Format);
                        $this->ImageInfo['h']["xResolution"] = sprintf("%4.2f (%d/%d) %s",(double)$tmp[0],$tmp[1][0],$tmp[1][1],$this->ImageInfo['h']["resolutionUnit"]);
                        break;
                case TAG_Y_RESOLUTION:
                        $tmp = $this->ConvertAnyFormat($ValuePtr, $Format);
                        $this->ImageInfo['h']["yResolution"] = sprintf("%4.2f (%d/%d) %s",(double)$tmp[0],$tmp[1][0],$tmp[1][1],$this->ImageInfo['h']["resolutionUnit"]);
                        break;
                case TAG_RESOLUTION_UNIT:
                        $tmp = $this->ConvertAnyFormat($ValuePtr, $Format);
                        $tmpArr = array("2"=>"Inches","3"=>"Centimeters");

                        $this->ImageInfo['h']["resolutionUnit"] =
                            (isset($tmpArr["$tmp"]) ? $tmpArr["$tmp"] : "Reserved");
                        break;
                case TAG_SOFTWARE:
                        $this->ImageInfo['h']["software"] = $this->string_format(substr($ValuePtr,0,$ByteCount));
                        break;
                case TAG_FILE_MODDATE;
                        $this->ImageInfo['h']["fileModifiedDate"] = $this->string_format(substr($ValuePtr,0,$ByteCount));
                        break;
                case TAG_YCBCR_POSITIONING:
                        $this->ImageInfo['h']["YCbCrPositioning"] = $this->ConvertAnyFormat($ValuePtr, $Format);
                        break;
                case TAG_EXIF_VERSION:
                        $this->ImageInfo['h']["exifVersion"] = $this->string_format(substr($ValuePtr,0,$ByteCount));
                        break;
                case TAG_DATE_TIME_DIGITIZED:
                        $this->ImageInfo['h']["dateTimeDigitized"] = $this->string_format(substr($ValuePtr,0,$ByteCount));
                        break;
                case TAG_COMPONENT_CONFIG: // need more tests for this
                        $tmp = (int)$this->ConvertAnyFormat($ValuePtr, $Format);

                        $tmpArr = array("0"=>"Does Not Exists","1"=>"Y","2"=>"Cb","3"=>"Cr","4"=>"R","5"=>"G","6"=>"B");

                        if(strlen($tmp) < 4 ) {
                            $this->ImageInfo['h']["componentConfig"] = $tmpArr["0"];
                        } else {
                            for($i=0;$i<strlen($tmp);$i++) {
                                if($tmp["$i"] != 0) {
                                    $this->ImageInfo['h']["componentConfig"] .= $tmpArr[$tmp["$i"]];
                                }
                            }
                        }
                        break;
                case TAG_MAKER_NOTE:
                        //$this->ImageInfo['h']["makerNote"] = substr($ValuePtr,0,$ByteCount);
                        $this->ImageInfo['h']["makerNote"] = "NOT IMPLEMENTED";
                        break;
                case TAG_SUB_SEC_TIME:
                        $this->ImageInfo['h']["subSectionTime"] = $this->string_format(substr($ValuePtr,0,$ByteCount));
                        break;
                case TAG_SUB_SEC_TIME_ORIG:
                        $this->ImageInfo['h']["subSectionTimeOriginal"] = $this->string_format(substr($ValuePtr,0,$ByteCount));
                        break;
                case TAG_SUB_SEC_TIME_DIGITIZED:
                        $this->ImageInfo['h']["subSectionTimeDigtized"] = $this->string_format(substr($ValuePtr,0,$ByteCount));
                        break;
                case TAG_FLASHPIX_VER:
                        $this->ImageInfo['h']["flashpixVersion"] = $this->string_format(substr($ValuePtr,0,$ByteCount));
                        break;
                case TAG_COLOR_SPACE:
                        $this->ImageInfo['h']["colorSpace"] = $this->string_format(substr($ValuePtr,0,$ByteCount));
                        break;
                case TAG_RELATED_SOUND_FILE:
                        $this->ImageInfo['h']["relatedSoundFile"] = $this->string_format(substr($ValuePtr,0,$ByteCount));
                        break;
                case TAG_GPS_LATITUDE_REF:
                        $this->ImageInfo['h']["GPSLatitudeRef"] = $this->string_format(substr($ValuePtr,0,$ByteCount));
						$this->ImageInfo['h']["GPSLatitudeRef"] = trim($this->ImageInfo['h']["GPSLatitudeRef"]);
						$tmp = substr($this->ImageInfo['h']["GPSLatitudeRef"],0,1);
						if($tmp == "S") {
							$this->ImageInfo['h']["GPSLatitudeRef"] = "South latitude";
						} else if($tmp == "N") {
							$this->ImageInfo['h']["GPSLatitudeRef"] = "North latitude";
						} else {
							$this->ImageInfo['h']["GPSLatitudeRef"] = "Reserved";
						}
                        break;
                case TAG_GPS_LATITUDE:
						$tmp = substr($ValuePtr,0,$ByteCount);

						$this->ImageInfo['h']["GPSLatitude"]["Degrees"] = ord(substr($tmp,0,1));
						$this->ImageInfo['h']["GPSLatitude"]["Minutes"] = ord(substr($tmp,1,1));
						$this->ImageInfo['h']["GPSLatitude"]["Seconds"] = ord(substr($tmp,2,1));
                        break;

                case TAG_GPS_LONGITUDE:
						$tmp = substr($ValuePtr,0,$ByteCount);

						$this->ImageInfo['h']["GPSLongitude"]["Degrees"] = ord(substr($tmp,0,1));
						$this->ImageInfo['h']["GPSLongitude"]["Minutes"] = ord(substr($tmp,1,1));
						$this->ImageInfo['h']["GPSLongitude"]["Seconds"] = ord(substr($tmp,2,1));

                        break;

                case TAG_GPS_LONGITUDE_REF:
                        $this->ImageInfo['h']["GPSLongitudeRef"] = substr($ValuePtr,0,$ByteCount);
						$this->ImageInfo['h']["GPSLongitudeRef"] = trim($this->ImageInfo['h']["GPSLongitudeRef"]);
						$tmp = substr($this->ImageInfo['h']["GPSLongitudeRef"],0,1);
						if($tmp == "E") {
							$this->ImageInfo['h']["GPSLongitudeRef"] = "East Longitude";
						} else if($tmp == "W") {
							$this->ImageInfo['h']["GPSLongitudeRef"] = "West Longitude";
						} else {
							$this->ImageInfo['h']["GPSLongitudeRef"] = "Reserved";
						}

                        break;


				case TAG_GPS_TrackRef: /* Reference for direction of movement    GPSTrackRef */
					$this->ImageInfo['h']["GPSTrackRef"] = $this->string_format(substr($ValuePtr,0,$ByteCount));
					break;


				case TAG_GPS_GPSTrack: /* Direction of movement					GPSTrack */
					$this->ImageInfo['h']["GPSTrack"] = $this->string_format(substr($ValuePtr,0,$ByteCount));
					break;
				case TAG_GPS_GPSImgDirectionRef: /* Reference for direction of image       GPSImgDirectionRef */
					$this->ImageInfo['h']["GPSImgDirectionRef"] = $this->string_format(substr($ValuePtr,0,$ByteCount));
					break;
				case TAG_GPS_GPSImgDirection: /* Direction of image                     GPSImgDirection     */
					$this->ImageInfo['h']["GPSImgDirection"] = $this->ConvertAnyFormat($ValuePtr, $Format);
					break;
				case TAG_GPS_GPSMapDatum: /* Geodetic survey data used              GPSMapDatum         */
					$this->ImageInfo['h']["GPSMapDatum"] = $this->string_format(substr($ValuePtr,0,$ByteCount));
					break;
				case TAG_GPS_GPSDestLatitudeRef:/* Reference for latitude of destination  GPSDestLatitudeRef  */
					$this->ImageInfo['h']["GPSDestLatitudeRef"] = substr($ValuePtr,0,$ByteCount);
					$this->ImageInfo['h']["GPSDestLatitudeRef"] = trim($this->ImageInfo['h']["GPSDestLatitudeRef"]);
					$tmp = substr($this->ImageInfo['h']["GPSDestLatitudeRef"],0,1);
					if($tmp == "S") {
						$this->ImageInfo['h']["GPSDestLatitudeRef"] = "South latitude";
					} else if($tmp == "N") {
						$this->ImageInfo['h']["GPSDestLatitudeRef"] = "North latitude";
					} else {
						$this->ImageInfo['h']["GPSDestLatitudeRef"] = "Reserved";
					}

					break;
				case TAG_GPS_GPSDestLatitude:/* Latitude of destination                GPSDestLatitude     */
						$tmp = substr($ValuePtr,0,$ByteCount);

						$this->ImageInfo['h']["GPSDestLatitude"]["Degrees"] = ord(substr($tmp,0,1));
						$this->ImageInfo['h']["GPSDestLatitude"]["Minutes"] = ord(substr($tmp,1,1));
						$this->ImageInfo['h']["GPSDestLatitude"]["Seconds"] = ord(substr($tmp,2,1));

					break;
				case TAG_GPS_GPSDestLongitudeRef:/* Reference for longitude of destination GPSDestLongitudeRef 21     */
					$this->ImageInfo['h']["GPSDestLongitudeRef"] = substr($ValuePtr,0,$ByteCount);
					$this->ImageInfo['h']["GPSDestLongitudeRef"] = trim($this->ImageInfo['h']["GPSDestLongitudeRef"]);
					$tmp = substr($this->ImageInfo['h']["GPSDestLongitudeRef"],0,1);
					if($tmp == "E") {
						$this->ImageInfo['h']["GPSDestLongitudeRef"] = "East Longitude";
					} else if($tmp == "W") {
						$this->ImageInfo['h']["GPSDestLongitudeRef"] = "West Longitude";
					} else {
						$this->ImageInfo['h']["GPSDestLongitudeRef"] = "Reserved";
					}

					break;
				case TAG_GPS_GPSDestLongitude:/* Longitude of destination               GPSDestLongitude    22     */
					$this->ImageInfo['h']["GPSDestLongitude"] = $this->string_format(substr($ValuePtr,0,$ByteCount));
					break;
				case TAG_GPS_GPSDestBearingRef:/* Reference for bearing of destination   GPSDestBearingRef   23     */
					$this->ImageInfo['h']["GPSDestBearingRef"] = $this->string_format(substr($ValuePtr,0,$ByteCount));
					break;
				case TAG_GPS_GPSDestBearing: /* Bearing of destination                 GPSDestBearing      24     */
					$this->ImageInfo['h']["GPSDestBearing"] = $this->string_format(substr($ValuePtr,0,$ByteCount));
					break;
				case TAG_GPS_GPSDestDistanceRef:/* Reference for distance to destination  GPSDestDistanceRef  25     */
					$this->ImageInfo['h']["GPSDestDistanceRef"] = $this->string_format(substr($ValuePtr,0,$ByteCount));
					break;
				case TAG_GPS_GPSDestDistance: /* Distance to destination                GPSDestDistance     26     */
					//$this->ImageInfo['h']["GPSDestDistance"] = $this->ConvertAnyFormat($ValuePtr, $Format);
					$tmp = $this->ConvertAnyFormat($ValuePtr, $Format);
					$this->ImageInfo['h']["GPSDestDistance"] = sprintf("%4.2f (%d/%d)",(double)$tmp[0],$tmp[1][0],$tmp[1][1]);;
					break;
				case TAG_GPS_GPSProcessingMethod: /* Name of GPS processing method          GPSProcessingMethod 27     */
					//$this->ImageInfo['h']["GPSProcessingMethod"] = $this->ConvertAnyFormat($ValuePtr, $Format);
					$tmp = $this->ConvertAnyFormat($ValuePtr, $Format);
					$this->ImageInfo['h']["GPSProcessingMethod"] = sprintf("%4.2f (%d/%d)",(double)$tmp[0],$tmp[1][0],$tmp[1][1]);;
					break;
				case TAG_GPS_GPSAreaInformation: /* Name of GPS area                       GPSAreaInformation  28     */
					$this->ImageInfo['h']["GPSAreaInformation"] = $this->string_format(substr($ValuePtr,0,$ByteCount));
					break;
				case TAG_GPS_GPSDateStamp: /* GPS date                               GPSDateStamp        29     */
					$this->ImageInfo['h']["GPSDateStamp"] = $this->string_format(substr($ValuePtr,0,$ByteCount));
					break;
				case TAG_GPS_GPSDifferential: /* GPS differential correction            GPSDifferential     30     */
					$this->ImageInfo['h']["GPSDifferential"] = $this->string_format(substr($ValuePtr,0,$ByteCount));
					break;

				case TAG_AUDIO_MU_LAW:
					$this->ImageInfo['h']["AudioMuLaw"] = $this->ConvertAnyFormat($ValuePtr, $Format);
					break;
				case TAG_AUDIO_IMA_ADPCM_DESC: //  IMA-ADPCM Audio File Description Example - 40
					$this->ImageInfo['h']["AudioIMA-ADPCM-DESC"] = $this->ConvertAnyFormat($ValuePtr, $Format);
					break;
				case TAG_AUDIO_MU_LAW_DESC: //  µ-Law Audio File Description Sample - 50
					$this->ImageInfo['h']["AudioMuLawDesc"] = $this->ConvertAnyFormat($ValuePtr, $Format);
					break;

				case TAG_EXPOSURE_INDEX:
					$tmp = $this->ConvertAnyFormat($ValuePtr, $Format);
					$this->ImageInfo['h']["ExposureIndex"] = sprintf("%4.2f (%d/%d)",(double)$tmp[0],$tmp[1][0],$tmp[1][1]);;
					break;

                case TAG_SENSING_METHOD:
                        $tmp = $this->ConvertAnyFormat($ValuePtr, $Format);
                        $tmpArr = array("1"=>"Not Defined","2"=>"One-chip color area sensor","3"=>"Two-chip color area sensor",
                                        "4"=>"Three -chip color area sensor","5"=>"Color sequential area sensor",
                                        "6"=>"Trilinear sensor", "7"=>"Color sequential linear sensor"
                                        );

                        $this->ImageInfo['h']["sensing"] =
                            (isset($tmpArr["$tmp"]) ? $tmpArr["$tmp"] : "Reserved");
                        break;
                case TAG_SOUCE_TYPE:
                        $this->ImageInfo['h']["sourceType"] = $this->string_format(substr($ValuePtr,0,$ByteCount));
                        break;
                case TAG_SCENE_TYPE:
                        $this->ImageInfo['h']["sceneType"] = $this->string_format(substr($ValuePtr,0,$ByteCount));
                        break;
                case TAG_CFA_PATTERN:
                        $this->ImageInfo['h']["CFAPattern"] = $this->string_format(substr($ValuePtr,0,$ByteCount));
                        break;
                case TAG_CUSTOM_RENDERED:
                        $tmp = $this->ConvertAnyFormat($ValuePtr, $Format);
                        $this->ImageInfo['h']["customRendered"] = ($mp == 0) ? 'Normal Process' : ($mp == 1 ? 'Custom Process' : 'Reserved');
                        break;
                case TAG_EXPOSURE_MODE:
                        $tmp = $this->ConvertAnyFormat($ValuePtr, $Format);
                        $tmpArr = array('Auto Exposure','Manual Exposure','Auto Bracket');
                        $this->ImageInfo['h']["exposureMode"] =
                            (isset($tmpArr["$tmp"]) ? $tmpArr["$tmp"] : "Reserved");
                        break;
                case TAG_WHITE_BALANCE:
                        $this->ImageInfo['h']["whiteBalance"] = $this->ConvertAnyFormat($ValuePtr, $Format);
                        break;
                case TAG_DIGITAL_ZOOM_RATIO:
                        $tmp = $this->ImageInfo['h']["zoomRatio"] = $this->ConvertAnyFormat($ValuePtr, $Format);
                        $this->ImageInfo['h']["zoomRatio"] = sprintf("%4.2f (%d/%d)",(double)$tmp[0],$tmp[1][0],$tmp[1][1]);
                        break;
                case TAG_FLENGTH_IN35MM:
                        $this->ImageInfo['h']["flength35mm"] = $this->ConvertAnyFormat($ValuePtr, $Format);
                        break;
                case TAG_SCREEN_CAP_TYPE:
                        $tmp = $this->ConvertAnyFormat($ValuePtr, $Format);
                        $tmpArr = array("Standard","Landscape","Portrait","Night Scene");
                        $this->ImageInfo['h']["screenCaptureType"] =
                            (isset($tmpArr["$tmp"]) ? $tmpArr["$tmp"] : "Reserved");
                        break;
                case TAG_GAIN_CONTROL:
                        $tmp = $this->ConvertAnyFormat($ValuePtr, $Format);
                        $tmpArr = array("None","Low Gain Up","High Gain Up","Low Gain Down","High Gain Down");
                        $this->ImageInfo['h']["gainControl"] =
                            (isset($tmpArr["$tmp"]) ? $tmpArr["$tmp"] : "Reserved");
                        break;
                case TAG_CONTRAST:
                        $tmp = $this->ConvertAnyFormat($ValuePtr, $Format);
                        $tmpArr = array("Normal","Soft","Hard");
                        $this->ImageInfo['h']["contrast"] =
                            (isset($tmpArr["$tmp"]) ? $tmpArr["$tmp"] : "Reserved");
                        break;
                case TAG_SATURATION:
                        $tmp = $this->ConvertAnyFormat($ValuePtr, $Format);
                        $tmpArr = array("Normal","Low Saturation","High Saturation");
                        $this->ImageInfo['h']["saturation"] =
                            (isset($tmpArr["$tmp"]) ? $tmpArr["$tmp"] : "Reserved");
                        break;
                case TAG_SHARPNESS:
                        $tmp = $this->ConvertAnyFormat($ValuePtr, $Format);
                        $tmpArr = array("Normal","Soft","Hard");
                        $this->ImageInfo['h']["sharpness"] =
                            (isset($tmpArr["$tmp"]) ? $tmpArr["$tmp"] : "Reserved");
                        break;
                case TAG_DIST_RANGE:
                        $tmp = $this->ConvertAnyFormat($ValuePtr, $Format);
                        $tmpArr = array("Unknown","Macro","Close View","Distant View");
                        $this->ImageInfo['h']["distanceRange"] =
                            (isset($tmpArr["$tmp"]) ? $tmpArr["$tmp"] : "Reserved");
                        break;
                case TAG_DEVICE_SETTING_DESC:
                        /*
                        $tmp = $this->ConvertAnyFormat($ValuePtr, $Format);
                        $tmpArr = array("Unknown","Macro","Close View","Distant View");
                        $this->ImageInfo['h']["distanceRange"] =
                            (isset($tmpArr["$tmp"]) ? $tmpArr["$tmp"] : "Reserved");
                        */
                        $this->ImageInfo['h']["deviceSettingDesc"] = "NOT IMPLEMENTED";
                        break;
                case TAG_COMPRESS_SCHEME:
                        $tmp = $this->ConvertAnyFormat($ValuePtr, $Format);
                        $tmpArr = array("1"=>"Uncompressed","6"=>"JPEG compression (thumbnails only)");
                        $this->ImageInfo['h']["compressScheme"] =
                            (isset($tmpArr["$tmp"]) ? $tmpArr["$tmp"] : "Reserved");
                        break;
                case TAG_IMAGE_WD:
                        $tmp = $this->ConvertAnyFormat($ValuePtr, $Format);
                        $this->ImageInfo['h']["jpegImageWidth"] = $tmp;
                        break;
                case TAG_IMAGE_HT:
                        $tmp = $this->ConvertAnyFormat($ValuePtr, $Format);
                        $this->ImageInfo['h']["jpegImageHeight"] = $tmp;
                        break;
                case TAG_IMAGE_BPS:
                        $tmp = $this->ConvertAnyFormat($ValuePtr, $Format);
                        $this->ImageInfo['h']["jpegBitsPerSample"] = $tmp;
                        break;
                case TAG_IMAGE_PHOTO_INT:
                        $tmp = $this->ConvertAnyFormat($ValuePtr, $Format);
                        $this->ImageInfo['h']["jpegPhotometricInt"] = $tmp;
                        $tmpArr = array("2"=>"RGB","6"=>"YCbCr");
                        $this->ImageInfo['h']["jpegPhotometricInt"] =
                            (isset($tmpArr["$tmp"]) ? $tmpArr["$tmp"] : "Reserved");

                        break;
                case TAG_IMAGE_SOFFSET:
                        $tmp = $this->ConvertAnyFormat($ValuePtr, $Format);
                        $this->ImageInfo['h']["jpegStripOffsets"] = $tmp;
                        break;
                case TAG_IMAGE_SPP:
                        $tmp = $this->ConvertAnyFormat($ValuePtr, $Format);
                        $this->ImageInfo['h']["jpegSamplesPerPixel"] = $tmp;
                        break;
                case TAG_IMAGE_RPS:
                        $tmp = $this->ConvertAnyFormat($ValuePtr, $Format);
                        $this->ImageInfo['h']["jpegRowsPerStrip"] = $tmp;
                        break;
                case TAG_IMAGE_SBC:
                        $tmp = $this->ConvertAnyFormat($ValuePtr, $Format);
                        $this->ImageInfo['h']["jpegStripByteCounts"] = $tmp;
                        break;
                case TAG_IMAGE_P_CONFIG:
                        $tmp = $this->ConvertAnyFormat($ValuePtr, $Format);
                        $tmpArr = array("1"=>"Chunky Format","2"=>"Planar Format");
                        $this->ImageInfo['h']["jpegPlanarConfig"] =
                            (isset($tmpArr["$tmp"]) ? $tmpArr["$tmp"] : "Reserved");
                        break;
                case TAG_FOCALPLANE_YRESOL:
                        $tmp = $this->ConvertAnyFormat($ValuePtr, $Format);
                        $this->ImageInfo['h']["focalPlaneYResolution"] = sprintf("%4.2f (%d/%d)",(double)$tmp[0],$tmp[1][0],$tmp[1][1]);
                        break;
                case TAG_BRIGHTNESS:
                        $tmp = $this->ConvertAnyFormat($ValuePtr, $Format);
                        $this->ImageInfo['h']["brightness"] = sprintf("%4.2f (%d/%d)",(double)$tmp[0],$tmp[1][0],$tmp[1][1]);
                        break;
                //---------------------------------------------
                case TAG_EXIF_OFFSET:
                case TAG_INTEROP_OFFSET:
                    {

                        $SubdirStart = substr($OffsetBase,$this->Get32u($ValuePtr[0],$ValuePtr[1],$ValuePtr[2],$ValuePtr[3]));
                        //if ($SubdirStart < $OffsetBase || $SubdirStart > $OffsetBase+$ExifLength){
                        //    debug("Illegal exif or interop ofset directory link",1);
                        //}else{
                            //echo "<h1>Calling sub-exif dir</h1>";
                            $this->ProcessExifDir($SubdirStart, $OffsetBase, $ExifLength);
                        //}
                        continue;
                    }
                default: {
                    $this->debug("UNKNOWN TAG: $Tag");
                    }
            }
        }

        {
        // In addition to linking to subdirectories via exif tags,
        // there's also a potential link to another directory at the end of each
        // directory.  this has got to be the result of a comitee!
        $tmpDirStart = substr($DirStart,2+12*$NumDirEntries);
        if (strlen($tmpDirStart) + 4 <= strlen($OffsetBase)+$ExifLength){
            $Offset = $this->Get32u($tmpDirStart[0],$tmpDirStart[1],$tmpDirStart[2],$tmpDirStart[3]);
            if ($Offset){
                $SubdirStart = substr($OffsetBase,$Offset);
                if (strlen($SubdirStart) > strlen($OffsetBase)+$ExifLength){
                    if (strlen($SubdirStart) < strlen($OffsetBase)+$ExifLength+20){
                        // Jhead 1.3 or earlier would crop the whole directory!
                        // As Jhead produces this form of format incorrectness,
                        // I'll just let it pass silently
                    } else {
                        $this->errno = 51;
                        $this->errstr = "Illegal subdirectory link";
                        $this->debug($this->errstr,1);
                    }
                }else{
                    if (strlen($SubdirStart) <= strlen($OffsetBase)+$ExifLength){
                        $this->ProcessExifDir($SubdirStart, $OffsetBase, $ExifLength);
                    }
                }
            }
        } else {
            // The exif header ends before the last next directory pointer.
        }
    }

    /**
    * Check if thumbnail has been cached or not.
    * If yes! then read the file.
    */
    /*
    if(file_exists($this->thumbnail) && $this->caching && (filemtime($this->thumbnail) == filemtime($this->file) )) {
        $this->ImageInfo["h"]["Thumbnail"] = $this->thumbnail;
        $this->ImageInfo["h"]["ThumbnailSize"] =  sprintf("%d bytes",filesize($this->thumbnail));
    } else{
        if ($this->ThumbnailSize && $this->ThumbnailOffset){
            if ($this->ThumbnailSize + $this->ThumbnailOffset <= $ExifLength){
                // The thumbnail pointer appears to be valid.  Store it.
                $this->ImageInfo["h"]["Thumbnail"] = substr($OffsetBase,$this->ThumbnailOffset);

                // Save the thumbnail /
                if($this->caching && is_dir($this->cacheDir)) {
                    $this->saveThumbnail($this->thumbnail);
                    $this->ImageInfo["h"]["Thumbnail"] = $this->thumbnail;
                }
                $this->ImageInfo["h"]["ThumbnailSize"] =  sprintf("%d bytes",strlen($this->ImageInfo["h"]["Thumbnail"]));
            }
        }
    }
	*/
    }

    /**
     * Process Exif data
     * @param   array    Section data as an array
     * @param   int  Length of the section (length of data array)
     *
     */
	function process_EXT_EXIF($data,$length) {
			//print_r($data);
	}

    /**
     * Process Exif data
     * @param   array    Section data as an array
     * @param   int  Length of the section (length of data array)
     *
     */
    function process_EXIF($data,$length) {

        $this->debug("Exif header $length bytes long\n");
        if(($data[2].$data[3].$data[4].$data[5]) != "Exif") {
            $this->errno = 52;
            $this->errstr = "NOT EXIF FORMAT";
            $this->debug($this->errstr,1);
        }

        $this->ImageInfo["h"]["FlashUsed"] = 0;
            /** If it s from a digicam, and it used flash, it says so. */

        $this->FocalplaneXRes = 0;
        $this->FocalplaneUnits = 0;
        $this->ExifImageWidth = 0;

        if(($data[8].$data[9]) == "II") {
            $this->debug("Exif section in Intel order\n");
            $this->MotorolaOrder = 0;
        } else if(($data[8].$data[9]) == "MM") {
            $this->debug("Exif section in Motorola order\n");
            $this->MotorolaOrder = 1;
        } else {
            $this->errno = 53;
            $this->errstr = "Invalid Exif alignment marker.\n";
            $this->debug($this->errstr,1);
            return;
        }

        if($this->Get16u($data[10],$data[11]) != 0x2A || $this->Get32s($data[12],$data[13],$data[14],$data[15]) != 0x08) {
            $this->errno = 54;
            $this->errstr = "Invalid Exif start (1)";
            $this->debug($this->errstr,1);
        }

        $DirWithThumbnailPtrs = NULL;

        //$this->ProcessExifDir(array_slice($data,16),array_slice($data,8),$length);
        $this->ProcessExifDir(substr($data,16),substr($data,8),$length);

        // Compute the CCD width, in milimeters.                      2
        if ($this->FocalplaneXRes != 0){
            $this->ImageInfo["h"]["CCDWidth"] = sprintf("%4.2fmm",(float)($this->ExifImageWidth * $this->FocalplaneUnits / $this->FocalplaneXRes));
        }

        $this->debug("Non settings part of Exif header: ".$length." bytes\n");
    } // end of function process_EXIF

    /**
     * Converts two byte number into its equivalent int integer
     * @param   int
     * @param   int
     *
     */
    function Get16u($val,$by) {
        if($this->MotorolaOrder){
            return ((ord($val) << 8) | ord($by));
        } else {
            return ((ord($by) << 8) | ord($val));
        }
    }

    /**
     * Converts 4-byte number into its equivalent integer
     *
     * @param   int
     * @param   int
     * @param   int
     * @param   int
     *
     * @return int
     */
    function Get32s($val1,$val2,$val3,$val4)
    {
        $val1 = ord($val1);
        $val2 = ord($val2);
        $val3 = ord($val3);
        $val4 = ord($val4);

        if ($this->MotorolaOrder){
            return (($val1 << 24) | ($val2 << 16) | ($val3 << 8 ) | ($val4 << 0 ));
        }else{
            return  (($val4 << 24) | ($val3 << 16) | ($val2 << 8 ) | ($val1 << 0 ));
        }
    }
    /**
     * Converts 4-byte number into its equivalent integer with the help of Get32s
     *
     * @param   int
     * @param   int
     * @param   int
     * @param   int
     *
     * @return int
     *
     */
    function get32u($val1,$val2,$val3,$val4) {
        return ($this->Get32s($val1,$val2,$val3,$val4) & 0xffffffff);
    }

    //--------------------------------------------------------------------------
    // Evaluate number, be it int, rational, or float from directory.
    //--------------------------------------------------------------------------
    function ConvertAnyFormat($ValuePtr, $Format)
    {
        $Value = 0;

        switch($Format){
            case FMT_SBYTE:     $Value = $ValuePtr[0];  break;
            case FMT_BYTE:      $Value = $ValuePtr[0];        break;

            case FMT_USHORT:    $Value = $this->Get16u($ValuePtr[0],$ValuePtr[1]);          break;
            case FMT_ULONG:     $Value = $this->Get32u($ValuePtr[0],$ValuePtr[1],$ValuePtr[2],$ValuePtr[3]);          break;

            case FMT_URATIONAL:
            case FMT_SRATIONAL:
                {

                    $Num = $this->Get32s($ValuePtr[0],$ValuePtr[1],$ValuePtr[2],$ValuePtr[3]);
                    $Den = $this->Get32s($ValuePtr[4],$ValuePtr[5],$ValuePtr[6],$ValuePtr[7]);
                    if ($Den == 0){
                        $Value = 0;
                    }else{
                        $Value = (double) ($Num/$Den);
                    }
                    return array($Value,array($Num,$Den));
                    break;
                }

            case FMT_SSHORT:    $Value = $this->Get16u($ValuePtr[0],$ValuePtr[1]);  break;
            case FMT_SLONG:     $Value = $this->Get32s($ValuePtr[0],$ValuePtr[1],$ValuePtr[2],$ValuePtr[3]);                break;

            // Not sure if this is correct (never seen float used in Exif format)
            case FMT_SINGLE:    $Value = $ValuePtr[0];      break;
            case FMT_DOUBLE:    $Value = $ValuePtr[0];             break;
        }
        return $Value;
    }

    /**
     * Function to extract thumbnail from Exif data of the image.
     * and store it in a filename given by $ThumbFile
     *
     * @param   String   Files name to store the thumbnail
     *
     */
    function saveThumbnail($ThumbFile) {
         $ThumbFile = trim($ThumbFile);
         $file = basename($this->file);

         if(empty($ThumbFile)) $ThumbFile = "th_$file";

         if (!empty($this->ImageInfo["h"]["Thumbnail"])){
            $tp = fopen($ThumbFile,"wb");
            if(!$tp) {
                $this->errno = 2;
                $this->errstr = "Cannot Open file '$ThumbFile'";
            }
            fwrite($tp,$this->ImageInfo["h"]["Thumbnail"]);
            fclose($tp);
            touch($ThumbFile,filemtime($this->file));
         }
         //$this->thumbnailURL = $ThumbFile;
         $this->ImageInfo["h"]["Thumbnail"] = $ThumbFile;
    }

    /**
     * Returns thumbnail url along with parameter supplied.
     * Should be called in src attribute of image
     *
     * @return  string  File URL
     *
     */
    function showThumbnail() {
        return "showThumbnail.php?file=".$this->file;
        //$this->ImageInfo["h"]["Thumbnail"]
    }

    /**
     * Function to give back thumbail image
     * @return string   full image
     *
     */
    function getThumbnail() {
        return $this->ImageInfo["h"]["Thumbnail"];
    }

    /**
    *
    */
    function getImageInfo() {

        $imgInfo = $this->ImageInfo["h"];

        $retArr = $imgInfo;
        $retArr["FileName"] = $imgInfo["FileName"];
        $retArr["FileSize"] = $imgInfo["FileSize"]." bytes";

        $retArr["FileDateTime"] = date("d-M-Y H:i:s",$imgInfo["FileDateTime"]);

        $retArr["resolution"] = $imgInfo["Width"]."x".$imgInfo["Height"];


        if ($this->ImageInfo[TAG_ORIENTATION] > 1){
                // Only print orientation if one was supplied, and if its not 1 (normal orientation)

                // 1 - "The 0th row is at the visual top of the image,    and the 0th column is the visual left-hand side."
                // 2 - "The 0th row is at the visual top of the image,    and the 0th column is the visual right-hand side."
                // 3 - "The 0th row is at the visual bottom of the image, and the 0th column is the visual right-hand side."
                // 4 - "The 0th row is at the visual bottom of the image, and the 0th column is the visual left-hand side."

                // 5 - "The 0th row is the visual left-hand side of of the image,  and the 0th column is the visual top."
                // 6 - "The 0th row is the visual right-hand side of of the image, and the 0th column is the visual top."
                // 7 - "The 0th row is the visual right-hand side of of the image, and the 0th column is the visual bottom."
                // 8 - "The 0th row is the visual left-hand side of of the image,  and the 0th column is the visual bottom."

                // Note: The descriptions here are the same as the name of the command line
                // ption to pass to jpegtran to right the image
                $OrientTab = array(
                "Undefined",
                "Normal",           // 1
                "flip horizontal",  // left right reversed mirror
                "rotate 180",       // 3
                "flip vertical",    // upside down mirror
                "transpose",        // Flipped about top-left <--> bottom-right axis.
                "rotate 90",        // rotate 90 cw to right it.
                "transverse",       // flipped about top-right <--> bottom-left axis
                "rotate 270",       // rotate 270 to right it.
                );

                $retArr["orientation"] = $OrientTab[$this->ImageInfo[TAG_ORIENTATION]];
        }

        $retArr["color"] = ($imgInfo["IsColor"] == 0) ? "Black and white" : "Color";

        if(isset($imgInfo["Process"])) {
            switch($imgInfo["Process"]) {
                case M_SOF0: $process = "Baseline";break;
                case M_SOF1: $process = "Extended sequential";break;
                case M_SOF2: $process = "Progressive";break;
                case M_SOF3: $process = "Lossless";break;
                case M_SOF5: $process = "Differential sequential";break;
                case M_SOF6: $process = "Differential progressive";break;
                case M_SOF7: $process = "Differential lossless";break;
                case M_SOF9: $process = "Extended sequential, arithmetic coding";break;
                case M_SOF10: $process = "Progressive, arithmetic coding";break;
                case M_SOF11: $process = "Lossless, arithmetic coding";break;
                case M_SOF13: $process = "Differential sequential, arithmetic coding";break;
                case M_SOF14: $process = "Differential progressive, arithmetic coding";break;
                case M_SOF15: $process =   "Differential lossless, arithmetic coding";break;
                default: $process = "Unknown";
            }
            $retArr["jpegProcess"] = $process;
        }

        if(file_exists($this->thumbnailURL)) {
                $retArr["Thumbnail"] = "<a href='$this->thumbnailURL'>$this->thumbnailURL</a>";
        }

        return $retArr;
    }

	/**
	*
	*/
	function string_format($str) {
		$tmpStr = "";

		for($i=0;$i<strlen($str);$i++) {
			if(ord($str[$i]) !=0) {
				$tmpStr .= $str[$i];
			}
		}
		return $tmpStr;
	}
    /**
    * Returns time in microseconds
    */
    function getmicrotime(){
        list($usec, $sec) = explode(" ",microtime());
        return ((float)$usec + (float)$sec);
    }

    /**
    *  Get the time difference
    */
    function getDiffTime() {
            return ($this->getmicrotime() - $this->timeStart);
    }

} // end of class
?>
Back to Top