forked from julmud/phpDVDProfiler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
incupdate.php
2520 lines (2301 loc) · 109 KB
/
incupdate.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
/* $Id$ */
if (!$inbrowser)
error_reporting(E_ALL);
function ExitSpecial() {
global $inbrowser;
if ($inbrowser)
echo '<div id="phpdvd_ErrorExit"></div>';
exit;
}
# Function to upgrade the database schema
function schema_update($schema_file) {
global $db, $lang, $inbrowser, $eoln, $table_prefix, $UpdateLast;
if (($sfh=fopen($schema_file, 'r')) === false) {
printf($lang['IMPORTMISSINGSCHEMA'].$eoln, $schema_file);
ExitSpecial();
}
// This code assumes that comments are only designated by #, and that # doesn't appear in quotes in a line ...
$dosub = ($table_prefix != 'DVDPROFILER_');
$cmd = '';
while ($line=fgets($sfh)) {
$temp = explode('#', $line);
if ($temp[0] != '') {
$tmp = trim($temp[0]);
$cmd .= $tmp;
if (substr($tmp, strlen($tmp)-1, 1) == ';') {
if ($dosub) $cmd = str_replace('DVDPROFILER_', $table_prefix, $cmd);
$res = $db->sql_query($cmd) or die($db->sql_error());
if (is_resource($res)) $db->sql_freeresult($res);
$cmd = '';
}
}
}
fclose($sfh);
$UpdateLast = UpdateUpdateLast(); // There is no data in the db, so let everyone know
}
function interpretEscapedXml($subject) {
$result = preg_replace_callback('/&/', function($matches) {
return '&';
}, $subject);
return preg_replace_callback('/&#(\d+);/', function($matches) {
return chr($matches[1]);
}, $result);
}
function ProcessLocalitiesCallback($matches) {
global $Locale, $RatingSystem, $RatingCallbackResult;
if (strncmp($matches[1], 'Locality ', strlen('Locality ')) == 0) {
preg_match('/ID="([^"]*)"/', $matches[1], $theid);
$Locale = $theid[1];
}
else if (strncmp($matches[1], 'Ratings ', strlen('Ratings ')) == 0) {
preg_match('/Description="([^"]*)"/', $matches[1], $theid);
$RatingSystem = interpretEscapedXml($theid[1]);
}
else if (strncmp($matches[1], 'Rating ', strlen('Rating ')) == 0) {
preg_match('/Name="([^"]*)".*Description="([^"]*)"/', $matches[1], $theid);
$theid[1] = interpretEscapedXml($theid[1]);
$theid[2] = interpretEscapedXml($theid[2]);
if ($RatingCallbackResult != '') $RatingCallbackResult .= ',';
$RatingCallbackResult .= "('Rating~$Locale~$RatingSystem~$theid[1]','$theid[2]')";
}
return;
}
function UpdateRatingDescriptions() {
global $db, $RatingCallbackResult, $DVD_PROPERTIES_TABLE;
$now = @filemtime('localities.xod');
if ($now === false)
return;
$result = $db->sql_query("SELECT value FROM $DVD_PROPERTIES_TABLE WHERE property='Rating~LastLocalitiesUpdateTime'") or die($db->sql_error());
$lastmtime = $db->sql_fetchrow($result);
$db->sql_freeresult($result);
if ($lastmtime === false || ($lastmtime['value'] < $now)) {
$data = file_get_contents('localities.xod');
$RatingCallbackResult = '';
preg_replace_callback('/<([^>]*)>/U', "ProcessLocalitiesCallback", $data);
if ($lastmtime !== false) $db->sql_query("DELETE FROM $DVD_PROPERTIES_TABLE WHERE property LIKE 'Rating%'") or die($db->sql_error());
$db->sql_query("INSERT INTO $DVD_PROPERTIES_TABLE (property,value) VALUES $RatingCallbackResult") or die($db->sql_error());
$db->sql_query("INSERT INTO $DVD_PROPERTIES_TABLE (property,value) VALUES ('Rating~LastLocalitiesUpdateTime',$now)") or die($db->sql_error());
}
return;
}
function CheckForCompleteXML($data) {
$retval = '';
$Sections['Locks'] = isset($data['LOCKS'][0]);
$Sections['Cast'] = isset($data['ACTORS'][0]);
$Sections['Crew'] = isset($data['CREDITS'][0]);
$Sections['Overview'] = isset($data['OVERVIEW'][0]);
$Sections['Notes'] = isset($data['NOTES'][0]);
$Sections['Tags'] = isset($data['TAGS'][0]);
$Sections['Easter Eggs'] = isset($data['EASTEREGGS'][0]);
foreach ($Sections as $key => $val)
if (!$val)
$retval .= "$key ";
return($retval);
}
function DoSomeStats($NAME, $NeedDistinct, $WHATWHEREFROM, $WHERE, $GROUPORDER, $noadulttitles, &$ProfileName, &$Profile, &$numtimings, &$t0) {
global $db, $TryToChangeMemoryAndTimeLimits, $DVD_STATS_TABLE, $IgnoreCount0Profiles;
$Distinct = '';
if ($NeedDistinct) $Distinct = 'DISTINCT';
if ($IgnoreCount0Profiles) $WHERE .= 'AND countas!=0 ';
$sql = "INSERT INTO $DVD_STATS_TABLE SELECT $Distinct '{$NAME}Adult',$WHATWHEREFROM $WHERE $GROUPORDER";
if ($TryToChangeMemoryAndTimeLimits) set_time_limit(0);
$db->sql_query($sql) or die($db->sql_error());
$ProfileName[$numtimings] = $NAME.'Adult'; $Profile[$numtimings++] = microtime_float()-$t0; $t0 = microtime_float();
if ($noadulttitles)
$sql = "INSERT INTO $DVD_STATS_TABLE SELECT '{$NAME}NoAdult',namestring1,namestring2,id,counts FROM $DVD_STATS_TABLE WHERE stattype='{$NAME}Adult'";
else
$sql = "INSERT INTO $DVD_STATS_TABLE SELECT $Distinct '{$NAME}NoAdult',$WHATWHEREFROM $WHERE AND isadulttitle=0 $GROUPORDER";
if ($TryToChangeMemoryAndTimeLimits) set_time_limit(0);
$db->sql_query($sql) or die($db->sql_error());
$ProfileName[$numtimings] = $NAME.'NoAdult'; $Profile[$numtimings++] = microtime_float()-$t0; $t0 = microtime_float();
if ($noadulttitles) $numtimings--;
return;
}
function HandleOutOfDateSchema(&$outputbuffer) {
global $lang, $WeCannotContinue, $inbrowser;
$outputbuffer = '';
if (!$WeCannotContinue)
return;
$schema_file = 'schema.sql';
if ($inbrowser) {
$outputbuffer = "$lang[IMPORTBADSCHEMA6]";
schema_update($schema_file);
$outputbuffer .= " $lang[IMPORTBADSCHEMA7]";
}
else {
$outputbuffer = html_entity_decode("$lang[IMPORTBADSCHEMA6]\n");
schema_update($schema_file);
$outputbuffer .= html_entity_decode("$lang[IMPORTBADSCHEMA7]\n");
}
}
function TranslateDateTime($string) {
// On entry, $string looks like: 1997-02-24T23:45:52.000Z
// MySQL seems to like: 1997-02-24 23:45:52
$halves = explode('T', $string);
if (!isset($halves[1])) $halves[1] = '00:00:00';
return($halves[0] . ' ' . substr($halves[1], 0, 8));
}
class BufferedInsert {
var $db;
var $max_packet;
var $table;
var $sql;
var $room_left;
var $col_names;
function __construct(&$db, $max_packet, $table, $col_names) {
$this->db = $db;
$this->room_left = $this->max_packet = $max_packet;
$this->table = $table;
$this->col_names = $col_names;
$this->sql = '';
}
function add_element($values) {
$retval = 0;
$templen = strlen($values);
if ($this->room_left <= $templen) {
$this->db->sql_query($this->sql) or die($this->db->sql_error());
$this->sql = '';
$this->room_left = $this->max_packet;
$retval = 1;
}
if ($this->sql == '') {
$this->sql = "INSERT INTO $this->table $this->col_names VALUES $values";
$this->room_left -= strlen($this->sql);
}
else {
$this->sql .= ',' . $values;
$this->room_left -= 1 + $templen;
}
return($retval);
}
function flush() {
if ($this->sql != '') {
$this->db->sql_query($this->sql) or die($this->db->sql_error());
return(1);
}
return(0);
}
}
// For memory stats, $ReportOnMemory=true and $pscommand='ps -p %%pid%% -o%mem= -orss='
// %%pid%% is replaced with the pid of the current process. This command gets the percentage
// of real memory used as well as the actual real size
$pscommand = str_replace('%%pid%%', getmypid(), $pscommand);
$MadeAChange = false;
$max_packet = 1024; // Initialise global value
// Displays shortened information about an array
// From http://www.devdump.com/phpxml.php
function print_a($obj) {
global $__level_deep;
if (!isset($__level_deep)) $__level_deep = array();
if (is_object($obj))
print '[obj]';
elseif (is_array($obj)) {
foreach(array_keys($obj) as $keys) {
array_push($__level_deep, "[$keys]");
print_a($obj[$keys]);
array_pop($__level_deep);
}
}
else
print implode(' ', $__level_deep)." = $obj\n";
}
// Modified from http://www.devdump.com/phpxml.php
$lineno=1; $addlineno=false;
function GetChildren($vals, &$i) {
global $lineno, $addlineno;
$children = array(); // Contains node data
/* Node has CDATA before it's children */
if (isset($vals[$i]['value'])) {
$children['VALUE'] = $vals[$i]['value'];
}
/* Loop through children */
while (++$i < count($vals)) {
switch ($vals[$i]['type']) {
/* Node has CDATA after one of it's children
(Add to cdata found before if this is the case) */
case 'cdata':
if (isset($children['VALUE']))
$children['VALUE'] .= $vals[$i]['value'];
else
$children['VALUE'] = $vals[$i]['value'];
break;
/* At end of current branch */
case 'complete':
if (isset($vals[$i]['attributes'])) {
$children[$vals[$i]['tag']][]['ATTRIBUTES'] = $vals[$i]['attributes'];
$index = count($children[$vals[$i]['tag']])-1;
if ($addlineno) {
$children[$vals[$i]['tag']][$index]['LINENO'] = $lineno;
$lineno++;
}
if (isset($vals[$i]['value']))
$children[$vals[$i]['tag']][$index]['VALUE'] = $vals[$i]['value'];
else
$children[$vals[$i]['tag']][$index]['VALUE'] = '';
}
else {
if (isset($vals[$i]['value']))
$children[$vals[$i]['tag']][]['VALUE'] = $vals[$i]['value'];
else
$children[$vals[$i]['tag']][]['VALUE'] = '';
if ($addlineno) {
$index = count($children[$vals[$i]['tag']])-1;
$children[$vals[$i]['tag']][$index]['LINENO'] = $lineno;
$lineno++;
}
}
break;
/* Node has more children */
case 'open':
if (($vals[$i]['tag'] == 'ACTORS') || ($vals[$i]['tag'] == 'CREDITS')) {
$addlineno = true;
$lineno = 1;
}
if (isset($vals[$i]['attributes'])) {
$children[$vals[$i]['tag']][]['ATTRIBUTES'] = $vals[$i]['attributes'];
$index = count($children[$vals[$i]['tag']])-1;
$children[$vals[$i]['tag']][$index] = array_merge($children[$vals[$i]['tag']][$index],GetChildren($vals, $i));
}
else {
$children[$vals[$i]['tag']][] = GetChildren($vals, $i);
}
break;
/* End of node, return collected data */
case 'close':
if (($vals[$i]['tag'] == 'ACTORS') || ($vals[$i]['tag'] == 'CREDITS')) {
$addlineno = false;
}
return $children;
}
}
}
function GetXMLTreeFromString($data, $inputencoding='ISO-8859-1') {
global $inbrowser, $lang, $WorkAroundLibxmlBug, $HTMLEntSearch, $HTMLEntReplace;
$data = '<?xml version="1.0" encoding="'.$inputencoding.'"?>' . "\n" . $data; // for php5
$parser = xml_parser_create($inputencoding);
xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'ISO-8859-1');
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, false);
if ($WorkAroundLibxmlBug) {
if (!isset($HTMLEntSearch)) {
$HTMLEntSearch = array('~ampers~', '&', '<', '>', '"', ''');
$HTMLEntReplace = array('&', '&', '<', '>', '"', "'");
}
$retval = xml_parse_into_struct($parser, str_replace('&', '~ampers~', $data), $vals, $index);
if ($retval != 0) {
$NumValues = count($vals);
for ($i=0; $i<$NumValues; $i++) {
if (isset($vals[$i]['value']))
$vals[$i]['value'] = str_replace($HTMLEntSearch, $HTMLEntReplace, $vals[$i]['value']);
if (isset($vals[$i]['attributes'])) {
foreach ($vals[$i]['attributes'] as $key => $attval)
$vals[$i]['attributes'][$key] = str_replace($HTMLEntSearch, $HTMLEntReplace, $vals[$i]['attributes'][$key]);
}
}
}
}
else
$retval = xml_parse_into_struct($parser, $data, $vals, $index);
if ($retval == 0) { // value returned is integer not boolean
global $amt_on_either_side;
$err = xml_get_error_code($parser);
$where_exactly = xml_get_current_byte_index($parser) - 1; // It appears that the byte may be one-based, so subtract 1
preg_match('|<Title>([^<]*)</Title>|', $data, $matches);
$title = $matches[1];
$tag = 'Unknown';
if (preg_match('|<([^>]*)>|', strrchr(substr($data, 0, $where_exactly-1), '<'), $matches) != 0)
$tag = $matches[1];
if ($inbrowser)
echo "<pre>\n";
printf($lang['IMPORTBADXML1'], $title, $tag);
printf($lang['IMPORTBADXML2'], $err, xml_error_string($err));
printf($lang['IMPORTBADXML3'], $where_exactly, xml_get_current_line_number($parser));
printf($lang['IMPORTBADXML4'], xml_get_current_column_number($parser), $amt_on_either_side);
$start = $where_exactly - $amt_on_either_side;
if ($start < 0) $start = 0;
echo hexdump(substr($data, $start, $where_exactly-$start), $where_exactly-$start, ' ');
echo hexdump($data{$where_exactly}, 1, '===> ');
echo hexdump(substr($data, $where_exactly+1, $amt_on_either_side), $amt_on_either_side, ' ');
echo $lang['IMPORTBADXML5'];
if ($inbrowser) {
print_r(htmlspecialchars($data, ENT_COMPAT, 'ISO-8859-1'));
echo "</pre>\n\n";
}
else
print_r($data);
ExitSpecial();
}
xml_parser_free($parser);
$tree = array();
$i = 0;
if (isset($vals[$i]['attributes']))
$tree[$vals[$i]['tag']]['ATTRIBUTES'] = $vals[$i]['attributes'];
$tree[$vals[$i]['tag']][] = GetChildren($vals, $i);
unset($vals);
unset($index);
return($tree);
}
function UpdateCommonTableFromMemory(&$common_memory, &$common_stats, $table, $hints=false) {
global $db, $max_packet, $lang;
$t0 = microtime_float();
$db->sql_query("SET autocommit=0;") or die($db->sql_error());
$db->sql_transaction('begin') or die($db->sql_error());
if ($common_memory != '') {
$col_names = '(caid,firstname,middlename,lastname,birthyear,fullname)';
$bi = new BufferedInsert($db, $max_packet, $table, $col_names);
if (!is_array($hints)) {
foreach ($common_memory as $key => $adata) {
list($caid, $add) = $adata;
if ($add == 1) {
$common_memory[$key] = array($caid, 0);
$common_stats['numadded']++;
list($fn, $mn, $ln, $by) = explode('|', $key);
$toadd = '('
. $caid . ','
. "'" . $db->sql_escape($fn) . "',"
. "'" . $db->sql_escape($mn) . "',"
. "'" . $db->sql_escape($ln) . "',"
. $by . ','
. "'" . $db->sql_escape(preg_replace('/\s\s+/', ' ', trim("$fn $mn $ln"))) . "'"
. ')';
$common_stats['numinserted'] += $bi->add_element($toadd);
}
}
}
else {
foreach ($hints as $key => $whichone) {
list($caid, $add) = $common_memory[$whichone];
$common_memory[$whichone] = array($caid, 0);
$common_stats['numadded']++;
list($fn, $mn, $ln, $by) = explode('|', $whichone);
$toadd = '('
. $caid . ','
. "'" . $db->sql_escape($fn) . "',"
. "'" . $db->sql_escape($mn) . "',"
. "'" . $db->sql_escape($ln) . "',"
. $by . ','
. "'" . $db->sql_escape(preg_replace('/\s\s+/', ' ', trim("$fn $mn $ln"))) . "'"
. ')';
$common_stats['numinserted'] += $bi->add_element($toadd);
}
}
$common_stats['numinserted'] += $bi->flush();
unset($bi);
unset($credit);
}
$db->sql_transaction('commit') or die($db->sql_error());
$db->sql_query("SET autocommit=1;") or die($db->sql_error());
$common_stats['amttime'] += microtime_float() - $t0;
}
function InitialiseCommonTable($which) {
global $db_fast_update, $common_actor, $common_actor_stats, $common_credit, $common_credit_stats, $db;
global $DVD_COMMON_ACTOR_TABLE, $DVD_COMMON_CREDITS_TABLE;
if ($db_fast_update) {
if ($which == 'common_actor' && empty($common_actor)) {
$res = $db->sql_query("SELECT * FROM $DVD_COMMON_ACTOR_TABLE ORDER BY caid") or die($db->sql_error());
$key = '';
while ($row = $db->sql_fetch_array($res)) {
$key = implode('|', array($row['firstname'], $row['middlename'], $row['lastname'], $row['birthyear']));
$common_actor[$key] = array($row['caid'], 0);
}
$db->sql_freeresult($res);
if ($key != '') {
if ($common_actor[$key][0] < 0)
$common_actor_stats['maxid'] = 0;
else
$common_actor_stats['maxid'] = intval($common_actor[$key][0]);
}
}
if ($which == 'common_credit' && empty($common_credit)) {
$res = $db->sql_query("SELECT * FROM $DVD_COMMON_CREDITS_TABLE ORDER BY caid") or die($db->sql_error());
$key = '';
while ($row = $db->sql_fetch_array($res)) {
$key = implode('|', array($row['firstname'], $row['middlename'], $row['lastname'], $row['birthyear']));
$common_credit[$key] = array($row['caid'], 0);
}
$db->sql_freeresult($res);
if ($key != '') {
if ($common_credit[$key][0] < 0)
$common_credit_stats['maxid'] = 0;
else
$common_credit_stats['maxid'] = intval($common_credit[$key][0]);
}
}
}
}
function FigureOutBuiltinMediaType($mediatypedvd, $mediatypehddvd, $mediatypebluray, $mediatypeultrahd) {
if ($mediatypehddvd) {
if ($mediatypedvd)
return(MEDIA_TYPE_HDDVD_DVD);
return(MEDIA_TYPE_HDDVD);
}
if ($mediatypeultrahd) {
if ($mediatypebluray)
return(MEDIA_TYPE_ULTRAHD_BLURAY);
// I don't think there's any 4k releases that have Just a DVD and no BD?
if ($mediatypedvd)
return(MEDIA_TYPE_ULTRAHD_BLURAY_DVD);
return(MEDIA_TYPE_ULTRAHD);
}
if ($mediatypebluray) {
if ($mediatypedvd)
return(MEDIA_TYPE_BLURAY_DVD);
return(MEDIA_TYPE_BLURAY);
}
if ($mediatypedvd)
return(MEDIA_TYPE_DVD);
return(0);
}
function OnOffAuto(&$str, $side, $caseslipcover, $casetype, $builtinmediatype, $custommediatype) {
// TODO: This is the place that determines whether the image needs a banner on it. The rules for this
// in the windows program are opaque due to bugs (settings do not cause reproducable results).
// There is currently no way to change the behavior for the Builtin mediatypes, but here would be
// the place to do it ...
// Note that in windows 3.7.2, 'automatic' will put a banner on the back covers - it didn't used
// to and it is likely wrong, but that is the observed behaiour, which we track
$defaulthasbanner = ($caseslipcover == 0 && ($casetype == 'HD Keep Case' || $casetype == 'HD Slim'));
if (isset($str)) {
$tmp = strtolower($str);
if ($tmp == 'off')
return(0);
if ($custommediatype != '')
return(-1);
if ($tmp == 'on' || ($tmp == 'automatic' && $defaulthasbanner))
return($builtinmediatype);
}
else {
if ($defaulthasbanner) {
if ($builtinmediatype != MEDIA_TYPE_DVD)
return($builtinmediatype);
}
}
return(0);
}
function TrueFalse(&$str) {
return((strtolower($str) == 'true') ? 1 : 0);
}
function GetHashs(&$oldhashs) {
global $db, $DVD_TABLE;
$result = $db->sql_query("SELECT id,hashprofile,hashnocolid,hashcast,hashcrew FROM $DVD_TABLE") or die($db->sql_error());
while ($row = $db->sql_fetchrow($result)) {
$id = array_shift($row);
$oldhashs[$id] = $row;
}
$db->sql_freeresult($result);
unset($row);
}
function HashData(&$data) {
$colid = '';
$hashprofile = Hex(crc32($data));
$hashnocolid = $hashcast = $hashcrew = $hashprofile;
if (($back = strpos($data, '</CollectionNumber>')) !== false) {
$front = strpos($data, '<CollectionNumber>') + strlen('<CollectionNumber>');
$colid = substr($data, $front, $back-$front);
$hashnocolid = Hex(crc32(substr($data, 0, $front).substr($data, $back)));
}
if (($back = strpos($data, '</Actors>')) !== false) {
$front = strpos($data, '<Actors>') + strlen('<Actors>');
$hashcast = Hex(crc32(substr($data, $front, $back-$front)));
}
if (($back = strpos($data, '</Credits>')) !== false) {
$front = strpos($data, '<Credits>') + strlen('<Credits>');
$hashcrew = Hex(crc32(substr($data, $front, $back-$front)));
}
return(array('hashprofile' => $hashprofile, 'hashnocolid' => $hashnocolid, 'hashcast' => $hashcast, 'hashcrew' => $hashcrew, 'colid' => $colid));
}
function MemoryUsage($str, $addeoln = false) {
global $pscommand, $eoln, $ReportOnMemory;
if (!$ReportOnMemory)
return($addeoln? $eoln: '');
if ($pscommand != '') {
exec($pscommand, $out);
list($percent, $kb) = explode(' ', trim($out[0]));
return("$str: Resident Set Size is " . number_format($kb/1024, 1) . "MB ($percent% of real memory) currently using " . number_format(memory_get_usage()/1024/1024, 1) . "MB$eoln");
}
return("$str: Currently using " . number_format(memory_get_usage()/1024/1024, 1) . "MB$eoln");
}
function PrepareBrowserOutput() {
global $lang;
SendNoCacheHeaders('Content-Type: text/html; charset="windows-1252";');
echo<<<EOT
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; CHARSET=windows-1252">
<title>$lang[IMPORTTITLE]</title>
<link rel="stylesheet" type="text/css" href="format.css.php">
</head>
<body class=f6>
EOT;
}
function ExtractFromZip($filename) {
global $DeleteTemporaryFile, $imagecachedir, $eoln, $lang;
$success = false;
$x = zip_open($filename);
if (!is_resource($x)) {
printf($lang['IMPORTZIPOPENFAIL'].$eoln, $x, $filename);
return($success);
}
$entry = zip_read($x);
if (is_resource($entry)) {
if (zip_entry_open($x, $entry, "r") !== false) {
// here we extract the zipfile
$name = $imagecachedir . zip_entry_name($entry);
if (file_exists($name)) {
printf($lang['IMPORTZIPDELETEPREVIOUS'].$eoln, $name);
@unlink($name);
}
if (($handle=fopen($name, 'w')) === false) {
printf($lang['IMPORTZIPFOPENFAIL'].$eoln, $name, $filename);
zip_entry_close($entry);
zip_close($x);
return($success);
}
@chmod($name, 0666); // just for my convenience
$entry_content = zip_entry_read($entry, 8192);
while ($entry_content !== false && strlen($entry_content) > 0) {
if (fwrite($handle, $entry_content) === false) {
printf($lang['IMPORTZIPFWRITEFAIL'].$eoln, $name, $filename);
zip_entry_close($entry);
zip_close($x);
return($success);
}
$entry_content = zip_entry_read($entry, 8192);
}
fclose($handle);
zip_entry_close($entry);
$DeleteTemporaryFile = true;
$success = $name;
}
else {
echo $lang['IMPORTZIPINTERNAL1'], $eoln;
}
}
else if ($entry === false) {
echo $lang['IMPORTZIPINTERNAL2'], $eoln;
}
else {
printf($lang['IMPORTZIPINTERNAL3'].$eoln, $filename);
printf($lang['IMPORTZIPINTERNAL4'].$eoln, $entry);
}
zip_close($x);
return($success);
}
function GetCompressionList() {
// These mechanisms are characterised by using the regular fgets() function to read data
$KnownCompressions = array(
0 => array(
'Supported' => true,
'Compression' => 'DVD Profiler XML',
'Magic' => "<?xml vers",
'Extension' => "",
'Open' => "fopen",
'Close' => "fclose"
),
1 => array(
'Supported' => function_exists('lzf_compress'),
'Compression' => 'LZ Compress',
'Magic' => "\037\235",
'Extension' => "Z",
'Open' => "",
'Close' => ""
),
2 => array(
'Supported' => function_exists('gzopen'),
'Compression' => 'gzip',
'Magic' => "\037\213",
'Extension' => "gz",
'Open' => "gzopen",
'Close' => "gzclose"
),
3 => array(
'Supported' => function_exists('bzopen'),
'Compression' => 'bzip2',
'Magic' => "BZ",
'Extension' => "bz2",
'Open' => "bzopen",
'Close' => "bzclose"
),
4 => array(
'Supported' => function_exists('zip_open'),
'Compression' => 'zip',
'Magic' => "PK\003\004",
'Extension' => "zip",
'Open' => "fopen", // we'll extract to ASCII first
'Close' => "fclose"
)
);
return($KnownCompressions);
}
function PrintSupportedCompressions(&$KnownCompressions) {
global $lang, $inbrowser, $eoln;
echo $lang['IMPORTFROMXMLNOFILES2'], $eoln;
if ($inbrowser) echo "<pre>";
foreach ($KnownCompressions as $Compression) {
if ($Compression['Supported'])
echo "\t$Compression[Compression]\n";
}
if ($inbrowser) echo "</pre>";
return;
}
function GetListOfXMLFiles(&$my_fopen, &$my_fclose) {
global $xmlfile, $xmldir, $lang, $eoln, $imagecachedir, $TryToChangeMemoryAndTimeLimits;
//
// This will return with an array of files. It will ensure that the IO routines are appropriate for the
// files. Note that the IO routines will only change to match the single file in $xmlfile, while this
// routine will only process files ending .xml in $xmldir, and assume that they are plain-text ASCII.
$allxmlfiles = array();
// If $xmldir points to a directory, then we grab only XML files from that directory.
// In this case, we ignore $xmlfile.
if (is_dir($xmldir) && is_readable($xmldir)) {
echo $lang['IMPORTFROMXMLDIR'], $eoln;
$handle = opendir($xmldir);
while (($file=readdir($handle)) !== false) {
if (strcasecmp(pathinfo($file, PATHINFO_EXTENSION), 'xml') != 0)
continue;
if (is_readable("$xmldir/$file"))
$allxmlfiles[] = "$xmldir/$file";
}
closedir($handle);
return($allxmlfiles);
}
// $xmldir did not point to a directory, so we will process $xmlfile.
echo $lang['IMPORTFROMXMLFILE'], $eoln;
$KnownCompressions = GetCompressionList();
$Trying = $xmlfile;
if (!is_readable($xmlfile)) {
// print $xmlfile not found - searching for $KnownCompressions, perhaps with stripped extension?
$dir = dirname($xmlfile);
if (!is_readable($dir)) {
printf($lang['IMPORTFROMXMLBADDIR'].$eoln, $xmlfile, $dir);
ExitSpecial();
}
$base = basename($xmlfile);
$noext = substr($base, 0, -1*strlen(pathinfo($base, PATHINFO_EXTENSION))-1);
$found = false;
$handle = opendir($dir);
while (($file=readdir($handle)) !== false) {
if ($file == '.' || $file == '..')
continue;
// check for simple case-sensitivity
if (strcasecmp($file, $base) == 0) {
if (is_readable("$dir/$file")) {
$found = true;
break;
}
}
// Check for each usable extension. Also check for replacement of the extension (.xml) with the compressed (.zip)
foreach ($KnownCompressions as $Compression) {
if (!$Compression['Supported'])
continue;
$ext = $Compression['Extension'];
if (strcasecmp($file, "$base.$ext") == 0 && is_readable("$dir/$file")) {
$found = true;
break;
}
if (strcasecmp($file, "$noext.$ext") == 0 && is_readable("$dir/$file")) {
$found = true;
break;
}
}
if ($found)
break;
}
closedir($handle);
$Trying = '';
if ($found) {
$Trying = $file;
if ($dir != '.') $Trying = "$dir/$file";
printf($lang['IMPORTFROMXMLFILEMISSING'].$eoln, $Trying);
}
}
if ($Trying == '') {
echo $lang['IMPORTFROMXMLNOFILES1'], $eoln;
PrintSupportedCompressions($KnownCompressions);
ExitSpecial();
}
// Figure out what type of file this is, so that we can diddle the IO routines.
if (($x=fopen($Trying, 'r')) === false) {
printf($lang['IMPORTFROMXMLCANTTYPEOPEN'].$eoln, $Trying);
ExitSpecial();
}
if (($buf=fread($x, 12)) === false) {
fclose($x);
printf($lang['IMPORTFROMXMLCANTTYPEREAD'].$eoln, $Trying);
ExitSpecial();
}
fclose($x);
$my_fopen = $my_fclose = '';
$filetype = '* Unknown *';
foreach ($KnownCompressions as $Compression) {
if (substr($buf, 0, strlen($Compression['Magic'])) == $Compression['Magic']) {
$my_fopen = $Compression['Open'];
$my_fclose = $Compression['Close'];
$filetype = $Compression['Compression'];
break;
}
}
printf($lang['IMPORTFROMXMLFILETYPE'].$eoln, $Trying, $filetype);
if ($my_fopen == '') {
printf($lang['IMPORTFROMXMLNOSUPPORT'].$eoln, $filetype);
PrintSupportedCompressions($KnownCompressions);
ExitSpecial();
}
// At this point we have determined the (single) file, its type, and set the IO routines to handle it.
// we should have printed any informative messages regarding failures, and should put the
// filename into the array. Failure should have already resulted in an exit.
if ($filetype == 'zip') {
if (!isset($imagecachedir) || !is_dir($imagecachedir) || !is_writeable($imagecachedir)) {
printf($lang['IMPORTZIPCANTWRITE'].$eoln, $Trying);
ExitSpecial();
}
printf($lang['IMPORTZIPEXTRACTHEAD'].$eoln, $Trying, $imagecachedir);
if ($TryToChangeMemoryAndTimeLimits) set_time_limit(0);
$Trying = ExtractFromZip($Trying);
if ($Trying === false)
ExitSpecial();
}
$allxmlfiles[] = $Trying;
return($allxmlfiles);
}
function ProcessXMLCollection($prelim_output) {
global $xmldir, $xmlfile, $inbrowser, $lang, $eoln, $PHP_SELF, $db, $DVD_TABLE, $delete, $FixBadXML, $UpdateLast, $users, $maxuserid;
global $forumuser, $handleadult, $collectionurl, $debugimageuploads, $endbody, $remove_missing, $TryToChangeMemoryAndTimeLimits, $MyConnectionId;
global $getimages, $DVD_PROPERTIES_TABLE, $DVD_COMMON_ACTOR_TABLE, $DVD_COMMON_CREDITS_TABLE, $CustomPostUpdate, $CollectionsNotInOwned;
global $common_actor, $common_actor_stats, $common_credit, $common_credit_stats, $db_fast_update, $max_packet, $displayfreq, $force_cleanup;
$T0 = microtime_float();
// Get the current connection ID and stuff it into the DB so that everyone knows we're running
$res = $db->sql_query("SELECT CONNECTION_ID() AS Id") or die($db->sql_error());
$row = $db->sql_fetchrow($res);
$MyConnectionId = $row['Id'];
$res = $db->sql_query("SELECT value FROM $DVD_PROPERTIES_TABLE WHERE property='CurrentPosition'", 0, true);
$row = $db->sql_fetchrow($res);
$db->sql_freeresult($res);
$val = substr($row['value'], 0, strrpos($row['value'], '|'));
unset($row);
$db->sql_query("UPDATE $DVD_PROPERTIES_TABLE SET value='$val|-$MyConnectionId' WHERE property='CurrentPosition'") or die($db->sql_error());
if ($inbrowser)
$tmp = "<div id=\"phpdvd_notice\" style=\"display:none\">200 - $MyConnectionId</div>";
else
$tmp = "$lang[UPDATECONNECTIONID]: $MyConnectionId$eoln";
if ($prelim_output != '')
$prelim_output = $tmp . $prelim_output . $eoln;
else
$prelim_output = $tmp;
$users = '';
$maxuserid = 0;
$common_actor = $common_credit = [];
$common_actor_stats = array('maxid' => 1, 'numadded' => 0, 'numinserted' => 0, 'amttime' => (float)0);
$common_credit_stats = array('maxid' => 1, 'numadded' => 0, 'numinserted' => 0, 'amttime' => (float)0);
if (!isset($db_fast_update))
$db_fast_update = false;
$safe_mode = (bool)@ini_get('safe_mode');
$TryToChangeMemoryAndTimeLimits = $TryToChangeMemoryAndTimeLimits && !$safe_mode;
if ($TryToChangeMemoryAndTimeLimits) @ini_set('memory_limit', -1); // the import script can use boatloads of memory ...
if ($inbrowser) {
PrepareBrowserOutput();
}
else {
foreach ($lang as $key => $val) {
if (substr($key, 0, 6) == 'IMPORT')
$lang[$key] = html_entity_decode(str_replace('—', '--', $lang[$key]));
}
}
$my_fopen = 'fopen';
$my_fclose = 'fclose';
$total = $UpdateLast['Total'];
$added = $UpdateLast['Added'];
$removed = 0;
$changed = $UpdateLast['Changed'];
$newcollnum = $UpdateLast['NewCollNum'];
$ppdelete = 0;
$start = microtime_float(); // This will be overwritten if we actually do any work
echo $prelim_output;
if ($UpdateLast['Offset'] >= 0) {
$allxmlfiles = GetListOfXMLFiles($my_fopen, $my_fclose);
$numxmlfiles = count($allxmlfiles);
$tmp = ($db_fast_update)? $lang['ON']: $lang['OFF'];
echo $lang['DBFAST'] . $tmp . $eoln;
flush();
@ob_flush();
// Find out how long a query we can send to the server ...
$result = $db->sql_query("SHOW VARIABLES like 'max_allowed_packet'") or die($db->sql_error());
$row = $db->sql_fetch_array($result);
$db->sql_freeresult($result);
$max_packet = $row['Value'];
$max_packet -= 2; // Experimentation has shown that the largest string we can send is max_allowed_packet-2 ...
unset($row);
$start = microtime_float();
// Delete contents of tables
if ($delete == 1) {
echo $lang['COMPLETE'] . $eoln;
flush();
@ob_flush();
DeleteFromTables('clean out all of the tables');
}
if ($UpdateLast['Offset'] != 0 && $remove_missing) {
$remove_missing = false;
echo $lang['UPDATEREMOVAL1'] . $eoln;
echo $lang['UPDATEREMOVAL2'] . $eoln;
echo $lang['UPDATEREMOVAL3'] . $eoln;
flush();
@ob_flush();
}
if (!$remove_missing) {
echo $lang['NOTREMOVING'] . $eoln;
flush();
@ob_flush();
}
$oldhashs = array();
GetHashs($oldhashs);
ModifyTables('DISABLE');
echo $lang['IMPORTUPDATING'] . $eoln; // database name
if ($numxmlfiles != 1)
printf($lang['IMPORTXMLDIR'].$eoln, $numxmlfiles, $xmldir);
$LotsaFiles = count($allxmlfiles) > 5;
$TT = sprintf("%9s", number_format(microtime_float() - $T0, 3, $lang['MON_DECIMAL_POINT'], $lang['MON_THOUSANDS_SEP']));
echo MemoryUsage("$TT: Before Processing");
if ($UpdateLast['Offset'] > 0) {
printf($lang['UPDATERESUMING'].$eoln, $UpdateLast['Total'],
number_format($UpdateLast['Offset'], 0, $lang['MON_DECIMAL_POINT'], $lang['MON_THOUSANDS_SEP']), $UpdateLast['Filename']);
}
foreach ($allxmlfiles as $key => $currentxmlfile) {
if ($UpdateLast['Offset'] > 0 && $currentxmlfile != $UpdateLast['Filename'])
continue;
if (($fh=$my_fopen($currentxmlfile, 'r')) === false) {
echo $lang['IMPORTBADOPEN'] . $currentxmlfile . $eoln;
if ($inbrowser)
echo "$endbody</html>\n";
ExitSpecial(); // Yes, the end html tag will precede the error div. none will care
}
$booya = fstat($fh);
$currentxmlfilesize = $booya['size'];
unset($booya);
if ($UpdateLast['Offset'] > 0 && isset($UpdateLast['Filesize']) && $UpdateLast['Filesize'] != $currentxmlfilesize) {
printf($lang['UPDATEFILECHANGED1'].$eoln, $currentxmlfile);
printf($lang['UPDATEFILECHANGED2'].$eoln, $UpdateLast['Filesize'], $currentxmlfilesize);
echo "$lang[UPDATEFILECHANGED3]$eoln";
}
if (!$LotsaFiles) {
if (substr($currentxmlfile, -3) == '.gz')
echo "$lang[IMPORTUSINGCOMPRESSED]$currentxmlfile$eoln";
else
echo "$lang[IMPORTPROCESSING]$currentxmlfile$eoln";
}
$inputencoding = '';
while (true) {
do {
if (($temp=fgets($fh)) === false)
break 2; // escape the while (true)
if ($inputencoding == '') {
if (preg_match('/<\?xml version="1.0" encoding="([^"]*)"\?>/i', $temp, $matches)) {
$inputencoding = $matches[1];
unset($matches);
if (strtolower($inputencoding) == 'windows-1252')
$inputencoding = 'ISO-8859-1';
}
}
} while (strpos($temp, '<DVD') === false);
if ($inputencoding == '')
$inputencoding = 'ISO-8859-1';
if ($UpdateLast['Offset'] > 0) {
fseek($fh, $UpdateLast['Offset']);
$UpdateLast['Offset'] = 0;
$UpdateLast['Filename'] = '';
$data = '';
do { // Ensure that we're at the beginning of a DVD section ... This could get messed up with MediaTypes ...
if (($temp=fgets($fh)) === false)
break 2; // escape the while (true)
} while (strpos($temp, '<DVD') === false);