Source

php-rescene / rescene.php

Full commit
   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
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
<?php 
/**
 * PHP Library to read and edit a .srr file. It reads .srs files.
 * Copyright (c) 2011-2013 Gfy
 *
 * rescene.php is free software, you can redistribute it and/or modify
 * it under the terms of GNU Affero General Public License
 * as published by the Free Software Foundation, either version 3
 * of the License, or (at your option) any later version.
 *
 * You should have received a copy of the the GNU Affero
 * General Public License, along with rescene.php. If not, see
 * http://www.gnu.org/licenses/agpl.html
 *
 * Additional permission under the GNU Affero GPL version 3 section 7:
 *
 * If you modify this Program, or any covered work, by linking or
 * combining it with other code, such other code is not for that reason
 * alone subject to any of the requirements of the GNU Affero GPL
 * version 3.
 */

/*
 * LGPLv3 with Affero clause (LAGPL)
 * See http://mo.morsi.org/blog/node/270
 * rescene.php written on 2011-07-27
 * Last version: 2013-02-01
 *
 * Features:
 *  - process a SRR file which returns:
 *     - SRR file size.
 *     - Application name of the tool used to create the SRR file.
 *     - List of files stored in the SRR.
 *     - List of RAR volumes the SRR can reconstruct.
 *     - List of files that are archived inside these RARs.
 *     - Size of all Recovery Records inside the SRR file.
 *     - Comments inside SFV files.
 *     - Warnings when something unusual is found with the SRR.
 *  - Remove a stored file.
 *  - Rename a stored file.
 *  - Add a stored file.
 *  - Read a stored file.
 *  - Extract a stored file.
 *  - Calculate a hash of the SRR based on RAR metadata.
 *  - Sorting of the stored file names.
 *  - process in memory SRR 'file'
 *  - compare two SRR files
 *      - nfo: ignore line endings
 *      - sfv: sort it before comparing and remove comment lines
 *      - rar metadata
 *          -> quick: by hash
 *          -> see what is missing
 *      - other files
 *          -> quick: by hash
 *  - compare SRS files
 *  - Output flag added to indicate if the RARs used compression.
 *  - Support to read SRS files. (AVI/MKV/MP4/WMV)
 *  - Sort stored files inside the SRR.
 *  - OpenSubtitles.org hash support.
 *
 *  - nfo compare: strip line endings + new line?
 *      Indiana.Jones.And.The.Last.Crusade.1989.PAL.DVDR-DNA
 *
 * List of possible features/todo list:
 *  - process in memory SRR 'file' + other API functions (very low priority)
 *      => can be done using temp files in memory
 *  - refactor compare SRR
 *  - merge SRRs (Python script exists)
 *  - encryption sanity check
 *  - add paths before the rar files
 *  - detect when SRR is cut/metadata from rars missing
 *      => hard to do correctly (SFVs subs exist too)
 *  - how to throw errors correctly?
 *  - sorting the list of the stored files by hand
 *  - "Application name found in the middle of the SRR."
 *    causes hashes to be different
 *
 */


$BLOCKNAME = array(
0x69 => 'SRR VolumeHeader',
0x6A => 'SRR Stored File',
0x6B => 'SRR OSO Hash',
0x71 => 'SRR RAR subblock',
0x72 => 'RAR Marker',
0x73 => 'Archive Header',
0x74 => 'File',
0x75 => 'Old style - Comment',
0x76 => 'Old style - Extra info (authenticity information)',
0x77 => 'Old style - Subblock',
0x78 => 'Old style - Recovery record',
0x79 => 'Old style - Archive authenticity',
0x7A => 'New-format subblock',
0x7B => 'Archive end'
);

class FileType {
    const MKV = 'MKV';
    const AVI = 'AVI';
    const MP4 = 'MP4';
    const WMV = 'WMV';
    const Unknown = '';
}

// cli progs are cool
if (!empty($argc) && strstr($argv[0], basename(__FILE__))) {
    /* How to use the CLI version in Windows:
     - Download and install PHP.  http://windows.php.net/download/
    - Run this script by entering something like
    C:\Program Files (x86)\PHP\php.exe rescene.php
    in the command prompt.
    - [Add 'C:\Program Files (x86)\PHP' to your systems Path environment variable
    to be able to run PHP from anywhere.]
    - To run this script from everywhere, create 'rescene.bat' in a directory that is in your PATH.
    For example: 'C:\Windows\rescene.bat'
    Include the following content:
    "C:\Program Files (x86)\PHP\php.exe" "C:\Windows\rescene.php" %*
    And place the PHP file accordingly.
    Enter 'rescene' anywhere to use it.
    */
    if (!array_key_exists(1, $argv)) {
        echo "The first parameter needs to be a .srr file.\n";
        echo "  -s 'file to store' (Save)\n";
        echo "  -d 'file to remove' (Delete)\n";
        echo "  -r 'file to rename' (Rename)\n";
        echo "  -v 'file to get' (View)\n";
        echo "  -x 'file to write' (eXtract)\n";
        echo "  -h 'special hash of the SRR file' (Hash)\n";
        echo "  -a 'show SRS info (sAmple)\n";
        echo "  -c 'compare two SRR files' (Compare)\n";
        echo "  -t 'runs a couple of small tests' (Testing)\n";
        exit(1);
    }
    $srr = $argv[1];

    // to test execution time
    $mtime = microtime();
    $mtime = explode(' ',$mtime);
    $mtime = $mtime[1] + $mtime[0];
    $starttime = $mtime;

    if (array_key_exists(2, $argv)) {
        $switch = $argv[2];
        if (array_key_exists(3, $argv)) {
            $file = $argv[3];
            switch($switch) {
                case '-d': // delete
                    if (removeFile($srr, $file)) {
                        echo 'File successfully removed.';
                    } else {
                        echo 'File not found in SRR file.';
                    }
                    break;
                case '-s': // store
                    $path = '';
                    if (array_key_exists(4, $argv)) {
                        $path = $argv[4];
                    }
                    if (storeFileCli($srr, $file, $path)) {
                        echo 'File successfully stored.';
                    } else {
                        echo 'Error while storing file.';
                    }
                    break;
                case '-r': // remove
                    if (array_key_exists(4, $argv)) {
                        $newName = $argv[4];
                        echo 'SRR file: ' . $srr . "\n";
                        echo 'Old name: ' . $file . "\n";
                        echo 'New name: ' . $newName . "\n";
                        if (renameFile($srr, $file, $newName)) {
                            echo 'File successfully renamed.';
                        } else {
                            echo 'Error while renaming file.';
                        }
                    } else {
                        echo 'Please enter a new name.';
                    }
                    break;
                case '-v': // view
                    print_r(getStoredFile($srr, $file));
                    break;
                case '-x': // extract
                    // strip the path info
                    $nopath = basename($file);
                    $result = file_put_contents($nopath, getStoredFile($srr, $file));
                    if ($result !== FALSE) {
                        echo 'File succesfully extracted';
                    } else {
                        echo 'Something went wrong. Did you provide a correct file name with path?';
                    }
                    break;
                case '-c': // compare
                    print_r(compareSrr($srr, $file));
                    break;
                default:
                    echo 'Unknown parameter. Use -r, -a, -v, -x or -c.';
            }
        } elseif ($switch === '-h') {
            echo 'The calculated content hash for this SRR file is: ';
            $result = processSrr($srr);
            echo calculateHash($srr, $result['rarFiles']);
        } elseif ($switch === '-a') {
            // show SRS info
            print_r(processSrsData(file_get_contents($srr)));
        } elseif ($switch === '-t') {
            echo 'fileNameCheckTest: ';
            if (fileNameCheckTest()) {
                echo "OK!\n";
            } else {
                echo "NOT OK!\n";
            }
            //compareSrr($srr, $srr);

            //$data = file_get_contents($srr);
            //print_r(processSrrData($data));
            //add file
            //storeFileCli($srr, 'dbmodel.png');

            //remove file
            //if(removeFile($srr, 'dbmodel.png')) {
            //    print_r("successfully removed");
            //}

            //process file
            if ($result = processSrr($srr)) {
                print_r($result);
                echo 'success';
            } else {
                echo 'failure';
            }
            
//             $sf = array_keys($result['storedFiles']);
//             sort($sf);
//             if (sortStoredFiles($srr, $sf)) {
//                 echo 'success';
//             } else {
//                 echo 'failure';
//             }

        }
    } else {
        $result = processSrr($srr);
        //print_r($result['storedFiles']);
        //print_r(($result['warnings']));
        //print_r(sortStoredFiles($result['storedFiles']));
        print_r($result);
    }

    // end part processing time
    $mtime = microtime();
    $mtime = explode(' ',$mtime);
    $mtime = $mtime[1] + $mtime[0];
    $endtime = $mtime;
    $totaltime = ($endtime - $starttime);
    echo "\nFile processed in {$totaltime} seconds";
}

// API functions
/**
 * Processes a whole SRR file and returns an array with useful details.
 * @param string $file location to the file that needs to be read.
 */
function processSrr($file) {
    $fh = fopen($file, 'rb');
    // file handle gets closed afterwards
    return processSrrHandle($fh, getFileSize($file));
}

/**
 * Processes a whole SRR file and returns an array with useful details.
 * @param bytes $srrFileData the contents of the SRR file.
 */
