-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrescene.php
2920 lines (2588 loc) · 85.7 KB
/
rescene.php
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
<?php
/**
* PHP Library to read and edit a .srr file. It reads .srs files.
* Copyright (c) 2011-2019 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: 2019-04-26
*
* 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/FLAC/MP3)
* - Sort stored files inside the SRR.
* - OpenSubtitles.org/ISDb hash support.
* - Extract the SRR meta data of a single RAR set
*
* - 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
* - http://www.srrdb.com/release/details/Race.To.Witch.Mountain.1080p.BluRay.x264-HD1080 (wrong file size)
* - http://www.srrdb.com/release/details/NBA.2010.03.02.Pacers.Vs.Lakers.720p.HDTV.x264-BALLS (crc FFFFFFFF)
* - http://www.srrdb.com/release/details/Dexter.S01E03.720p.Bluray.x264-ORPHEUS (short crc)
* - When renaming a file and only the capitals will be different, a file with the old name is added.
* - http://www.srrdb.com/release/details/Scrapland.AlcoholClone.MI-NOGRP (dupe names, so not all files get shown)
* - Add error when a file is twice in the SFV (twice the meta data too)
* - Add warning when there is no SFV file and the SRR contains RAR meta data
*
*/
namespace ReScene;
// necessary for storing files in large (60MB) SRR files
ini_set('memory_limit', '1024M');
$BLOCKNAME = array(
0x69 => 'SRR VolumeHeader',
0x6A => 'SRR Stored File',
0x6B => 'SRR OSO Hash',
0x6C => 'SRR RAR Padding',
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 FLAC = 'FLAC';
const MP3 = 'MP3';
const STREAM = 'STRM'; // vob and basic m2ts
const M2TS = 'M2TS';
const Unknown = '';
}
// for suppressing error messages
$CLI_APP = false;
// cli progs are cool
if (!empty($argc) && strstr($argv[0], basename(__FILE__))) {
$CLI_APP = true;
/* 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 " -p 'file to split' (sPlit)\n";
echo " -h 'special hash of the SRR file' (Hash)\n";
echo " -a 'show SRS info (sAmple)\n";
echo " -l 'show stored SRR languages (Languages)\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': // rename
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;
case '-p': // split
$data = grabSrrSubset($srr, $file);
file_put_contents('rescene.php_split.srr', $data);
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
$srsData = file_get_contents($srr);
print_r(processSrsData($srsData));
} elseif ($switch === '-l') {
// show vobsub languages
print_r(getVobsubLanguages($srr));
} elseif ($switch === '-t') {
echo 'fileNameCheckTest: ';
if (fileNameCheckTest()) {
echo "OK!\n";
} else {
echo "NOT OK!\n";
}
echo 'createSrrHeaderBlockTest: ';
if (createSrrHeaderBlockTest()) {
echo "OK!\n";
} else {
echo "NOT OK!\n";
}
echo 'getBasenameVolumeTest: ';
if (getBasenameVolumeTest()) {
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.
* @return mixed data array, or false on failure
*/
function processSrr($file) {
$result = FALSE;
if(file_exists($file)) {
$fh = fopen($file, 'rb');
if (flock($fh, LOCK_SH)) {
$result = processSrrHandle($fh);
flock($fh, LOCK_UN); // release the lock
}
fclose($fh); // close the file
}
return $result;
}
/**
* Processes a whole SRR file and returns an array with useful details.
* @param resource $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+');
fwrite($fp, $srrFileData);
rewind($fp);
$result = processSrrHandle($fp);
fclose($fp);
return $result;
}
/**
* Leaves the file handle open!
* Only used in the 2 functions above.
*/
function processSrrHandle($fileHandle) {
// global $BLOCKNAME;
$fh = $fileHandle;
$srrSize = getFileSizeHandle($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
$encrypted = FALSE; // encryption is used on one or more files
// other initializations
$read = 0; // number of bytes we have read so far
$last_read = 0; // to prevent looping on encountering bad data
$current_rar = NULL;
$customPacker = FALSE; // when not created with WinRAR
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 ISDb/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 0x6C: // SRR RAR Padding Block
$current_rar['fileSize'] -= $block->hsize;
$block->skipBlock();
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)) {
// message here must start with Duplicate for the check in sorting
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']);
$sf['basenameVolume'] = getBasenameVolume($block->fileName, FALSE);
}
$block->skipBlock();
// calculate CRC of the stored file
$sdata = stream_get_contents($fileHandle, $block->addSize, $block->storedFileStartOffset);
$sf['fileCrc'] = strtoupper(str_pad(dechex(crc32($sdata)), 8, '0', STR_PAD_LEFT));
// $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
// initialize, set later when volume header is available
$f['basenameVolume'] = '';
}
$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];
// FLEET, AVS,... (first and last rar have correct size)
if ($f['fileSizeStart'] !== $block->fileSize) {
$customPacker = TRUE;
}
} else { // new file found in the archives
$f = array();
$f['fileName'] = $block->fileName;
$f['fileTime'] = date("Y-m-d h:i:s", $block->fileTime);
$f['compressionMethod'] = $block->compressionMethod;
$f['fileSizeStart'] = $block->fileSize;
// file size complexity because of crappy custom packers
if ($block->fileSize !== 0xffffffffffffffff && // 1
$block->fileSize !== -1 && /* 2) 32 bit php */
$block->fileSize !== 0xffffffff /* 2) 64 bit php */) {
// file size normal case
$f['fileSize'] = $block->fileSize;
} else {
$f['fileSize'] = 0;
// 1) custom RAR packers used: last RAR contains the size
// Street.Fighter.V-RELOADED or Magic.Flute-HI2U or 0x0007
if ($block->fileSize == 0xffffffffffffffff) {
array_push($warnings, "RELOADED/HI2U/0x0007 custom RAR packer detected.");
}
// 2) crap group that doesn't store the correct size at all:
// The.Powerpuff.Girls.2016.S01E08.HDTV.x264-QCF
if ($block->fileSize == 0xffffffff || $block->fileSize == -1) {
array_push($warnings, "Crappy QCF RAR packer detected.");
}
}
}
// check if compression was used
if ($f['compressionMethod'] != 0x30) { // 0x30: Storing
$compressed = TRUE;
}
// file size counting fixes
// 2) above int was correct? it must match at the end - QCF
if (($block->fileSize == -1 || $block->fileSize == 0xffffffff) && !$compressed) {
$f['fileSize'] += $block->addSize;
}
// 1) expected the last RAR (first with the proper value)
if ($block->fileSize !== 0xffffffffffffffff && $f['fileSize'] == 0) {
$f['fileSize'] = $block->fileSize;
}
// 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;
// file is encrypted with password
// The.Sims.4.City.Living.INTERNAL-RELOADED
if ($block->flags & 0x4) {
$encrypted = TRUE;
}
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
$block->skipBlock();
break;
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']}.");
}
$is_new_style_naming = $block->flags & 0x0010 && $block->flags & 0x0001; // new numbering and a volume
$current_rar['basenameVolume'] = getBasenameVolume($current_rar['fileName'], $is_new_style_naming);
// encrypted block headers are used: these SRRs don't exist
if ($block->flags & 0x0080) {
$encrypted = TRUE;
}
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);
// don't loop when bad data is encountered
if ($read === $last_read) {
break;
}
$last_read = $read;
}
// mapping SFV CRC32 -> RAR
if (\count($rar_files) > 0) {
$sfvTotal = \count($sfv['files']);
addCrcSfvs($sfv, $rar_files);
if ($sfvTotal === \count($sfv['files'])) {
// examples: Office.Lady.Sex.Orgv.BID-027.Jav.Censored.DVDRip.XviD-MotTto
// Mana.Sakura.STAR-334.Jav.Censored.DVDRip.XviD-MotTto
$cleanedMapping = array();
foreach ($rar_files as $key => $_value) {
$cleanedMapping[trim($key)] = $key;
}
addCrcSfvs($sfv, $rar_files, $cleanedMapping);
if ($sfvTotal === \count($sfv['files'])) {
array_push($warnings, 'Included SFVs have no SRR stored RAR file matches.');
} else {
array_push($warnings, 'Stored RAR file names have leading/trailing spaces.');
}
}
}
if ($customPacker) {
array_push($warnings, 'Custom RAR packer detected.');
}
// 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,
'encrypted' => $encrypted
);
}
/**
* Same as the getStoredFileData() function, but based on the file name.
* @param string $srrfile The name of the SRR file to read.
* @param string $filename The file we want the contents from, including the path.
* @return resource The bytes of the file or FALSE on failure.
*/
function getStoredFile($srrfile, $filename) {
$result = FALSE;
$fh = fopen($srrfile, 'rb');
if (flock($fh, LOCK_SH)) {
$srr = processSrrHandle($fh);
foreach($srr['storedFiles'] as $key => $value) {
if($key === $filename) {
$result = stream_get_contents($fh, $value['fileSize'], $value['fileOffset']);
break;
}
}
flock($fh, LOCK_UN); // release the lock
}
fclose($fh); // close the file
return $result;
}
/**
* Removes a file stored in the SRR file.
* @param string $srrfile Path of the SRR file.
* @param string $filename Path and name of the file to remove.
* @return TRUE on success, FALSE otherwise
*/
function removeFile($srrfile, $filename) {
$result = FALSE;
$fh = fopen($srrfile, 'c+b');
if (flock($fh, LOCK_EX)) {
$srr = processSrrHandle($fh);
foreach ($srr['storedFiles'] as $key => $value) {
if ($value['fileName'] === $filename) {
// how much to remove? read the block starting from the offset
fseek($fh, $value['blockOffset'], SEEK_SET);
$warnings_stub = array();
$block = new Block($fh, $warnings_stub);
fseek($fh, $value['blockOffset'] + $block->fullSize, SEEK_SET);
$after = fread($fh, $srr['srrSize']); // srrSize: the (max) amount to read
ftruncate($fh, $value['blockOffset']);
fseek($fh, 0, SEEK_END); // Upon success, returns 0; otherwise, returns -1.
fwrite($fh, $after);
$result = TRUE;
break;
}
}
flock($fh, LOCK_UN); // release the lock
}
fclose($fh); // close the file
return $result;
}
/**
* 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 resource $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 $srrFile The path of the SRR file.
* @param string $filePath The path and name that will be stored.
* @param resource $fdata The bytes of the file to store in the SRR file.
* @return TRUE when storing succeeds.
*/
function storeFile($srrFile, $filePath, $fdata) {
// check for illegal windows characters
// the path separator must be /
// twice (//) may not be possible
if (fileNameCheck($filePath)) {
return FALSE;
}
$fh = fopen($srrFile, 'c+b');
if (flock($fh, LOCK_EX)) {
$srr = processSrrHandle($fh);
// don't let the same file get added twice
foreach($srr['storedFiles'] as $key => $value) {
if($key === $filePath) {
flock($fh, LOCK_UN);
fclose($fh);
return FALSE;
}
}
$offset = newFileOffset($fh);
if ($offset < 0) {
// broken/empty .srr file due to bugs :(
flock($fh, LOCK_UN);
fclose($fh);
return FALSE;
}
$after = fread($fh, $srr['srrSize']);
$header = createStoredFileHeader($filePath, \strlen($fdata));
ftruncate($fh, $offset);
fseek($fh, 0, SEEK_END); // Upon success, returns 0; otherwise, returns -1.
fwrite($fh, $header);
fwrite($fh, $fdata);
fwrite($fh, $after);
flock($fh, LOCK_UN); // release the lock
}
fclose($fh); // close the file
return TRUE;
}
function addOsoHash($srrFile, $oso_hash_data) {
$fh = fopen($srrFile, 'c+b');
if (flock($fh, LOCK_EX)) {
$result = processSrrHandle($fh);
// the hash must not already exist
foreach($result['osoHashes'] as $value) {
if ($value['data'] == $oso_hash_data) {
flock($fh, LOCK_UN);
fclose($fh);
return FALSE;
}
}
fseek($fh, 0, SEEK_END); // is not necessary
fwrite($fh, $oso_hash_data);
flock($fh, LOCK_UN); // release the lock
}
fclose($fh); // close the file
return TRUE;
}
// /**
// * 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, getFileSizeHandle($fh));
// 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 $srrFile 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($srrFile, $oldName, $newName) {
if (fileNameCheck($newName)) {
if ($CLI_APP) {
print_r("The new file name is illegal. Use only forward slashes for paths.\n");
}
return FALSE;
}
$result = FALSE;
$fh = fopen($srrFile, 'c+b');
if (flock($fh, LOCK_EX)) {
$srr = processSrrHandle($fh);
// prevent renaming to a file that already exists
foreach ($srr['storedFiles'] as $key => $value) {
if ($key === $newName) {
flock($fh, LOCK_UN);
fclose($fh);
return FALSE;
}
}
// rename the first file
foreach ($srr['storedFiles'] as $key => $value) {
if ($value['fileName'] === $oldName) {
fseek($fh, $value['blockOffset'], SEEK_SET);
$warnings_stub = array();
$block = new Block($fh, $warnings_stub);
$block->srrReadStoredFileHeader();
fseek($fh, $value['blockOffset'] + $block->hsize, SEEK_SET);
$after = fread($fh, $srr['srrSize']); // srrSize: the (max) amount to read
ftruncate($fh, $value['blockOffset']);
fseek($fh, 0, SEEK_END); // Upon success, returns 0; otherwise, returns -1.
$changedHeader = createStoredFileHeader($newName, $block->addSize);
fwrite($fh, $changedHeader);
fwrite($fh, $after);
$result = TRUE;
break;
}
}
flock($fh, LOCK_UN); // release the lock
}
fclose($fh); // close the file
return $result;
}
/**
* Calculate hash to identify SRRs that cover the same RAR volumes.
* The result can be wrong when the provided $rarFiles array is outdated.
* @param string $srr The SRR file.
* @param array $rarFiles The resulting array from processSrr().
* @return string Sha1 hash of the srr file
*/
function calculateHash($srrfile, $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, '\ReScene\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);
$fh = fopen($srrfile, 'rb');
if (flock($fh, LOCK_SH)) {
// calculate hash only on the RAR metadata
foreach ($rarFiles as $key => $value) {
$start = $value['offsetStartRar'];
$end = $value['offsetEnd'];
$data = stream_get_contents($fh, ($end - $start), $start);
hash_update($hashContext, $data);
}
flock($fh, LOCK_UN); // release the lock
}
fclose($fh); // close the file
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