function processSrrData(&$srrFileData) {
    // http://www.php.net/manual/en/wrappers.php.php
    // Set the limit to 5 MiB. After this limit, a temporary file will be used.
    $memoryLimit = 5 * 1024 * 1024;
    $fp = fopen("php://temp/maxmemory:$memoryLimit", 'r+');
    fputs($fp, $srrFileData);
    rewind($fp);
    $fileAttributes = fstat($fp);
    return processSrrHandle($fp, $fileAttributes['size']);
}

/**
 * Closes the file handle.
 * Only used in the 2 functions above.
 */
function processSrrHandle($fileHandle, $srrSize) {
    // global $BLOCKNAME;
    $fh = $fileHandle;

    // variables to store all resulting data
    $appName = 'No SRR application name found';
    $stored_files = array();
    $rar_files = array();
    $archived_files = array();
    $oso_hashes = array();
    $recovery = NULL;
    $sfv = array();
    $sfv['comments'] = array();
    $sfv['files'] = array();
    $warnings = array();
    $compressed = FALSE; // it's an SRR file for compressed RARs

    // other initializations
    $read = 0; // number of bytes we have read so far
    $current_rar = NULL;

    while($read < $srrSize) {
        $add_size = TRUE;

        // to read basic block header
        $block = new Block($fh, $warnings);

        // echo 'Block type: ' . $BLOCKNAME[$block->blockType] . "\n";
        // echo 'Block flags: ' . dechex($block->flags) . "\n";
        // echo 'Header size: ' . $block->hsize . "\n";

        switch($block->blockType) {
            case 0x69: // SRR Header Block
                if ($appName !== 'No SRR application name found') {
                    array_push($warnings, 'Application name found in the middle of the SRR.');
                }
                $appName = $block->readSrrAppName();
                break;
            case 0x6B: // SRR OSO Hash (blocks at the end of the file)
                  $block->srrOsoHashFileHeader();
                $entry = array();
                $entry['fileName'] = $block->fileName;
                $entry['osoHash'] = $block->osoHash;
                $entry['fileSize'] = $block->fileSize;
                $entry['blockOffset'] = $block->startOffset;
                $entry['blockSize'] = $block->hsize;
                $entry['data'] = $block->data;
                array_push($oso_hashes, $entry);
                
                if (!is_null($current_rar)) {
                    $current_rar = NULL; // SRR block detected: start again
                }
                break;
            case 0x6A: // SRR Stored File Block
                $block->srrReadStoredFileHeader();

                // store stored file details
                $sf = array();
                $sf['fileName'] = $block->fileName;
                $sf['fileOffset'] = $block->storedFileStartOffset;
                $sf['fileSize'] = $block->addSize;
                $sf['blockOffset'] = $block->startOffset;

                // The same file can be stored multiple times.
                // This can make SRR files unnoticeably large.
                if (array_key_exists($block->fileName, $stored_files)) {
                    array_push($warnings, "Duplicate file detected! {$sf['fileName']}");
                }
                if (preg_match('/\\\\/', $block->fileName)) {
                    array_push($warnings, "Backslash detected! {$sf['fileName']}");
                }
                if ($block->addSize === 0) {
                    // an "empty" directory is allowed
                    if (strpos($sf['fileName'], '/') === FALSE) {
                        array_push($warnings, "Empty file detected! {$sf['fileName']}");
                    }
                } elseif (strtolower(substr($sf['fileName'], - 4)) === '.sfv') {
                    // we read the sfv file to grab the crc data of the rar files
                    $temp = processSfv(fread($fh, $block->addSize));
                    $sfv['comments'] = array_merge($sfv['comments'], $temp['comments']);
                    $sfv['files'] = array_merge($sfv['files'], $temp['files']);
                }

                $block->skipBlock();
                // calculate CRC of the stored file
                $sdata = getStoredFileDataHandle($fileHandle, $block->storedFileStartOffset, $block->addSize);
                $sf['fileCrc'] = strtoupper(dechex(crc32($sdata)));
                // $sf['fileCrc'] = dechex(crc32(fread($fh, $block->addSize)));
                // $sf['fileCrc'] = hash('crc32b', fread($fh, $block->addSize));

                $stored_files[$block->fileName] = $sf;
                // end file size counting (_should_ not be necessary for Stored File Block)
                // -> 'ReScene Database Cleanup Script 1.0' SRRs were fixed with 'FireScene Cleanup'
                // (stored files weren't before the first SRR Rar file block)
            case 0x71: // SRR Rar File
                if (!is_null($current_rar)) {
                    $current_rar = NULL; // SRR block detected: start again
                }
                // end fall through from SRR Stored File block
                if ($block->blockType == 0x6A) {
                    break;
                }

                $add_size = FALSE;

                // read the name of the stored rar file
                $block->srrReadRarFileHeader();
                $recovery_data_removed = $block->flags & 0x1;

                // the hashmap key is only the lower case file name without the path
                // to make it possible to add the CRC data from the SFVs
                $key = strtolower(basename($block->rarName));

                if (array_key_exists($key, $rar_files)) {
                    $f = $rar_files[$key];
                } else {
                    $f = array(); // array that stores the file details
                    $f['fileName'] = $block->rarName; // the path is still stored here
                    $f['fileSize'] = 0;
                    // when the SRR is build without SFV or the SFV is missing some lines
                    $f['fileCrc'] = 'UNKNOWN!';
                    // useful for actually comparing srr data
                    // $f['offsetStartSrr'] = $block->startOffset; // where the SRR block begins
                    $f['offsetStartRar'] = ftell($fh); // where the actual RAR headers begin
                }

                $rar_files[$key] = $f;

                // start counting file size
                $current_rar = $f;
                break;
            case 0x74: // RAR Packed File
                $block->rarReadPackedFileHeader();

                if (array_key_exists($block->fileName, $archived_files)) {
                    $f = $archived_files[$block->fileName];
                } else { // new file found in the archives
                    $f = array();
                    $f['fileName'] = $block->fileName;
                    $f['fileSize'] = $block->fileSize;
                    $f['fileTime'] = date("Y-m-d h:i:s", $block->fileTime);
                    $f['compressionMethod'] = $block->compressionMethod;
                }

                // check if compression was used
                if ($f['compressionMethod'] != 0x30) { // 0x30: Storing
                    $compressed = TRUE;
                }

                // CRC of the file is the CRC stored in the last archive that has the file
                // add leading zeros when the CRC isn't 8 characters
                $f['fileCrc'] = strtoupper(str_pad($block->fileCrc, 8, '0', STR_PAD_LEFT));
                $archived_files[$block->fileName] = $f;
                break;
            case 0x78: // RAR Old Recovery
                if (is_null($recovery)) {
                    // first recovery block we see
                    $recovery = array();
                    $recovery['fileName'] = 'Protect!';
                    $recovery['fileSize'] = 0;
                }
                $recovery['fileSize'] += $block->addSize;
                if ($recovery_data_removed) {
                    $block->skipHeader();
                } else { // we need to skip the data that is still there
                    $block->skipBlock();
                }
                break;
            case 0x7A: // RAR New Subblock: RR, AV, CMT
                $block->rarReadPackedFileHeader();
                if ($block->fileName === 'RR') { // Recovery Record
                    if (is_null($recovery)) {
                        $recovery = array();
                        $recovery['fileName'] = 'Protect+';
                        $recovery['fileSize'] = 0;
                    }
                    $recovery['fileSize'] += $block->addSize;
                    if (!$recovery_data_removed) {
                        $block->skipBlock();
                    }
                    break;
                } // other types have no data removed and will be fully skipped: fall through
            case 0x73: // RAR Volume Header
                // warnings for ASAP and IMMERSE -> crappy rars
                $ext = strtolower(substr($current_rar['fileName'], - 4));
                if (($block->flags & 0x0100) && $ext !== '.rar' && $ext !== '.001') {
                    array_push($warnings, "MHD_FIRSTVOLUME flag set for {$current_rar['fileName']}.");
                }
            case 0x72: // RAR Marker
            case 0x7B: // RAR Archive End
            case 0x75: // Old Comment
            case 0x76: // Old Authenticity
            case 0x77: // Old Subblock
            case 0x79: // Old Authenticity
                // no usefull stuff for us anymore: skip block and possible contents
                $block->skipBlock();
                break;
            default: // Unrecognized RAR/SRR block found!
                $block->skipBlock();
                if (!empty($current_rar['fileName'])) { // Psych.S06E02.HDTV.XviD-P0W4
                    // -> P0W4 cleared RAR archive end block: almost all zeros except for the header length field
                    array_push($warnings, "Unknown RAR block found in {$current_rar['fileName']}");
                } else { // e.g. a rar file that still has its contents
                    array_push($warnings, 'ERROR: Not a SRR file?');
                    return FALSE;
                    //trigger_error('Not a SRR file.', E_USER_ERROR);
                }
        }

        // calculate size of the rar file + end offset
        if (!is_null($current_rar)) {
            if ($add_size === TRUE) {
                $current_rar['fileSize'] += $block->fullSize;
            }
            // store end offset of the header data of the rar volume
            $current_rar['offsetEnd'] = ftell($fh);
            // keep the results updated
            $rar_files[strtolower(basename($current_rar['fileName']))] = $current_rar;
        }

        // nuber of bytes we have processed
        $read = ftell($fh);
    }

    fclose($fh); // close the file

    // add sfv CRCs to all the rar files we have found
    foreach ($sfv['files'] as $key => $val) {
        // the capitalization between sfv and the actual file isn't always the same
        $lkey = strtolower($key);
        if (array_key_exists($lkey, $rar_files)) {
            $rar_files[$lkey]['fileCrc'] = strtoupper($val);
            // everything that stays can not be reconstructed (subs from .sfv files)
            unset($sfv['files'][$key]); // remove data from $sfv
        }
    }

    // return all info in a multi dimensional array
    return array(
            'srrSize' => $srrSize,
            'appName' => $appName,
            'storedFiles' => $stored_files,
            'rarFiles' => $rar_files,
            'archivedFiles' => $archived_files,
            'osoHashes' => $oso_hashes,
            // Recovery Records across all archives in the SRR data
            // the name is based on the first encountered recovery block
            // Protect! -> old style RAR recovery (before RAR 3.0)
            // Protect+ -> new style RAR recovery
            'recovery' => $recovery,
            'sfv' => $sfv, // comments and files that aren't covered by the SRR
            'warnings' => $warnings, // when something unusual is found
            'compressed' => $compressed,
    );
}

/**
 * Returns the bytes of a stored file. (or any other part of the SRR file)
 * It makes use of the data returned in the above function.
 * @param $srrFile  The name of the SRR file to read.
 * @param $offset   The location where the stored file starts in the SRR file.
 * @param $length   The size of the stored file to read.
 * @return The bytes of the file.
 */
function getStoredFileData($srrFile, $offset, $length) {
    // string file_get_contents ( string $filename [, bool $use_include_path = FALSE
    //                              [, resource $context [, int $offset = -1 [, int $maxlen ]]]] )
    // http://php.net/manual/en/function.file-get-contents.php
    return file_get_contents($srrFile, FALSE, NULL, $offset, $length);
}

function getStoredFileDataHandle($fileHandle, $offset, $length) {
    return stream_get_contents($fileHandle, $length, $offset);
}

/**
 * Same as the getStoredFileData() function, but based on the file name.
 * @param $srrfile  The name of the SRR file to read.
 * @param $filename The file we want the contents from, including the path.
 * @return The bytes of the file.
 */
function getStoredFile($srrfile, $filename) {
    $srr = processSrr($srrfile);

    foreach($srr['storedFiles'] as $key => $value) {
        if($key === $filename) {
            return getStoredFileData($srrfile, $value['fileOffset'], $value['fileSize']);
        }
    }

    // // a faster approach for the fun of it:
    // $fh = fopen($srrfile, 'rb');
    // $sentinel = 0;
    // while ($sentinel < filesize($srrfile)) {
    //     $warnings_stub = array();
    //     $block = new Block($fh, $warnings_stub);
    //     $jump = $block->hsize + $block->addSize;
    //
    //     if ($block->blockType === 0x6A) { // a stored file block found
    //         $block->srrReadStoredFileHeader();
    //         if ($block->fileName === $filename) {
    //             return getStoredFileData($srrfile, $block->storedFileStartOffset, $block->addSize);
    //         }
    //         $block->skipBlock();
    //     } elseif ($block->blockType === 0x74 or $block->blockType === 0x78 ||
    //               ($block->blockType === 0x7A && $block->fileName === 'RR')) {
    //         // a rar packed file or recovery block that has its content removed
    //         $jump = $block->hsize;
    //         $block->skipHeader();
    //     } else {
    //         $block->skipBlock();
    //     }
    //     $sentinel += $jump;
    // }
}

/**
 * Removes a file stored in the SRR file.
 * @param   string  $srr        Path of the SRR file.
 * @param   string  $filename   Path and name of the file to remove.
 * @return TRUE on success, FALSE otherwise
 */
function removeFile($srr, $filename) {
    $result = processSrr($srr);

    foreach ($result['storedFiles'] as $key => $value) {
        if ($value['fileName'] === $filename) {
            // how much to remove? read the block starting from the offset
            $fh = fopen($srr, 'rb');
            $before = fread($fh, $value['blockOffset']);
            $warnings_stub = array();
            $block = new Block($fh, $warnings_stub);
            fseek($fh, $value['blockOffset'] + $block->fullSize, SEEK_SET);
            $after = fread($fh, $result['srrSize']); // srrSize: the (max) amount to read
            fclose($fh);
            file_put_contents($srr, $before . $after, LOCK_EX);
            return TRUE;
        }
    }
    return FALSE;
}

/**
 * Adds a file to the saved files inside a SRR file.
 * @param string    $srr    The path of the SRR file.
 * @param string    $file   The file to store.
 * @param bytes     $path   The path that must be prefixed for the file name.
 * @return TRUE on success, FALSE otherwise.
 */
function storeFileCli($srr, $file, $path='') {
    // the path must have the path separator included
    if ($path != '' && substr($path, -1) !== '/') {
        return FALSE;
    }
    $fileContents = file_get_contents($file);
    return storeFile($srr, $path . basename($file), $fileContents);
}

/**
 * Adds a file to the saved files inside a SRR file.
 * @param string    $srr        The path of the SRR file.
 * @param string    $filePath   The path and name that will be stored.
 * @param bytes     $fdata      The bytes of the file to store in the SRR file.
 * @return TRUE when storing succeeds.
 */
function storeFile($srr, $filePath, $fdata) {
    // check for illegal windows characters
    // the path separator must be /
    // twice (//) may not be possible
    if (fileNameCheck($filePath)) {
        return FALSE;
    }
    // TODO: it is possible that you only have a path/

    // don't let the same file get added twice
    $result = processSrr($srr);
    foreach($result['storedFiles'] as $key => $value) {
        if($key === $filePath) {
            return FALSE;
        }
    }

    $offset = newFileOffset($srr);
    if ($offset < 0) {
        return FALSE;
    }

    $fh = fopen($srr, 'rb');
    $before = fread($fh, $offset);
    $after = fread($fh, getFileSize($srr));
    fclose($fh);

    $header = createStoredFileHeader($filePath, strlen($fdata));
    file_put_contents($srr, $before . $header . $fdata . $after, LOCK_EX);
    return TRUE;
}

function addOsoHash($srr, $oso_hash_data) {
    // the hash must not already exist
    $result = processSrr($srr);
    foreach($result['osoHashes'] as $value) {
        if ($value['data'] == $oso_hash_data) {
            return FALSE;
        }
    }
    
    $orig_data = file_get_contents($srr);
    file_put_contents($srr, $orig_data . $oso_hash_data, LOCK_EX);
}

// /**
//  * Adds a new OSO hash to the end of the SRR file.
//  * 
//  * @param string $srr
//  * @param int $fileSize
//  * @param string $osoHash
//  * @param string $fileName
//  */
// function addOsoHash($srr, $fileSize, $osoHash, $fileName) {
//     // check for illegal windows characters; no paths
//     if (fileNameCheck($fileName) || strstr($fileName, '/')) {
//         return FALSE;
//     }
//     if ($fileSize < 0 || !preg_match('/[a-f0-9]{16}/i', $osoHash) || strlen($fileName) < 1) {
//         return FALSE;
//     }
    
//     // the hash must not already exist
//     $result = processSrr($srr);
//     foreach($result['osoHashes'] as $value) {
//         if ($value['fileName'] == $fileName &&
//             $value['fileSize'] == $fileSize &&
//             $value['osoHash'] == $osoHash) {
//             return FALSE;
//         }
//     }
    
//     $fh = fopen($srr, 'rb');
//     $before = fread($fh, getFileSize($srr));
//     fclose($fh);
    
//     // 2 byte CRC, 1 byte block type, 2 bytes for the flag 0x0000
//     $header = pack('H*' , '6B6B6B0000');
    
//     $osoBlockHeader = encode_int($fileSize); // broken on 32 bit!!
//     // OSO hash stored as little endian
//     $reversed = '';
//     for($i=strlen($osoHash);$i>=0;$i-=2) {
//         $reversed .= substr($osoHash, $i, 2);
//     }
//     $osoBlockHeader .= pack('H*' , $reversed);
//     $osoBlockHeader .= pack('v', strlen($fileName));
//     $osoBlockHeader .= $fileName;
//     $headerSize = pack('v', 5 + 2 + 8 + 8 + 2 + strlen($fileName));

//     print_r(unpack('H*', $header . $headerSize . $osoBlockHeader));
//     //file_put_contents($srr, $before . $header . $headerSize . $osoBlockHeader, LOCK_EX);
//     return TRUE;
// }

// function encode_int($in, $pad_to_bits=64, $little_endian=true) {
//     $in = decbin($in);
//     $in = str_pad($in, $pad_to_bits, '0', STR_PAD_LEFT);
//     $out = '';
//     for ($i = 0, $len = strlen($in); $i < $len; $i += 8) {
//         $out .= chr(bindec(substr($in,$i,8)));
//     }
//     if($little_endian) $out = strrev($out);
//     return $out;
// }

/**
 * Renames a stored file.
 * @param string $srr     The path of the SRR file.
 * @param string $oldName The path and file name of a stored file.
 * @param string $newName The new path and file name of a stored file.
 * @return TRUE on success, FALSE otherwise.
 */
function renameFile($srr, $oldName, $newName) {
    if (fileNameCheck($newName)) {
        print_r("The new file name is illegal. Use only forward slashes for paths.\n");
        return FALSE;
    }
    $result = processSrr($srr);

    // prevent renaming to a file that already exists
    foreach ($result['storedFiles'] as $key => $value) {
        if ($key === $newName) {
            return FALSE;
        }
    }

    foreach ($result['storedFiles'] as $key => $value) {
        if ($value['fileName'] === $oldName) {
            $fh = fopen($srr, 'rb');
            $before = fread($fh, $value['blockOffset']);
            $warnings_stub = array();
            $block = new Block($fh, $warnings_stub);
            $block->srrReadStoredFileHeader();
            fseek($fh, $value['blockOffset'] + $block->hsize, SEEK_SET);
            $after = fread($fh, $result['srrSize']); // srrSize: the (max) amount to read
            fclose($fh);

            // allow an ending on / only for empty files -> srr crashes
            if (substr($newName, - 1) === '/') { // && $block->addSize > 0) {
                return FALSE;
            }

            $changedHeader = createStoredFileHeader($newName, $block->addSize);
            file_put_contents($srr, $before . $changedHeader . $after, LOCK_EX);
            return TRUE;
        }
    }
    return FALSE;
}

/**
 * Calculate hash to identify SRRs that cover the same RAR volumes.
 * @param string $srr The SRR file.
 * @param array $rarFiles The resulting array from processSrr().
 * @return Sha1 hash of the srr file
 */
function calculateHash($srr, $rarFiles, $algorithm='sha1') {
    // do the calculation only on the sorted RAR volumes
    // this way it still yields the same result if the order of creation differs
    uasort($rarFiles, 'rarFileCmp'); // sort on filename without path, case insensitive
    // compared with pyReScene when capitals are used: same behavior
    // Parlamentet.S06E02.SWEDiSH-SQC
    $hashContext = hash_init($algorithm);

    // calculate hash only on the RAR metadata
    foreach ($rarFiles as $key => $value) {
        $start = $value['offsetStartRar'];
        $end = $value['offsetEnd'];
        $data = getStoredFileData($srr, $start, ($end - $start));
        hash_update($hashContext, $data);
    }
    return hash_final($hashContext);
}

// Comparison function
function rarFileCmp($a, $b) {
    if ($a['fileName'] == $b['fileName']) {
        return 0;
    }
    return (strtolower($a['fileName']) < strtolower($b['fileName'])) ? -1 : 1;
}

function calculateHashHandle($srrHandle, $rarFiles, $algorithm='sha1') {
    // do the calculation only on the sorted RAR volumes
    // this way it still yields the same result if the order of creation differs
    asort($rarFiles); // Sort an array and maintain index association
    $hashContext = hash_init($algorithm);

    // calculate hash only on the RAR metadata
    foreach ($rarFiles as $key => $value) {
        echo $key;
        $start = $value['offsetStartRar'];
        $end = $value['offsetEnd'];
        $data = getStoredFileDataHandle($srrHandle, $start, ($end - $start));
        hash_update($hashContext, $data);
    }
    return hash_final($hashContext);
}

function calculateHashString($srrData, $rarFiles, $algorithm='sha1') {
    // do the calculation only on the sorted RAR volumes
    // this way it still yields the same result if the order of creation differs
    asort($rarFiles);
    $hashContext = hash_init($algorithm);

    // calculate hash only on the RAR metadata
    foreach ($rarFiles as $key => $value) {
        echo $key;
        $start = $value['offsetStartRar'];
        $end = $value['offsetEnd'];

        $memoryLimit = 5 * 1024 * 1024;
        $fp = fopen("php://temp/maxmemory:$memoryLimit", 'r+');
        fputs($fp, $srrData);
        rewind($fp);
        $fileAttributes = fstat($fp);

        $data = getStoredFileDataHandle($fp, $start, ($end - $start));
        hash_update($hashContext, $data);
    }
    return hash_final($hashContext);
}


/**
 * Compare 2 SRR files and list the differences.
 * @param $one First SRR file.
 * @param $two Second SRR file.
 * @return Some complicated array with differences.
 */
function compareSrr($one, $two) {
    $rone = processSrr($one);
    $rtwo = processSrr($two);
    return compareSrrRaw($rone, $rtwo, $one, $two);
}

/**
 * Same as above, but the info arrays of the SRR files were read before.
 * 2 times less parsing of the SRR files.
 */
function compareSrrRaw($rone, $rtwo, $one, $two) {
    $hashOne = calculateHash($one, $rone['rarFiles']);
    $hashTwo = calculateHash($two, $rtwo['rarFiles']);

    // ----- The RARs -----
    // rebuild data can be considered the same?
    $sameRarData = $hashOne === $hashTwo;

    // hash => file name
    $hashesOne = hashParts($one, $rone['rarFiles']);
    $hashesTwo = hashParts($two, $rtwo['rarFiles']);

    // hash => file name (of those names unique to the first array)
    $left = array_diff($hashesOne, $hashesTwo);
    $right = array_diff($hashesTwo, $hashesOne);

    if ($sameRarData && count(array_merge($left, $right)) === 0) {
        $sameRarNames = TRUE;
    } else {
        $sameRarNames = FALSE;
        // must be picked in the comparison as the other one doesn't have it
        $uniqueRarOne = array_values(array_diff_key($hashesOne, $hashesTwo));
        $uniqueRarTwo = array_values(array_diff_key($hashesTwo, $hashesOne));

        // of the ones that are the same, the best name should be picked by default
        $twiceHash = array_keys(array_intersect_key($left, $right));
        $namesRarOne = array();
        $namesRarTwo = array();

        foreach ($twiceHash as $value) {
            $l = $left[$value];
            $r = $right[$value];

            // heuristic: we want the one with the longest length
            // this one probably has a path added
            if (strlen($l) > strlen($r)) {
                array_push($namesRarOne, $l);
            } else {
                array_push($namesRarTwo, $r);
            }
        }
    }

    // ----- The stored files -----
    // we compare .nfo, .sfv, .srs and other files to check if they are the same
    // or not a notewhorthy difference (line endings, sfv comments, ...)
    // if they are the same, only the filename/path needs to be chosen
    $filesOne = $rone['storedFiles'];
    $filesTwo = $rtwo['storedFiles'];

    // same name, same data => OK
    // different name, same data => one of both probably has a bad name (paths should always be the same for nfos)
    $same = array(); // list of tuples (fileOne, fileTwo, best) (because they can have different names)
    $sameName = array(); // same name, different data => e.g. Mr.X and Mr.Y sitescripts banner added for NFOs
    // suggest the largest file?

    // different name, different data => nfos from fixes ect.
    $uniqueOne = $filesOne;
    $uniqueTwo = $filesTwo;


    // *** NFO ***
    $oneNfo = getFilesByExt($filesOne, '.nfo');
    $twoNfo = getFilesByExt($filesTwo, '.nfo');
    // do not process these files again
    // Returns an array containing all the values from array1 that are not present in any of the other arrays.
    $filesOne = array_diff_assoc($filesOne, $oneNfo);
    $filesTwo = array_diff_assoc($filesTwo, $twoNfo);
    $oneNfo = addNfoHash($oneNfo, $one);
    $twoNfo = addNfoHash($twoNfo, $two);

    foreach ($oneNfo as $okey => $ovalue) {
        foreach ($twoNfo as $tkey => $tvalue) {
            $toUnset = FALSE;
            if ($ovalue['hash'] === $tvalue['hash']) {
                array_push($same, array($okey, $tkey,
                'lines1' => $ovalue['lines'], 'lines2' => $tvalue['lines']));
                $toUnset = TRUE;
            } elseif ($ovalue['fileName'] === $tvalue['fileName']) {
                // suggest the largest NFO file
                if ($ovalue['fileSize'] > $tvalue['fileSize']) {
                    $best = 0;
                } else {
                    $best = 1;
                }
                array_push($sameName, array($okey, $tkey, 'best' => $best,
                'lines1' => $ovalue['lines'], 'lines2' => $tvalue['lines']));
                $toUnset = TRUE;
                // TODO: show text diff?
            }
            if ($toUnset) {
                // remove from the array
                unset($uniqueOne[$okey]);
                unset($uniqueTwo[$tkey]);
            }
        }
    }

    // *** SFV ***
    $oneSfv = getFilesByExt($filesOne, '.sfv');
    $twoSfv = getFilesByExt($filesTwo, '.sfv');
    // do not process these files again
    $filesOne = array_diff_assoc($filesOne, $oneSfv);
    $filesTwo = array_diff_assoc($filesTwo, $twoSfv);
    $oneSfv = addSfvInfo($oneSfv, $one);
    $twoSfv = addSfvInfo($twoSfv, $two);

    foreach ($oneSfv as $okey => $ovalue) {
        foreach ($twoSfv as $tkey => $tvalue) {
            $toUnset = FALSE;
            if ($ovalue['files'] === $tvalue['files']) {
                // suggest the SFV file with the most comments
                if (count($ovalue['comments']) > count($tvalue['comments'])) {
                    $best = 0;
                } elseif (count($ovalue['comments']) < count($tvalue['comments'])) {
                    $best = 1;
                } else {
                    // SFV with the longest file name has probably path info
                    if (strlen($ovalue['fileName']) > strlen($tvalue['fileName'])) {
                        $best = 0;
                    } else {
                        $best = 1;
                    }
                }
                array_push($same, array($okey, $tkey, 'best' => $best));
                $toUnset = TRUE;
            } elseif ($ovalue['fileName'] === $tvalue['fileName']) {
                array_push($sameName, array($okey, $tkey));
                $toUnset = TRUE;
            }
            if ($toUnset) {
                unset($uniqueOne[$okey]);
                unset($uniqueTwo[$tkey]);
            }
        }
    }

    // *** SRS ***
    $oneSrs = getFilesByExt($filesOne, '.srs');
    $twoSrs = getFilesByExt($filesTwo, '.srs');
    // do not process these files again
    $filesOne = array_diff_assoc($filesOne, $oneSrs);
    $filesTwo = array_diff_assoc($filesTwo, $twoSrs);
    $oneSrs = addSrsInfo($oneSrs, $one);
    $twoSrs = addSrsInfo($twoSrs, $two);

    //print_r($oneSrs);
    //print_r($twoSrs);
    foreach ($oneSrs as $okey => $ovalue) {
        foreach ($twoSrs as $tkey => $tvalue) {
            $toUnset = FALSE;
            // sample name and crc32 must be the same to be the same sample
            if ($ovalue['fileData']->name === $tvalue['fileData']->name &&
                    $ovalue['fileData']->crc32 === $tvalue['fileData']->crc32) {
                // checked against main movie file
                if ($ovalue['trackData'][1]->matchOffset === $tvalue['trackData'][1]->matchOffset) {
                    // equal enough
                    array_push($same, array($okey, $tkey));
                    $toUnset = TRUE;
                } else {
                    // -c parameter difference
                    // indicate which one had the -c parameter used
                    if ($ovalue['trackData'][1]->matchOffset != 0) {
                        $best = 0;
                    } elseif ($tvalue['trackData'][1]->matchOffset != 0) {
                        $best = 1;
                    } else {
                        // suggest longest file name
                        if (strlen($ovalue['fileName']) > strlen($tvalue['fileName'])) {
                            $best = 0;
                        } else {
                            $best = 1;
                        }
                    }
                    array_push($sameName, array($okey, $tkey, 'best' => $best));
                    $toUnset = TRUE;
                }
            }
            if ($toUnset) {
                unset($uniqueOne[$okey]);
                unset($uniqueTwo[$tkey]);
            }
        }
    }

    // *** OTHER ***
    foreach ($filesOne as $okey => $ovalue) {
        foreach ($filesTwo as $tkey => $tvalue) {
            $toUnset = FALSE;
            // same CRC: exactly the same
            if ($ovalue['fileCrc'] === $tvalue['fileCrc']) {
                array_push($same, array($okey, $tkey));
                $toUnset = TRUE;
                // they only have the same name
            } elseif ($ovalue['fileName'] === $tvalue['fileName']) {
                array_push($sameName, array($okey, $tkey));
                $toUnset = TRUE;
            }
            if ($toUnset) {
                unset($uniqueOne[$okey]);
                unset($uniqueTwo[$tkey]);
            }
        }
    }

    $result = array(
            'sameRarData' => $sameRarData,
            'sameRarNames' => $sameRarNames,

            'same' => $same,
            'sameName' => $sameName,
            'uniqueOne' => array_keys($uniqueOne),
            'uniqueTwo' => array_keys($uniqueTwo),
    );
    if (!$sameRarNames) {
        // these 4 lists cover all unique RAR metadata
        $result = array_merge($result, array(
                'uniqueRarOne' => $uniqueRarOne, // RAR files that are new
                'uniqueRarTwo' => $uniqueRarTwo,
                'namesRarOne' => $namesRarOne, // the RAR names that are better (when content is the same)
                'namesRarTwo' => $namesRarTwo, // these should be picked by default when mergeing
        ));
    }
    return $result;
}

function getFilesByExt($fileList, $extention) {
    $result = array();

    foreach ($fileList as $key => $value) {
        if (strtolower(substr($value['fileName'], - 4)) === $extention) {
            $result[$key] = $value;
        }
    }
    return $result;
}

function addNfoHash($list, $srrFile) {
    foreach($list as $key => $value) {
        // store nfo hash next to the other stored file data
        $nfoData = getStoredFileData($srrFile, $value['fileOffset'], $value['fileSize']);
        $list[$key]['hash'] = nfoHash($nfoData);
        // check for which nfo has the fewest lines -> probably no unnessesary white lines
        // Indiana.Jones.And.The.Last.Crusade.1989.PAL.DVDR-DNA
        $list[$key]['lines'] = count(explode("\n", $nfoData));
    }
    return $list;
}

function addSfvInfo($list, $srrFile) {
    foreach($list as $key => $value) {
        $result = processSfv(getStoredFileData($srrFile, $value['fileOffset'], $value['fileSize']));
        $list[$key]['comments'] = $result['comments'];
        $list[$key]['files'] = $result['files'];
    }
    return $list;
}

function addSrsInfo($list, $srrFile) {
    foreach($list as $key => $value) {
        $result = processSrsData(getStoredFileData($srrFile, $value['fileOffset'], $value['fileSize']));
        //print_r($result);
        $list[$key] += $result;
    }
    return $list;
}

function nfoHash($nfoData) {
    // ignore all new lines
    $string = preg_replace("/(\r\n|\r|\n)/", '', $nfoData);
    // trailing whitespace can be stripped sometimes too
    $string = rtrim($string);
    return md5($string);
}

/**
 * Merge two SRR files by selecting the wanted data parts from each of them.
 * @param $one First SRR file.
 * @param $two Second SRR file.

 */
function mergeSrr($one, $two, $storeOne, $storeTwo, $rarOne, $rarTwo, $result) {
    $rone = processSrr($one);
    $rtwo = processSrr($two);




}

function processSrsData($srsFileData) {
    // http://www.php.net/manual/en/wrappers.php.php
    // Set the limit to 5 MiB. After this limit, a temporary file will be used.
    $memoryLimit = 5 * 1024 * 1024;
    $fp = fopen("php://temp/maxmemory:$memoryLimit", 'r+');
    fputs($fp, $srsFileData);
    rewind($fp);
    $fileAttributes = fstat($fp);
    return processSrsHandle($fp, $fileAttributes['size']);
}

/**
 * Parses an SRS file.
 * @param $fileHandle
 * @param int $srsSize
 * @return info array
 */
function processSrsHandle($fileHandle, $srsSize) {
    switch(detectFileFormat($fileHandle)) {
        case FileType::AVI:
            $result = parse_srs_avi($fileHandle, $srsSize);
            break;
        case FileType::MKV:
            $result = parse_srs_mkv($fileHandle, $srsSize);
            break;
        case FileType::MP4:
            $result = parse_srs_mp4($fileHandle, $srsSize);
            break;
        case FileType::WMV:
            $result = parse_srs_wmv($fileHandle, $srsSize);
            break;
        default:
            echo 'SRS file type not detected';
    }
    fclose($fileHandle);
    return $result;
}

/**
 * Sorts the stored files in $srr according to $sortedFileNameList.
 * @param string $srr: path to the SRR file
 * @param array $sortedFileNameList: simple array with file names
 * @return bool success status
 */
function sortStoredFiles($srr, $sortedFileNameList) {
    $srrInfo = processSrr($srr);
    if (count($srrInfo['storedFiles']) != count($sortedFileNameList)) {
        // not the same amount of elements: bad input
        return FALSE;
    }
    
    $before = $srrInfo['srrSize'];
    $after = 0;
    // check if each name is the same in both lists
    foreach ($srrInfo['storedFiles'] as $key => $value) {
        if (array_search($key, $sortedFileNameList) === FALSE) {
            return FALSE;
        }
        
        // offsets where the stored files start and end
        if ($value['blockOffset'] < $before) {
            $before = $value['blockOffset'];
        }
        $offset = $value['fileOffset'] + $value['fileSize'];
        if ($offset > $after) {
            $after = $offset;
        }
    }
    
    $fh = fopen($srr, 'rb');
    $beforeData = fread($fh, $before);
    fseek($fh, $after, SEEK_SET);
    $afterData = fread($fh, $srrInfo['srrSize']); // srrSize: the (max) amount to read
    
    // sort the files and grab their blocks
    $between = ''; 
    foreach ($sortedFileNameList as $key) {
        $bo = $srrInfo['storedFiles'][$key]['blockOffset'];
        $fo = $srrInfo['storedFiles'][$key]['fileOffset'];
        $fs = $srrInfo['storedFiles'][$key]['fileSize'];
        $blockSize = ($fo + $fs) - $bo;
        fseek($fh, $bo, SEEK_SET);
        $between .= fread($fh, $blockSize);
    }
    fclose($fh);
    $amount = file_put_contents($srr, $beforeData . $between . $afterData, LOCK_EX);
    assert($amount === $srrInfo['srrSize']);
    
    return TRUE;
}

// Private helper functions -------------------------------------------------------------------------------------------

function getFileSize($file) {
    $fh = fopen($file, 'rb');
    // PHP uses caching for filesize() and we do not always want that!
    $stat = fstat($fh);
    fclose($fh);
    return $stat['size'];
}

function isFolder($dir) {
    return (strpos($dir, '/', 1) !== FALSE);
}

/**
 * No illegal Windows characters.
 * No \ as path separator.
 * No // (double forward slashes).
 * The string cannot start with a /.
 * The string must contain at least one character.
 * The string cannot start or end with a space.
 */
function fileNameCheck($path) {
    return preg_match('/([\\\\:*?"<>|]|\/\/)|^\/|^$|^ .*|^.* $/', $path);
}

function fileNameCheckTest() {
    return (!fileNameCheck('ok.ext') &&
            fileNameCheck('dir\file.ext') &&
            fileNameCheck('dir/file:file.ext') &&
            fileNameCheck('dir/file*.ext') &&
            fileNameCheck('dir/file?.ext') &&
            fileNameCheck('dir/file".ext') &&
            fileNameCheck('dir/file<.ext') &&
            fileNameCheck('dir/file>.ext') &&
            fileNameCheck('dir/file|.ext') &&
            fileNameCheck('dir//file.ext') &&
            fileNameCheck('dir\\\\file.ext') &&
            fileNameCheck('/dir/file.ext') &&
            fileNameCheck('') &&
            fileNameCheck('dir\\file.ext') &&
            fileNameCheck(' dir/file.ext') &&
            fileNameCheck('dir/file.ext '));
}

/**
 * Hash all RAR metadata parts of a SRR file.
 * @param $srr The SRR file.
 * @param $rarFiles Subarray result from processSrr().
 */
function hashParts($srr, $rarFiles) {
    $hashes = array();
    foreach($rarFiles as $key => $value) {
        $start = $value['offsetStartRar'];
        $end = $value['offsetEnd'];
        $hash = sha1(getStoredFileData($srr, $start, ($end - $start)));
        $hashes[$hash] = $value['fileName'];
    }
    return $hashes;
}

/**
 * Construct the header of a SRR stored file block.
 * @param string $name The path (including file name) of the file to store.
 * @param int $fileSize The size of the stored file.
 */
function createStoredFileHeader($name, $fileSize) {
    // 2 byte CRC, 1 byte block type, 2 bytes for the flag 0x8000: addsize field is present
    $header = pack('H*' , '6A6A6A0080');
    $addSize = pack('V', $fileSize);
    $pathLength = pack('v', strlen($name));
    $headerSize = pack('v', 5 + 2 + 4 + 2 + strlen($name));
    return $header . $headerSize . $addSize . $pathLength . $name;
}

/**
 * We choose the offset to insert a new file to be after the SRR Header Block
 * to keep all files always at the front and to anticipate new SRR blocks.
 * @param string $srr   The path of the SRR file to open.
 */
function newFileOffset($srr) {
    $fh = fopen($srr, 'rb');
    // read SRR Header Block
    $warnings_stub = array();
    $block = new Block($fh, $warnings_stub);
    if ($block->blockType === 0x69) {
        $block->readSrrAppName();
    } else {
        return -1;
    }

    $offset = ftell($fh);
    fclose($fh);
    return $offset;
}

/**
 * Returns an array with comments and files
 * @param $data Binary datastream of SFV file.
 */
function processSfv($data) {
    // create array of all the lines
    $lines = explode("\n", $data);
    $result = array();
    $result['comments'] = array();
    $result['files'] = array();

    for ($i=0; $i < count($lines); $i++) {
        $line = trim($lines[$i]);
        $lineLength = strlen($line);

        // process if line has contents
        if ($lineLength > 0) {
            // the line is a comment line or it is too short
            if (in_array($line[0], array(';')) or $lineLength < 10) {
                array_push($result['comments'], $line);
            } else {
                // parse SFV line
                $spaceIndex = strrpos($line, ' ');
                $fileName = substr($line, 0, $spaceIndex);
                // TODO: A sfv file can contain multiple spaces in between
                // TODO: the crc isn't always 8 chars
                $result['files'][$fileName] = substr($line, $spaceIndex + 1, 8);
            }
        }
    }

    // print_r($result);
    return $result;
}

/**
 * Converts MS DOS timestamp to something usable.
 * DosDateTimeToFileTime()
 * http://msdn.microsoft.com/en-us/library/ms724247(v=vs.85).aspx
 * @returns date in unix time
 */
function parseDosTime($dword) {
    $second = ($dword & 0x1F) * 2;
    $dword = $dword >> 5;
    $minute = $dword & 0x3F;
    $dword = $dword >> 6;
    $hour = $dword & 0x1F;
    $dword = $dword >> 5;
    $day = $dword & 0x1F;
    $dword = $dword >> 5;
    $month = $dword & 0x0F;
    $dword = $dword >> 4;
    $year = ($dword & 0x7F) + 1980;
    return mktime($hour, $minute, $second, $month, $day, $year);
}


/**
 * A RAR or SRR block used for reading all header fields.
 */
class Block {
    /**
     * The constructor initializes a RAR block by reading the the basic 7 byte
     * header fields. It checks if there is content after the block header.
     * @param   open file handle
     */
    public function __construct($fileHandle, &$warnings) {
        $this->fh = $fileHandle;
        $this->startOffset = ftell($fileHandle); // current location in the file
        $this->warnings = &$warnings;

        // reading basic 7 byte header block
        $array = unpack('vheaderCrc/CblockType/vflags/vheaderSize', fread($this->fh, 7));
        $this->headerCrc = $array['headerCrc'];
        $this->blockType = $array['blockType'];
        $this->flags = $array['flags'];
        $this->hsize = $array['headerSize'];
        $this->addSize = 0; // size of data after the header

        // check if block contains additional data
        $addSizeFlag = $array['flags'] & 0x8000;
        if ($addSizeFlag || ($array['blockType'] === 0x74) || ($array['blockType'] === 0x7A)) {
            // The BiA guys need some bitch slapping first:
            // they don't set the 0x8000 flag for RAR file blocks.
            if (!$addSizeFlag) {
                array_push($warnings, 'LONG_BLOCK flag (0x8000) not set for RAR File block (0x74).');
            }
            $array = unpack('VaddSize', fread($this->fh, 4));
            $this->addSize = $array['addSize'];
        }

        // only used to calculate the full size of a rar file
        // size header + size stored content
        // this content is removed for RAR blocks
        $this->fullSize = $this->hsize + $this->addSize;

        // -- check CRC of block header --
        $offset = ftell($this->fh);
        fseek($this->fh, $this->startOffset + 2, SEEK_SET);
        $crcData = fread($this->fh, $this->hsize - 2);
        // only the 4 lower order bytes are used
        $crc = crc32($crcData) & 0xffff;
        // igonore blocks with no CRC set (same as twice the blockType)
        if ($crc !== $this->headerCrc && $this->headerCrc !== 0x6969 // SRR Header
                && $this->headerCrc !== 0x6a6a // SRR Stored File
                && $this->headerCrc !== 0x6b6b // SRR OSO Hash
                && $this->headerCrc !== 0x7171 // SRR RAR block
                && $this->blockType !== 0x72 // RAR marker block (fixed: magic number)
        ) {
            // it can not fail here for releases such as Haven.S02E05.HDTV.XviD-P0W4
            global $BLOCKNAME;
            array_push($warnings, 'ERROR: Invalid block header CRC found: header is corrupt. (' .
                    $BLOCKNAME[$this->blockType] . ', ' . $offset . ')');
        }
        // set offset back to where we started from
        fseek($this->fh, $offset, SEEK_SET);
    }

    /**
     * Reads the additional fields for a SRR Header Block.
     * @return  string  Name of the application used to create the SRR file.
     */
    function readSrrAppName() {
        if ((dechex($this->flags) & 1)) {
            // read 2 fields after basic header block
            $length = unpack('vnamelength', fread($this->fh, 2));
            return fread($this->fh, $length['namelength']);
        } else {
            return ""; // there isn't an application name stored
        }
    }

    /**
     * Reads the additional fields for a SRR Stored File Block.
     */
    function srrReadStoredFileHeader() {
        $array = unpack('vlength', fread($this->fh, 2));
        if ($array['length'] !== 0) {
            $this->fileName = fread($this->fh, $array['length']);
        } else {
            array_push($this->warnings, 'Stored file with no name detected!');
            $this->fileName = "";
        }
        $this->storedFileStartOffset = ftell($this->fh);

        // skip possible (future) fields to start file
        $this->skipHeader();
    }
    
    /**
     * Reads the OpenSubtitles.org Hashes.
     */
    function srrOsoHashFileHeader() {
        // FILE SIZE
        $file_size = unpack('Vlow/Vhigh', fread($this->fh, 8));
        // add the high order bits before the low order bits and convert to decimal
        $lowhex = str_pad(dechex($file_size['low']), 8, '0', STR_PAD_LEFT);
        $highhex = dechex($file_size['high']);
        $this->fileSize = hexdec($highhex . $lowhex);
        
        // OSO HASH
        $oso_hash = unpack('Vlow/Vhigh', fread($this->fh, 8));
        // add the high order bits before the low order bits and convert to decimal
        $lowhex = str_pad(dechex($oso_hash['low']), 8, '0', STR_PAD_LEFT);
        $highhex = dechex($oso_hash['high']);
        $this->osoHash = $highhex . $lowhex;
        
        // FILE NAME
        $array = unpack('vnameSize', fread($this->fh, 2));
        $this->fileName = fread($this->fh, $array['nameSize']);
        
        // skip possible (future) fields
        fseek($this->fh, $this->startOffset, SEEK_SET);
        $this->data = fread($this->fh, $this->hsize);
    }

    /**
     * Reads the additional fields for a SRR block that indicates
     * that RAR blocks are following.
     */
    function srrReadRarFileHeader() {
        $length = unpack('vlength', fread($this->fh, 2));
        if ($length['length'] !== 0) {
            $this->rarName = fread($this->fh, $length['length']);
        } else {
            array_push($this->warnings, 'RAR file with no name detected!');
            $this->rarName = "";
        }
    }

    /**
     * Reads the additional fields for a RAR file block.
     */
    function rarReadPackedFileHeader() {
        $array = unpack('Vus/Cos/VfileCrc/VfileTime/CunpackVersion/Cmethod/vnameSize/Vattr',
                fread($this->fh, 21));
        // $this->packSize = $this->addSize
        // $this->unpackedSize = $array['us'];
        $this->fileSize = $array['us'];
        $this->fileCrc = dechex($array['fileCrc']);
        // $this->os = $array['os'];
        $this->fileTime = parseDosTime($array['fileTime']);
        // $this->unpackVersion = $array['unpackVersion'];
        $this->compressionMethod = $array['method'];
        // $this->fileAttributes = $array['attr'];

        if ($this->flags & 0x100) {
            $high = unpack('VhighPackSize/VhighUnpackSize', fread($this->fh, 8));
            // $this->highPackSize = $high['highPackSize'];
            // $this->highUnpackSize = $high['highUnpackSize'];
            // add the high order bits before the low order bits and convert to decimal
            $lowhex = str_pad(dechex($array['us']), 8, '0', STR_PAD_LEFT);
            $highhex = dechex($high['highUnpackSize']);
            $this->fileSize = hexdec($highhex . $lowhex);
        }

        // only grab the ascii representation of the name
        $fname = explode('\0', fread($this->fh, $array['nameSize']), 1);
        $this->fileName = $fname[0];

        // salt and extra time fields are here and not interesting
        $this->skipHeader();
    }

    /**
     * Set the file handle cursor at the end of the header.
     * Data that follows can be a next block or a stored file.
     */
    function skipHeader() {
        // skip whole header of the block
        fseek($this->fh, $this->startOffset + $this->hsize, SEEK_SET);
    }

    /**
     * Sets file cursor to the next block based on the values in the header!
     */
    function skipBlock() {
        fseek($this->fh, $this->startOffset + $this->hsize + $this->addSize, SEEK_SET);
    }
}

function detectFileFormat($fileHandle) {
    $ft = FileType::Unknown;
    $firstBytes = strtoupper(bin2hex(fread($fileHandle, 4)));

    switch($firstBytes) {
        case '1A45DFA3':
            $ft = FileType::MKV;
            break;
        case '52494646': // RIFF
            $ft = FileType::AVI;
            break;
        case '3026B275':
            $ft =  FileType::WMV;
            break;
        default:
            if ('66747970' ===  bin2hex(fread($fileHandle, 4))) {
                $ft = FileType::MP4;
            }
    }
    rewind($fileHandle);
    return $ft;
}

function parse_srs_avi($fh, $srsSize) {
    $result = array();
    $result['trackData'] = array();

    $rr = new RiffReader($fh, $srsSize);
    $done = FALSE;
    while (!$done && $rr->read()) {
        if ($rr->chunkType == 'LIST') {
            $rr->moveToChild();
        } else {
            if ($rr->fourcc == 'SRSF') {
                $data = $rr->readContents();
                $result['fileData'] = new FileData($data);
            } elseif ($rr->fourcc == 'SRST') {
                $data = $rr->readContents();
                $track = new TrackData($data);
                $result['trackData'][$track->trackNumber] = $track;
            } elseif ($rr->chunkType == 'MOVI') {
                $done = TRUE;
                break;
            } else {
                $rr->skipContents();
            }
        }
    }
    return $result;
}

class EbmlType {
    const Segment = 'segment';
    const ReSample = 'resample';
    const ReSampleFile = 'resamplefile';
    const ReSampleTrack = 'resampletrack';
    const Cluster = 'cluster';
    const AttachmentList = 'attachmentlist';
    const Block = 'block';
    const Unknown = 'whatever';
}

function parse_srs_mkv($fh, $srsSize) {
    $result = array();
    $result['trackData'] = array();

    $er = new EbmlReader($fh, $srsSize);
    $done = FALSE;
    while(!$done && $er->read()) {
        if ($er->etype == EbmlType::Segment || $er->etype == EbmlType::ReSample) {
            $er->moveToChild();
        } elseif ($er->etype == EbmlType::ReSampleFile) {
            $data = $er->readContents();
            $result['fileData'] = new FileData($data);
        } elseif ($er->etype == EbmlType::ReSampleTrack) {
            $data = $er->readContents();
            $track = new TrackData($data);
            $result['trackData'][$track->trackNumber] = $track;
        } elseif ($er->etype == EbmlType::Cluster || $er->etype == EbmlType::AttachmentList) {
            $er->skipContents();
            $done = TRUE;
        } else {
            $er->skipContents();
        }
    }
    return $result;
}

function parse_srs_mp4($fh, $srsSize) {
    $result = array();
    $result['trackData'] = array();

    $mr = new MovReader($fh, $srsSize);
    while($mr->read()) {
        if ($mr->atomType == 'SRSF') {
            $data = $mr->readContents();
            $result['fileData'] = new FileData($data);
        } elseif ($mr->atomType == 'SRST') {
            $data = $mr->readContents();
            $track = new TrackData($data);
            $result['trackData'][$track->trackNumber] = $track;
        } elseif ($mr->atomType == 'mdat') {
            $mr->moveToChild();
        } else {
            $mr->skipContents();
        }
    }
    return $result;
}

function parse_srs_wmv($fh, $srsSize) {
    $result = array();
    $result['trackData'] = array();
    
    $GUID_SRS_FILE = 'SRSFSRSFSRSFSRSF';
    $GUID_SRS_TRACK = 'SRSTSRSTSRSTSRST';
    $GUID_SRS_PADDING = "PADDINGBYTESDATA";
    
    $start_pos = strpos(fread($fh, $srsSize), $GUID_SRS_FILE);
    fseek($fh, $start_pos);

    while ($start_pos < $srsSize) {
       $guid = fread($fh, 16);
       $object_size = unpack('Vlow/Vhigh', fread($fh, 8));
       // add the high order bits before the low order bits and convert to decimal
       $lowhex = str_pad(dechex($object_size['low']), 8, '0', STR_PAD_LEFT);
       $highhex = dechex($object_size['high']);
       $size = hexdec($highhex . $lowhex);
       
       $object_data = fread($fh, $size - 24);
       if ($guid == $GUID_SRS_FILE) {
           $result['fileData'] = new FileData($object_data);
       } elseif ($guid == $GUID_SRS_TRACK) {
           $track = new TrackData($object_data);
           $result['trackData'][$track->trackNumber] = $track;
       } elseif ($guid == $GUID_SRS_PADDING) {
           // normally the padding bytes are always zero, but not in this sample
           // all the padding bytes are stored in this block when at least one of them isn't zero
           $result['paddingSize'] = $size - 24;
       } else {
           // all interesting objects are grouped together
           // nothing interesting follows
           break;
       }
        
       $start_pos = ftell($fh);
    }

    return $result;
}

class FileData {
    public function __construct($data) {
        $u = unpack('vflags/vappLength', substr($data, 0, 4));
        $this->flags = $u['flags'];
        $this->appName = substr($data, 4, $u['appLength']);
        $v = unpack('vnameLength', substr($data, 4 + $u['appLength'], 2));
        $this->name = substr($data, 4 + $u['appLength'] + 2, $v['nameLength']);
        $offset = 4 + $u['appLength'] + 2 + $v['nameLength'];

        $w = unpack('Vlow/Vhigh/Vcrc32', substr($data, $offset, 12));
        // add the high order bits before the low order bits and convert to decimal
        $lowhex = str_pad(dechex($w['low']), 8, '0', STR_PAD_LEFT);
        $highhex = dechex($w['high']);
        $this->fileSize = hexdec($highhex . $lowhex);
        $this->crc32 = dechex($w['crc32']);
    }
}

class TrackData {
    public function __construct($data) {
        $u = unpack('vflags', substr($data, 0, 2));
        $this->flags = $u['flags'];

        // MP4 files can have larger track numbers
        if ($this->flags & 0x8) { // big track number
            // 4 bytes
            $u = unpack('VtrackNumber', substr($data, 2, 6));
            $extra = 2;
        } else {
            // 2 bytes
            $u = unpack('vtrackNumber', substr($data, 2, 4));
            $extra = 0;
        }
        $this->trackNumber = $u['trackNumber'];

        if ($this->flags & 0x4) { // big file
            $w = unpack('Vlow/Vhigh', substr($data, 4 + $extra, 8));
            $lowhex = str_pad(dechex($w['low']), 8, '0', STR_PAD_LEFT);
            $highhex = dechex($w['high']);
            $this->dataSize = hexdec($highhex . $lowhex);
            $add = 8;
        } else {
            $w = unpack('Vsize', substr($data, 4 + $extra, 4));
            $this->dataSize = $w['size'];
            $add = 4;
        }
        $w = unpack('Vlow/Vhigh', substr($data, 4 + $extra + $add, 8));
        $lowhex = str_pad(dechex($w['low']), 8, '0', STR_PAD_LEFT);
        $highhex = dechex($w['high']);
        // location where the track is located in the main file (often zero)
        $this->matchOffset = hexdec($highhex . $lowhex);
        // signature length and signature bytes we don't need
    }
}

class RiffReader {
    public function __construct($fileHandle, $srsSize) {
        $this->fh = $fileHandle;
        $this->fileSize = $srsSize;
        $this->readDone = TRUE;

        $this->chunkType = null;
        $this->hasPadding = FALSE;
        $this->chunkLength = 0;
        $this->fourcc = '';
    }

    public function read() {
        $chunkStartPosition = ftell($this->fh);
        $this->readDone = FALSE;

        if ($chunkStartPosition + 8 > $this->fileSize) {
            return FALSE;
        }

        $header = fread($this->fh, 8);
        $this->fourcc = substr($header, 0, 4);
        $this->chunkLength = unpack('Vlength', substr($header, 4, 4));
        $this->chunkLength = $this->chunkLength['length'];

        if ($this->fourcc == 'RIFF' || $this->fourcc == 'LIST') {
            fseek($this->fh, 4, SEEK_CUR);
            //echo $this->chunkLength . "\n";
            $this->chunkLength -= 4;
            $this->chunkType = 'LIST';
        } else {
            if (ctype_digit(substr($header, 0, 2))) {
                $this->chunkType = 'MOVI';
            } else {
                $this->chunkType = '    ';
            }
        }
        $this->hasPadding = $this->chunkLength % 2 == 1;

        return TRUE;
    }

    public function readContents() {
        if ($this->readDone) {
            fseek($this->fh, -$this->chunkLength - $this->hasPadding, SEEK_CUR);
        }

        $this->readDone = TRUE;
        $buffer = null;

        if ($this->chunkType != 'MOVI') {
            $buffer = fread($this->fh, $this->chunkLength);
        }

        if ($this->hasPadding) {
            fseek($this->fh, 1, SEEK_CUR);
        }
        return $buffer;
    }

    public function skipContents() {
        if (!$this->readDone) {
            $this->readDone = TRUE;

            if ($this->chunkType != 'MOVI') {
                fseek($this->fh, $this->chunkLength, SEEK_CUR);
            }

            if ($this->hasPadding) {
                fseek($this->fh, 1, SEEK_CUR);
            }
        }
    }

    public function moveToChild() {
        $this->readDone = TRUE;
    }
}

class EbmlReader {
    public function __construct($fileHandle, $srsSize) {
        $this->fh = $fileHandle;
        $this->fileSize = $srsSize;
        $this->readDone = TRUE;

        $this->etype = null;
        $this->elementLength = 0;
    }

    private function String2Hex($string){
        $hex='';
        for ($i=0; $i < strlen($string); $i++){
            $hex .= str_pad(dechex(ord($string[$i])), 2,  '0', STR_PAD_LEFT);
        }
        return $hex;
    }

    public function read() {
        assert($this->readDone == TRUE || $this->etype == EbmlType::Block);
        // too little data
        if (ftell($this->fh) + 2 > $this->fileSize) {
            return FALSE;
        }

        $this->readDone = FALSE;

        // element ID
        $readByte = ord(fread($this->fh, 1));
        $idLengthDescriptor = $this->getUIntLength($readByte);
        $elementHeader = str_pad(dechex($readByte), 2,  '0', STR_PAD_LEFT);
        if ($idLengthDescriptor > 1) {
            $elementHeader .= $this->String2Hex(fread($this->fh, $idLengthDescriptor - 1));
        }

        // data size
        $readByte = ord(fread($this->fh, 1));
        $dataLengthDescriptor = $this->getUIntLength($readByte);
        $elementHeader .= str_pad(dechex($readByte), 2,  '0', STR_PAD_LEFT);
        if ($dataLengthDescriptor > 1) {
            $elementHeader .= $this->String2Hex(fread($this->fh, $dataLengthDescriptor - 1));
        }

        assert ($idLengthDescriptor + $dataLengthDescriptor == strlen($elementHeader)/2);
        if ($idLengthDescriptor + $dataLengthDescriptor != strlen($elementHeader)/2)
            exit();

        // data
        $eh = strtoupper(substr($elementHeader, 0, 2*$idLengthDescriptor));
        switch ($eh) {
            case 'A1':
            case 'A2':
                $this->etype = EbmlType::Block;
                break;
            case '1F43B675':
                $this->etype = EbmlType::Cluster;
                break;
            case '18538067':
                $this->etype = EbmlType::Segment;
                break;
            case '1941A469':
                $this->etype = EbmlType::AttachmentList;
                break;
            case '1F697576':
                $this->etype = EbmlType::ReSample;
                break;
            case '6A75':
                $this->etype = EbmlType::ReSampleFile;
                break;
            case '6B75':
                $this->etype = EbmlType::ReSampleTrack;
                break;
            default:
                $this->etype = EbmlType::Unknown;
        }

        $this->elementLength = $this->getEbmlUInt($elementHeader, $idLengthDescriptor, $dataLengthDescriptor);

        return TRUE;
    }

    private function getUIntLength($lengthDescriptor) {
        $length = 0;
        for ($i=0;$i<8;$i++) {
            if (($lengthDescriptor & (0x80 >> $i)) != 0) {
                $length = $i + 1;
                break;
            }
        }
        return $length;
    }

    private function getEbmlUInt($buff, $offset, $count) {
        $size = hexdec(substr($buff, $offset*2, 2)) & (0xFF >> $count);
        for ($i=1;$i<$count;$i++) {
            $size = ($size << 8) + hexdec(substr($buff, $offset*2+$i*2, 2));
        }
        return $size;
    }

    public function readContents() {
        if ($this->readDone) {
            fseek($this->fh, -$this->elementLength, SEEK_CUR);
        }

        $this->readDone = TRUE;
        $buffer = null;

        // skip over removed ebml elements
        if ($this->etype != EbmlType::Block) {
            $buffer = fread($this->fh, $this->elementLength);
        }
        return $buffer;
    }

    public function skipContents() {
        if (!$this->readDone) {
            $this->readDone = TRUE;

            if ($this->etype != EbmlType::Block) {
                fseek($this->fh, $this->elementLength, SEEK_CUR);
            }
        }
    }

    public function moveToChild() {
        $this->readDone = TRUE;
    }
}

class MovReader {
    public function __construct($fileHandle, $srsSize) {
        $this->fh = $fileHandle;
        $this->fileSize = $srsSize;
        $this->readDone = TRUE;
        $this->atomType = '';
        $this->atomLength = 0;
        $this->atomStartPosition = 0;
        assert(ftell($this->fh) === 0);
    }

    public function read() {
        assert($this->readDone);
        $atomStartPosition = ftell($this->fh);
        $this->readDone = FALSE;

        if ($atomStartPosition + 8 > $this->fileSize) {
            return FALSE;
        }
        $header = fread($this->fh, 8);
        $u = unpack('Nlength', substr($header, 0, 4));
        $atomLength = $u['length'];
        $this->atomType = substr($header, 4, 4);

        // special sizes
        $hsize = 8;
        if ($atomLength === 1) {
            // 8-byte size field after the atom type
            $bsize = fread($this->fh, 8);
            $w = unpack('Nhigh/Nlow', substr($bsize, 0, 8));
            // add the high order bits before the low order bits and convert to decimal
            $lowhex = str_pad(dechex($w['low']), 8, '0', STR_PAD_LEFT);
            $highhex = dechex($w['high']);
            $atomLength = hexdec($highhex . $lowhex);
            $hsize += 8;
        } elseif ($atomLength === 0) {
            // FoV/COMPULSiON samples have an atom that consists of just 8 null bytes.
            // This is the case if it is followed by an mdat
            if ($this->atomType === "\x00\x00\x00\x00") {
                $atomLength = 8;
            } else {
                // the atom extends to the end of the file
                $atomLength = $this->fileSize - $atomStartPosition;
            }
        }
        $this->headerSize = $hsize;
        $this->atomLength = $atomLength;
        $this->atomStartPosition = $atomStartPosition;
            
        fseek($this->fh, $atomStartPosition, SEEK_SET);
        
        return TRUE;
    }

    public function readContents() {
        if ($this->readDone) {
            fseek($this->fh, $this->atomStartPosition, SEEK_SET);
        }

        $this->readDone = TRUE;
        $buffer = null;

        fseek($this->fh, $this->headerSize, SEEK_CUR);
        
        if ($this->atomType != 'mdat') {
            $buffer = fread($this->fh, $this->atomLength - $this->headerSize);
        }

        return $buffer;
    }

    public function skipContents() {
        if (!$this->readDone) {
            $this->readDone = TRUE;

            if ($this->atomType != 'mdat') {
                fseek($this->fh, $this->atomLength, SEEK_CUR);
            } else {
                fseek($this->fh, $this->headerSize, SEEK_CUR);
            }
        }
    }

    public function moveToChild() {
        $this->readDone = TRUE;
        fseek($this->fh, $this->headerSize, SEEK_CUR);
    }
}

/* ----- end of rescene.php ----- */