-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall.php
More file actions
5062 lines (4608 loc) · 274 KB
/
Copy pathinstall.php
File metadata and controls
5062 lines (4608 loc) · 274 KB
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
session_start();
// The installer can run for a long time (esp. step that imports the 2.3GB
// vBulletin dump). Disable PHP execution / input timeouts and raise memory
// from inside the script so this works even if Apache hasn't been restarted
// to pick up php.ini changes.
@set_time_limit(0);
@ini_set('max_execution_time', '0');
@ini_set('max_input_time', '-1');
@ini_set('memory_limit', '2048M');
@ignore_user_abort(true);
if (file_exists(__DIR__.'/cms/config.php')) {
echo 'CMS already installed.';
exit;
}
$step = isset($_GET['step']) ? (int)$_GET['step'] : 1;
$errors = [];
/**
* Convert a loose, human-readable date (e.g. "Wed, 24 Aug 2005"
* or "February 24, 2005, 12:33 pm") to 'Y-m-d H:i:s'.
* If PHP can't parse it, return the original string unchanged.
*/
function normalizeDate(string $raw): string
{
// strip outer quotes that str_getcsv removed earlier
$clean = trim($raw, " \t\n\r\0\x0B'\"");
$ts = strtotime($clean);
return $ts !== false ? date('Y-m-d H:i:s', $ts) : $raw;
}
/**
* Split a multi_query batch buffer back into individual statements when the
* whole-batch path fails. We built the buffer ourselves with `;\n` between
* statements, so a literal split is safe here — no need for a full SQL parser.
*/
function self_split_sql_batch(string $buf): array
{
$parts = explode(";\n", $buf);
$out = [];
foreach ($parts as $p) {
$t = trim($p);
if ($t !== '' && $t !== ';') {
$out[] = $t;
}
}
return $out;
}
/**
* Convert a single SQL VALUES-tuple line into one TSV row.
*
* Input : "(1005, '[2004] Steam Discussions', '', 0, NULL, 1),"
* Output : "1005\t[2004] Steam Discussions\t\t0\t\\N\t1\n"
*
* Critical correctness note: mysqldump's INSERT-string escape sequences
* (\n, \r, \t, \0, \\, \', \") decode byte-for-byte the same way under
* LOAD DATA's default escape rules. So we copy the bytes between the outer
* `'` quotes verbatim — no decoding+re-encoding pass needed. This is what
* makes the conversion fast enough for a 2GB+ dump.
*
* Returns "" on parse failure (caller skips the row).
*/
function vbimport_tuple_to_tsv(string $line): string
{
$n = strlen($line);
$i = 0;
// Skip to opening `(`
while ($i < $n && $line[$i] !== '(') $i++;
if ($i >= $n) return '';
$i++;
$fields = [];
while ($i < $n) {
// Skip whitespace
while ($i < $n) {
$c = $line[$i];
if ($c === ' ' || $c === "\t" || $c === "\n" || $c === "\r") $i++;
else break;
}
if ($i >= $n) break;
$c = $line[$i];
if ($c === "'") {
// Quoted string: walk to matching `'`, skipping `\X` pairs
$i++;
$start = $i;
while ($i < $n) {
$ch = $line[$i];
if ($ch === '\\') {
$i += 2; // skip escaped char (incl. its body byte)
} elseif ($ch === "'") {
break;
} else {
$i++;
}
}
$fields[] = substr($line, $start, $i - $start);
if ($i < $n) $i++; // past closing '
} elseif (($c === 'N' || $c === 'n')
&& $i + 3 < $n
&& strcasecmp(substr($line, $i, 4), 'NULL') === 0) {
$fields[] = "\\N";
$i += 4;
} else {
// Unquoted (number / boolean / unquoted ident) — copy until `,` or `)`
$start = $i;
while ($i < $n && $line[$i] !== ',' && $line[$i] !== ')') $i++;
$fields[] = trim(substr($line, $start, $i - $start));
}
// Skip whitespace, then expect `,` (next field) or `)` (end of tuple)
while ($i < $n) {
$c = $line[$i];
if ($c === ' ' || $c === "\t") $i++;
else break;
}
if ($i >= $n) break;
if ($line[$i] === ',') { $i++; continue; }
if ($line[$i] === ')') break;
// Anything else is a parse error — bail
return '';
}
return implode("\t", $fields) . "\n";
}
/**
* Split a tail-of-line tuple sequence like:
* "(1, 'a'), (2, 'b'), (3, 'c');"
* into ["(1, 'a')", "(2, 'b')", "(3, 'c')"]
*
* Handles strings (so commas/parens inside `'...'` don't split the tuple).
* Used only when an INSERT header has tuples appended on the same line —
* mysqldump's default extended-INSERT format puts each tuple on its own line,
* so this path is rare but cheap to support.
*/
function vbimport_split_inline_tuples(string $s): array
{
$n = strlen($s);
$i = 0;
$out = [];
while ($i < $n) {
while ($i < $n && $s[$i] !== '(') $i++;
if ($i >= $n) break;
$start = $i;
$i++;
// Walk to matching `)`, respecting strings
while ($i < $n) {
$c = $s[$i];
if ($c === "'") {
$i++;
while ($i < $n) {
$cc = $s[$i];
if ($cc === '\\') { $i += 2; }
elseif ($cc === "'") { $i++; break; }
else { $i++; }
}
} elseif ($c === ')') {
$i++;
break;
} else {
$i++;
}
}
$out[] = substr($s, $start, $i - $start);
}
return $out;
}
/**
* Preprocess SQL statement to convert human-readable dates to MySQL format.
* Detects and converts date values like 'Friday, April 1 2005' or 'Jan 15, 2005' to '2005-04-01'.
*/
function normalizeSqlDates(string $sql): string
{
// Pattern to match quoted date strings that look like human-readable dates
// Examples: 'Friday, April 1 2005', 'Jan 15, 2005', 'Monday, January 15, 2004', etc.
// This pattern looks for: 'Optional-Weekday, Month Day[,] Year'
// The comma after the day is optional (,?)
$pattern = "/'((?:[A-Z][a-z]+day,\s*)?[A-Z][a-z]+\s+\d{1,2},?\s+\d{4})'/";
return preg_replace_callback($pattern, function($matches) {
$dateStr = $matches[1];
$timestamp = strtotime($dateStr);
// If strtotime successfully parsed it, convert to Y-m-d format
if ($timestamp !== false) {
// For DATE columns, use Y-m-d format
$mysqlDate = date('Y-m-d', $timestamp);
return "'" . $mysqlDate . "'";
}
// If parsing failed, return the original match unchanged
return $matches[0];
}, $sql);
}
/**
* Split SQL content into individual statements, handling multi-line strings and blocks
*/
function split_sql_statements($sql)
{
$stmts = [];
$buffer = '';
$inBlock = false;
$blockDepth = 0;
$inString = false;
$stringChar = '';
$escaped = false;
$delimiter = ';';
foreach (preg_split("/\r?\n/", $sql) as $line) {
$trim = trim($line);
if ($inBlock) {
if (strpos($trim, '*/') !== false) {
$inBlock = false;
}
continue;
}
if (!$inString && ($trim === '' || str_starts_with($trim, '--') || $trim[0] === '#')) {
continue;
}
if (!$inString && str_starts_with($trim, '/*')) {
$inBlock = true;
continue;
}
if (!$inString && preg_match('/^DELIMITER\s+(\S+)/i', $trim, $matches)) {
$delimiter = $matches[1] !== '' ? $matches[1] : ';';
// Reset buffer when switching delimiters to avoid partial statements carrying over
$buffer = '';
continue;
}
if (!$inString && preg_match('/\bBEGIN\b/i', $trim)) {
$blockDepth++;
}
if (!$inString && $blockDepth > 0 && preg_match('/\bEND\b/i', $trim) && !preg_match('/\bEND\s+(IF|LOOP|CASE|REPEAT)\b/i', $trim)) {
$blockDepth--;
}
$buffer .= $line."\n";
// Track string state to avoid splitting on delimiters inside quoted strings
for ($i = 0; $i < strlen($line); $i++) {
$char = $line[$i];
if ($escaped) {
$escaped = false;
continue;
}
if ($char === '\\') {
$escaped = true;
continue;
}
if (!$inString && ($char === "'" || $char === '"')) {
$inString = true;
$stringChar = $char;
} elseif ($inString && $char === $stringChar) {
$inString = false;
$stringChar = '';
}
}
$bufferTrimmed = rtrim($buffer);
if ($bufferTrimmed === '') {
continue;
}
if ($delimiter === ';') {
if ($blockDepth === 0 && !$inString && str_ends_with(rtrim($trim), $delimiter)) {
$stmts[] = trim(substr($bufferTrimmed, 0, -strlen($delimiter)));
$buffer = '';
}
} else {
if (!$inString && str_ends_with($bufferTrimmed, $delimiter)) {
$stmts[] = trim(substr($bufferTrimmed, 0, -strlen($delimiter)));
$buffer = '';
}
}
}
if (trim($buffer) !== '') {
$stmts[] = trim($buffer);
}
return $stmts;
}
/**
* Convert SQL string from any encoding to UTF-8
* Handles ISO-8859-1 (Latin-1) and other common encodings
*/
function ensureUtf8Encoding(string $sql): string
{
// Detect the encoding of the string
$encoding = mb_detect_encoding($sql, ['UTF-8', 'ISO-8859-1', 'ASCII', 'Windows-1252'], true);
// If not UTF-8, convert it
if ($encoding && $encoding !== 'UTF-8') {
$sql = mb_convert_encoding($sql, 'UTF-8', $encoding);
}
return $sql;
}
/**
* Execute SQL file with date normalization
*/
function run_sql_file(PDO $pdo, string $file): void
{
$sql = file_get_contents($file);
// Convert from detected encoding to UTF-8
$sql = ensureUtf8Encoding($sql);
// Preprocess SQL to normalize date formats
$sql = normalizeSqlDates($sql);
foreach (split_sql_statements($sql) as $stmt) {
$stmt = trim($stmt);
if ($stmt === '') {
continue;
}
$pdo->exec($stmt);
}
}
/**
* Convert phpBB schema.json type to MySQL column definition
*/
function phpbb_type_to_mysql($type, $default = null, $extra = null): string
{
$unsigned = '';
$mysql_type = '';
// Handle type with size specifier (e.g., VCHAR:50, TINT:2)
if (strpos($type, ':') !== false) {
[$base_type, $size] = explode(':', $type, 2);
} else {
$base_type = $type;
$size = null;
}
switch ($base_type) {
case 'UINT':
$mysql_type = 'INT(10) UNSIGNED';
break;
case 'ULINT':
$mysql_type = 'BIGINT(20) UNSIGNED';
break;
case 'USINT':
$mysql_type = 'SMALLINT(4) UNSIGNED';
break;
case 'BINT':
$mysql_type = 'BIGINT(20)';
break;
case 'TINT':
$mysql_type = 'TINYINT(' . ($size ?? 4) . ')';
break;
case 'INT':
$mysql_type = 'INT(' . ($size ?? 11) . ')';
break;
case 'VCHAR':
case 'VCHAR_UNI':
case 'VCHAR_CI':
$mysql_type = 'VARCHAR(' . ($size ?? 255) . ')';
break;
case 'CHAR':
$mysql_type = 'CHAR(' . ($size ?? 1) . ')';
break;
case 'XSTEXT':
case 'XSTEXT_UNI':
$mysql_type = 'VARCHAR(' . ($size ?? 1000) . ')';
break;
case 'STEXT':
case 'STEXT_UNI':
$mysql_type = 'TEXT';
break;
case 'TEXT':
case 'TEXT_UNI':
$mysql_type = 'TEXT';
break;
case 'MTEXT':
case 'MTEXT_UNI':
$mysql_type = 'MEDIUMTEXT';
break;
case 'TIMESTAMP':
$mysql_type = 'INT(11) UNSIGNED';
break;
case 'BOOL':
$mysql_type = 'TINYINT(1) UNSIGNED';
break;
case 'PDEC':
// Decimal with precision, size format is "precision,scale"
$mysql_type = 'DECIMAL(' . ($size ?? '5,2') . ')';
break;
default:
$mysql_type = 'TEXT';
}
// Build the column definition
$def = $mysql_type;
// MySQL 5.7+ strict mode and MySQL 8 reject DEFAULT clauses on TEXT/BLOB columns
// (error 1101). phpBB's native installer omits DEFAULT for these types and uses
// NOT NULL, requiring callers to supply an explicit value on INSERT. MariaDB
// 10.2.1+ allows it, but skipping is safe on both engines.
$is_text_blob = in_array($mysql_type, ['TEXT', 'MEDIUMTEXT', 'LONGTEXT', 'BLOB', 'MEDIUMBLOB', 'LONGBLOB'], true);
// Handle default value
if ($default !== null) {
if ($is_text_blob) {
$def .= ' NOT NULL';
} elseif (is_string($default) && $default !== '') {
$def .= " DEFAULT '" . addslashes($default) . "'";
} elseif (is_numeric($default)) {
$def .= " DEFAULT " . $default;
} elseif ($default === '') {
$def .= " DEFAULT ''";
}
} else {
$def .= ' NOT NULL';
}
// Handle auto_increment
if ($extra === 'auto_increment') {
$def .= ' AUTO_INCREMENT';
}
return $def;
}
/**
* Generate MySQL CREATE TABLE statements from phpBB schema.json
*/
function generate_phpbb_schema(string $schema_json_path): array
{
$statements = [];
if (!file_exists($schema_json_path)) {
throw new Exception("Schema file not found: $schema_json_path");
}
$json_content = file_get_contents($schema_json_path);
if ($json_content === false) {
throw new Exception("Failed to read schema file: $schema_json_path");
}
$schema = json_decode($json_content, true);
if ($schema === null) {
$json_error = json_last_error_msg();
throw new Exception("Failed to parse schema JSON: $json_error (file: $schema_json_path)");
}
if (empty($schema)) {
throw new Exception("Schema is empty: $schema_json_path");
}
foreach ($schema as $table_name => $table_def) {
$columns = [];
$primary_key = null;
$keys = [];
// Process columns
if (isset($table_def['COLUMNS'])) {
foreach ($table_def['COLUMNS'] as $col_name => $col_def) {
$type = $col_def[0];
$default = $col_def[1] ?? null;
$extra = $col_def[2] ?? null;
$col_sql = "`$col_name` " . phpbb_type_to_mysql($type, $default, $extra);
$columns[] = $col_sql;
}
}
// Process primary key
if (isset($table_def['PRIMARY_KEY'])) {
$pk = $table_def['PRIMARY_KEY'];
if (is_array($pk)) {
$primary_key = 'PRIMARY KEY (`' . implode('`, `', $pk) . '`)';
} else {
$primary_key = "PRIMARY KEY (`$pk`)";
}
}
// Process indexes
if (isset($table_def['KEYS'])) {
foreach ($table_def['KEYS'] as $key_name => $key_def) {
$key_type = $key_def[0];
$key_cols = $key_def[1];
// Handle column definitions - may include prefix length like "column_name:255"
$format_key_col = function($col) {
if (strpos($col, ':') !== false) {
// Format: column_name:prefix_length -> `column_name`(prefix_length)
[$col_name, $prefix_len] = explode(':', $col, 2);
return "`$col_name`($prefix_len)";
}
return "`$col`";
};
if (is_array($key_cols)) {
$cols_str = implode(', ', array_map($format_key_col, $key_cols));
} else {
$cols_str = $format_key_col($key_cols);
}
switch ($key_type) {
case 'UNIQUE':
$keys[] = "UNIQUE KEY `$key_name` ($cols_str)";
break;
case 'INDEX':
default:
$keys[] = "KEY `$key_name` ($cols_str)";
break;
}
}
}
// Build CREATE TABLE statement
$parts = array_merge($columns, $primary_key ? [$primary_key] : [], $keys);
$sql = "CREATE TABLE IF NOT EXISTS `$table_name` (\n " . implode(",\n ", $parts) . "\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
$statements[] = $sql;
}
return $statements;
}
/**
* Install phpBB modules (ACP, MCP, UCP)
* This is required for the admin control panel to function
*/
function install_phpbb_modules(PDO $pdo): void
{
echo " [phpBB] Installing modules...\n";
// Module structure based on phpBB's add_modules.php
// Format: [class => [category => [subcategories]]]
$module_categories = [
'acp' => [
'ACP_CAT_GENERAL' => [
'ACP_QUICK_ACCESS',
'ACP_BOARD_CONFIGURATION',
'ACP_CLIENT_COMMUNICATION',
'ACP_SERVER_CONFIGURATION',
],
'ACP_CAT_FORUMS' => [
'ACP_MANAGE_FORUMS',
'ACP_FORUM_BASED_PERMISSIONS',
],
'ACP_CAT_POSTING' => [
'ACP_MESSAGES',
'ACP_ATTACHMENTS',
],
'ACP_CAT_USERGROUP' => [
'ACP_CAT_USERS',
'ACP_GROUPS',
'ACP_USER_SECURITY',
],
'ACP_CAT_PERMISSIONS' => [
'ACP_GLOBAL_PERMISSIONS',
'ACP_FORUM_BASED_PERMISSIONS',
'ACP_PERMISSION_ROLES',
'ACP_PERMISSION_MASKS',
],
'ACP_CAT_CUSTOMISE' => [
'ACP_STYLE_MANAGEMENT',
'ACP_EXTENSION_MANAGEMENT',
'ACP_LANGUAGE',
],
'ACP_CAT_MAINTENANCE' => [
'ACP_FORUM_LOGS',
'ACP_CAT_DATABASE',
],
'ACP_CAT_SYSTEM' => [
'ACP_AUTOMATION',
'ACP_GENERAL_TASKS',
'ACP_MODULE_MANAGEMENT',
],
'ACP_CAT_DOT_MODS' => [],
],
'mcp' => [
'MCP_MAIN' => [],
'MCP_QUEUE' => [],
'MCP_REPORTS' => [],
'MCP_NOTES' => [],
'MCP_WARN' => [],
'MCP_LOGS' => [],
'MCP_BAN' => [],
],
'ucp' => [
'UCP_MAIN' => [],
'UCP_PROFILE' => [],
'UCP_PREFS' => [],
'UCP_PM' => [],
'UCP_USERGROUPS' => [],
'UCP_ZEBRA' => [],
],
];
// Module basenames for categories that have them
$category_basenames = [
'UCP_PM' => 'ucp_pm',
];
// ACP module info - maps basename to modes with their categories
// Based on acp_* info files in phpBB
$acp_modules = [
'acp_main' => [
'main' => ['cat' => ['ACP_QUICK_ACCESS'], 'title' => 'ACP_INDEX', 'auth' => 'acl_a_'],
],
'acp_board' => [
'settings' => ['cat' => ['ACP_BOARD_CONFIGURATION'], 'title' => 'ACP_BOARD_SETTINGS', 'auth' => 'acl_a_board'],
'features' => ['cat' => ['ACP_BOARD_CONFIGURATION'], 'title' => 'ACP_BOARD_FEATURES', 'auth' => 'acl_a_board'],
'avatar' => ['cat' => ['ACP_BOARD_CONFIGURATION'], 'title' => 'ACP_AVATAR_SETTINGS', 'auth' => 'acl_a_board'],
'message' => ['cat' => ['ACP_MESSAGES'], 'title' => 'ACP_MESSAGE_SETTINGS', 'auth' => 'acl_a_board'],
'post' => ['cat' => ['ACP_MESSAGES'], 'title' => 'ACP_POST_SETTINGS', 'auth' => 'acl_a_board'],
'signature' => ['cat' => ['ACP_MESSAGES'], 'title' => 'ACP_SIGNATURE_SETTINGS', 'auth' => 'acl_a_board'],
'registration' => ['cat' => ['ACP_CAT_USERS'], 'title' => 'ACP_REGISTER_SETTINGS', 'auth' => 'acl_a_board'],
'auth' => ['cat' => ['ACP_CAT_USERS'], 'title' => 'ACP_AUTH_SETTINGS', 'auth' => 'acl_a_board'],
'cookie' => ['cat' => ['ACP_CLIENT_COMMUNICATION'], 'title' => 'ACP_COOKIE_SETTINGS', 'auth' => 'acl_a_board'],
'load' => ['cat' => ['ACP_SERVER_CONFIGURATION'], 'title' => 'ACP_LOAD_SETTINGS', 'auth' => 'acl_a_board'],
'server' => ['cat' => ['ACP_SERVER_CONFIGURATION'], 'title' => 'ACP_SERVER_SETTINGS', 'auth' => 'acl_a_board'],
'security' => ['cat' => ['ACP_SERVER_CONFIGURATION'], 'title' => 'ACP_SECURITY_SETTINGS', 'auth' => 'acl_a_board'],
'email' => ['cat' => ['ACP_CLIENT_COMMUNICATION'], 'title' => 'ACP_EMAIL_SETTINGS', 'auth' => 'acl_a_board'],
],
'acp_users' => [
'overview' => ['cat' => ['ACP_CAT_USERS'], 'title' => 'ACP_MANAGE_USERS', 'auth' => 'acl_a_user'],
],
'acp_groups' => [
'manage' => ['cat' => ['ACP_GROUPS'], 'title' => 'ACP_GROUPS_MANAGE', 'auth' => 'acl_a_group'],
],
'acp_forums' => [
'manage' => ['cat' => ['ACP_MANAGE_FORUMS'], 'title' => 'ACP_MANAGE_FORUMS', 'auth' => 'acl_a_forum'],
],
'acp_permissions' => [
'intro' => ['cat' => ['ACP_GLOBAL_PERMISSIONS'], 'title' => 'ACP_PERMISSIONS', 'auth' => 'acl_a_viewauth'],
'admins' => ['cat' => ['ACP_GLOBAL_PERMISSIONS'], 'title' => 'ACP_ADMINISTRATORS', 'auth' => 'acl_a_aauth'],
'global' => ['cat' => ['ACP_GLOBAL_PERMISSIONS'], 'title' => 'ACP_GLOBAL_MODERATORS', 'auth' => 'acl_a_aauth'],
'forum' => ['cat' => ['ACP_FORUM_BASED_PERMISSIONS'], 'title' => 'ACP_FORUM_PERMISSIONS', 'auth' => 'acl_a_fauth'],
'moderators' => ['cat' => ['ACP_FORUM_BASED_PERMISSIONS'], 'title' => 'ACP_FORUM_MODERATORS', 'auth' => 'acl_a_fauth'],
],
'acp_permission_roles' => [
'admin_roles' => ['cat' => ['ACP_PERMISSION_ROLES'], 'title' => 'ACP_ADMIN_ROLES', 'auth' => 'acl_a_roles'],
'user_roles' => ['cat' => ['ACP_PERMISSION_ROLES'], 'title' => 'ACP_USER_ROLES', 'auth' => 'acl_a_roles'],
'mod_roles' => ['cat' => ['ACP_PERMISSION_ROLES'], 'title' => 'ACP_MOD_ROLES', 'auth' => 'acl_a_roles'],
'forum_roles' => ['cat' => ['ACP_PERMISSION_ROLES'], 'title' => 'ACP_FORUM_ROLES', 'auth' => 'acl_a_roles'],
],
'acp_styles' => [
'style' => ['cat' => ['ACP_STYLE_MANAGEMENT'], 'title' => 'ACP_STYLES', 'auth' => 'acl_a_styles'],
'install' => ['cat' => ['ACP_STYLE_MANAGEMENT'], 'title' => 'ACP_STYLES_INSTALL', 'auth' => 'acl_a_styles'],
],
'acp_extensions' => [
'main' => ['cat' => ['ACP_EXTENSION_MANAGEMENT'], 'title' => 'ACP_EXTENSIONS', 'auth' => 'acl_a_extensions'],
],
'acp_language' => [
'lang_packs' => ['cat' => ['ACP_LANGUAGE'], 'title' => 'ACP_LANGUAGE_PACKS', 'auth' => 'acl_a_language'],
],
'acp_logs' => [
'admin' => ['cat' => ['ACP_FORUM_LOGS'], 'title' => 'ACP_ADMIN_LOGS', 'auth' => 'acl_a_viewlogs'],
'mod' => ['cat' => ['ACP_FORUM_LOGS'], 'title' => 'ACP_MOD_LOGS', 'auth' => 'acl_a_viewlogs'],
'users' => ['cat' => ['ACP_FORUM_LOGS'], 'title' => 'ACP_USERS_LOGS', 'auth' => 'acl_a_viewlogs'],
'critical' => ['cat' => ['ACP_FORUM_LOGS'], 'title' => 'ACP_CRITICAL_LOGS', 'auth' => 'acl_a_viewlogs'],
],
'acp_database' => [
'backup' => ['cat' => ['ACP_CAT_DATABASE'], 'title' => 'ACP_BACKUP', 'auth' => 'acl_a_backup'],
'restore' => ['cat' => ['ACP_CAT_DATABASE'], 'title' => 'ACP_RESTORE', 'auth' => 'acl_a_backup'],
],
'acp_bots' => [
'bots' => ['cat' => ['ACP_CAT_USERS'], 'title' => 'ACP_BOTS', 'auth' => 'acl_a_bots'],
],
'acp_php_info' => [
'info' => ['cat' => ['ACP_GENERAL_TASKS'], 'title' => 'ACP_PHP_INFO', 'auth' => 'acl_a_phpinfo'],
],
'acp_prune' => [
'users' => ['cat' => ['ACP_CAT_USERS'], 'title' => 'ACP_PRUNE_USERS', 'auth' => 'acl_a_userdel'],
'forums' => ['cat' => ['ACP_MANAGE_FORUMS'], 'title' => 'ACP_PRUNE_FORUMS', 'auth' => 'acl_a_prune'],
],
'acp_modules' => [
'acp' => ['cat' => ['ACP_MODULE_MANAGEMENT'], 'title' => 'ACP_MODULE_MANAGEMENT', 'auth' => 'acl_a_modules'],
'ucp' => ['cat' => ['ACP_MODULE_MANAGEMENT'], 'title' => 'UCP', 'auth' => 'acl_a_modules'],
'mcp' => ['cat' => ['ACP_MODULE_MANAGEMENT'], 'title' => 'MCP', 'auth' => 'acl_a_modules'],
],
'acp_attachments' => [
'attach' => ['cat' => ['ACP_ATTACHMENTS'], 'title' => 'ACP_ATTACHMENT_SETTINGS', 'auth' => 'acl_a_attach'],
'extensions' => ['cat' => ['ACP_ATTACHMENTS'], 'title' => 'ACP_MANAGE_EXTENSIONS', 'auth' => 'acl_a_attach'],
'ext_groups' => ['cat' => ['ACP_ATTACHMENTS'], 'title' => 'ACP_EXTENSION_GROUPS', 'auth' => 'acl_a_attach'],
'orphan' => ['cat' => ['ACP_ATTACHMENTS'], 'title' => 'ACP_ORPHAN_ATTACHMENTS', 'auth' => 'acl_a_attach'],
],
'acp_search' => [
'settings' => ['cat' => ['ACP_SERVER_CONFIGURATION'], 'title' => 'ACP_SEARCH_SETTINGS', 'auth' => 'acl_a_search'],
'index' => ['cat' => ['ACP_GENERAL_TASKS'], 'title' => 'ACP_SEARCH_INDEX', 'auth' => 'acl_a_search'],
],
];
// MCP modules
$mcp_modules = [
'mcp_main' => [
'front' => ['cat' => ['MCP_MAIN'], 'title' => 'MCP_MAIN_FRONT', 'auth' => ''],
'forum_view' => ['cat' => ['MCP_MAIN'], 'title' => 'MCP_MAIN_FORUM_VIEW', 'auth' => 'acl_m_'],
'topic_view' => ['cat' => ['MCP_MAIN'], 'title' => 'MCP_MAIN_TOPIC_VIEW', 'auth' => 'acl_m_'],
'post_details' => ['cat' => ['MCP_MAIN'], 'title' => 'MCP_MAIN_POST_DETAILS', 'auth' => 'acl_m_'],
],
'mcp_queue' => [
'unapproved_topics' => ['cat' => ['MCP_QUEUE'], 'title' => 'MCP_QUEUE_UNAPPROVED_TOPICS', 'auth' => 'acl_m_approve'],
'unapproved_posts' => ['cat' => ['MCP_QUEUE'], 'title' => 'MCP_QUEUE_UNAPPROVED_POSTS', 'auth' => 'acl_m_approve'],
'deleted_topics' => ['cat' => ['MCP_QUEUE'], 'title' => 'MCP_QUEUE_DELETED_TOPICS', 'auth' => 'acl_m_approve'],
'deleted_posts' => ['cat' => ['MCP_QUEUE'], 'title' => 'MCP_QUEUE_DELETED_POSTS', 'auth' => 'acl_m_approve'],
],
'mcp_reports' => [
'reports' => ['cat' => ['MCP_REPORTS'], 'title' => 'MCP_REPORTS_OPEN', 'auth' => 'acl_m_report'],
'reports_closed' => ['cat' => ['MCP_REPORTS'], 'title' => 'MCP_REPORTS_CLOSED', 'auth' => 'acl_m_report'],
'report_details' => ['cat' => ['MCP_REPORTS'], 'title' => 'MCP_REPORT_DETAILS', 'auth' => 'acl_m_report', 'display' => 0],
],
'mcp_notes' => [
'front' => ['cat' => ['MCP_NOTES'], 'title' => 'MCP_NOTES_FRONT', 'auth' => ''],
'user_notes' => ['cat' => ['MCP_NOTES'], 'title' => 'MCP_NOTES_USER', 'auth' => ''],
],
'mcp_warn' => [
'front' => ['cat' => ['MCP_WARN'], 'title' => 'MCP_WARN_FRONT', 'auth' => 'acl_m_warn'],
'list' => ['cat' => ['MCP_WARN'], 'title' => 'MCP_WARN_LIST', 'auth' => 'acl_m_warn'],
'warn_user' => ['cat' => ['MCP_WARN'], 'title' => 'MCP_WARN_USER', 'auth' => 'acl_m_warn'],
'warn_post' => ['cat' => ['MCP_WARN'], 'title' => 'MCP_WARN_POST', 'auth' => 'acl_m_warn', 'display' => 0],
],
'mcp_logs' => [
'front' => ['cat' => ['MCP_LOGS'], 'title' => 'MCP_LOGS_FRONT', 'auth' => 'acl_m_'],
'forum_logs' => ['cat' => ['MCP_LOGS'], 'title' => 'MCP_LOGS_FORUM_VIEW', 'auth' => 'acl_m_'],
'topic_logs' => ['cat' => ['MCP_LOGS'], 'title' => 'MCP_LOGS_TOPIC_VIEW', 'auth' => 'acl_m_'],
],
'mcp_ban' => [
'user' => ['cat' => ['MCP_BAN'], 'title' => 'MCP_BAN_USERNAMES', 'auth' => 'acl_m_ban'],
'ip' => ['cat' => ['MCP_BAN'], 'title' => 'MCP_BAN_IPS', 'auth' => 'acl_m_ban'],
'email' => ['cat' => ['MCP_BAN'], 'title' => 'MCP_BAN_EMAILS', 'auth' => 'acl_m_ban'],
],
];
// UCP modules
$ucp_modules = [
'ucp_main' => [
'front' => ['cat' => ['UCP_MAIN'], 'title' => 'UCP_MAIN_FRONT', 'auth' => ''],
'subscribed' => ['cat' => ['UCP_MAIN'], 'title' => 'UCP_MAIN_SUBSCRIBED', 'auth' => ''],
'bookmarks' => ['cat' => ['UCP_MAIN'], 'title' => 'UCP_MAIN_BOOKMARKS', 'auth' => 'cfg_allow_bookmarks'],
'drafts' => ['cat' => ['UCP_MAIN'], 'title' => 'UCP_MAIN_DRAFTS', 'auth' => ''],
],
'ucp_profile' => [
'profile_info' => ['cat' => ['UCP_PROFILE'], 'title' => 'UCP_PROFILE_PROFILE_INFO', 'auth' => ''],
'signature' => ['cat' => ['UCP_PROFILE'], 'title' => 'UCP_PROFILE_SIGNATURE', 'auth' => ''],
'avatar' => ['cat' => ['UCP_PROFILE'], 'title' => 'UCP_PROFILE_AVATAR', 'auth' => ''],
'reg_details' => ['cat' => ['UCP_PROFILE'], 'title' => 'UCP_PROFILE_REG_DETAILS', 'auth' => ''],
'autologin_keys' => ['cat' => ['UCP_PROFILE'], 'title' => 'UCP_PROFILE_AUTOLOGIN_KEYS', 'auth' => ''],
],
'ucp_prefs' => [
'personal' => ['cat' => ['UCP_PREFS'], 'title' => 'UCP_PREFS_PERSONAL', 'auth' => ''],
'post' => ['cat' => ['UCP_PREFS'], 'title' => 'UCP_PREFS_POST', 'auth' => ''],
'view' => ['cat' => ['UCP_PREFS'], 'title' => 'UCP_PREFS_VIEW', 'auth' => ''],
],
'ucp_pm' => [
'view' => ['cat' => ['UCP_PM'], 'title' => 'UCP_PM_VIEW', 'auth' => 'cfg_allow_privmsg'],
'compose' => ['cat' => ['UCP_PM'], 'title' => 'UCP_PM_COMPOSE', 'auth' => 'cfg_allow_privmsg'],
'drafts' => ['cat' => ['UCP_PM'], 'title' => 'UCP_PM_DRAFTS', 'auth' => 'cfg_allow_privmsg'],
'options' => ['cat' => ['UCP_PM'], 'title' => 'UCP_PM_OPTIONS', 'auth' => 'cfg_allow_privmsg'],
],
'ucp_groups' => [
'membership' => ['cat' => ['UCP_USERGROUPS'], 'title' => 'UCP_USERGROUPS_MEMBER', 'auth' => ''],
'manage' => ['cat' => ['UCP_USERGROUPS'], 'title' => 'UCP_USERGROUPS_MANAGE', 'auth' => ''],
],
'ucp_zebra' => [
'friends' => ['cat' => ['UCP_ZEBRA'], 'title' => 'UCP_ZEBRA_FRIENDS', 'auth' => ''],
'foes' => ['cat' => ['UCP_ZEBRA'], 'title' => 'UCP_ZEBRA_FOES', 'auth' => ''],
],
'ucp_notifications' => [
'notification_options' => ['cat' => ['UCP_PREFS'], 'title' => 'UCP_NOTIFICATION_OPTIONS', 'auth' => ''],
],
'ucp_attachments' => [
'attachments' => ['cat' => ['UCP_MAIN'], 'title' => 'UCP_MAIN_ATTACHMENTS', 'auth' => 'acl_u_attach'],
],
];
// Clear existing modules
$pdo->exec("DELETE FROM phpbb_modules");
// Helper to insert module and return its ID
$insert_module = function($module_class, $parent_id, $langname, $basename = '', $mode = '', $auth = '', $display = 1) use ($pdo) {
// Get max right_id for this class
$stmt = $pdo->query("SELECT MAX(right_id) as max_right FROM phpbb_modules WHERE module_class = " . $pdo->quote($module_class));
$row = $stmt->fetch();
$left_id = ($row['max_right'] ?? 0) + 1;
$right_id = $left_id + 1;
$stmt = $pdo->prepare("INSERT INTO phpbb_modules
(module_enabled, module_display, module_basename, module_class, parent_id, left_id, right_id, module_langname, module_mode, module_auth)
VALUES (1, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->execute([$display, $basename, $module_class, $parent_id, $left_id, $right_id, $langname, $mode, $auth]);
return $pdo->lastInsertId();
};
$category_ids = [];
$module_count = 0;
// First pass: Create all categories
foreach ($module_categories as $module_class => $categories) {
$category_ids[$module_class] = [];
foreach ($categories as $cat_name => $subs) {
// Check if this category has a basename
$basename = $category_basenames[$cat_name] ?? '';
// Insert top-level category
$cat_id = $insert_module($module_class, 0, $cat_name, $basename);
$category_ids[$module_class][$cat_name] = $cat_id;
$module_count++;
// Insert subcategories
if (is_array($subs) && !empty($subs)) {
foreach ($subs as $sub_name) {
$sub_basename = $category_basenames[$sub_name] ?? '';
$sub_id = $insert_module($module_class, $cat_id, $sub_name, $sub_basename);
$category_ids[$module_class][$sub_name] = $sub_id;
$module_count++;
}
}
}
}
// Second pass: Add ACP modules
foreach ($acp_modules as $basename => $modes) {
foreach ($modes as $mode => $info) {
foreach ($info['cat'] as $cat_name) {
if (isset($category_ids['acp'][$cat_name])) {
$display = $info['display'] ?? 1;
$insert_module('acp', $category_ids['acp'][$cat_name], $info['title'], $basename, $mode, $info['auth'], $display);
$module_count++;
}
}
}
}
// Third pass: Add MCP modules
foreach ($mcp_modules as $basename => $modes) {
foreach ($modes as $mode => $info) {
foreach ($info['cat'] as $cat_name) {
if (isset($category_ids['mcp'][$cat_name])) {
$display = $info['display'] ?? 1;
$insert_module('mcp', $category_ids['mcp'][$cat_name], $info['title'], $basename, $mode, $info['auth'], $display);
$module_count++;
}
}
}
}
// Fourth pass: Add UCP modules
foreach ($ucp_modules as $basename => $modes) {
foreach ($modes as $mode => $info) {
foreach ($info['cat'] as $cat_name) {
if (isset($category_ids['ucp'][$cat_name])) {
$display = $info['display'] ?? 1;
$insert_module('ucp', $category_ids['ucp'][$cat_name], $info['title'], $basename, $mode, $info['auth'], $display);
$module_count++;
}
}
}
}
// Rebuild nested set tree (left_id, right_id) properly
// This is a simplified rebuild that just numbers everything sequentially
foreach (['acp', 'mcp', 'ucp'] as $module_class) {
$counter = 1;
// Get all top-level categories
$stmt = $pdo->prepare("SELECT module_id FROM phpbb_modules WHERE module_class = ? AND parent_id = 0 ORDER BY module_id");
$stmt->execute([$module_class]);
$top_cats = $stmt->fetchAll(PDO::FETCH_COLUMN);
foreach ($top_cats as $cat_id) {
$left = $counter++;
// Get all children
$stmt = $pdo->prepare("SELECT module_id FROM phpbb_modules WHERE module_class = ? AND parent_id = ? ORDER BY module_id");
$stmt->execute([$module_class, $cat_id]);
$children = $stmt->fetchAll(PDO::FETCH_COLUMN);
foreach ($children as $child_id) {
$child_left = $counter++;
// Get grandchildren
$stmt2 = $pdo->prepare("SELECT module_id FROM phpbb_modules WHERE module_class = ? AND parent_id = ? ORDER BY module_id");
$stmt2->execute([$module_class, $child_id]);
$grandchildren = $stmt2->fetchAll(PDO::FETCH_COLUMN);
foreach ($grandchildren as $gchild_id) {
$pdo->prepare("UPDATE phpbb_modules SET left_id = ?, right_id = ? WHERE module_id = ?")
->execute([$counter, $counter + 1, $gchild_id]);
$counter += 2;
}
$child_right = $counter++;
$pdo->prepare("UPDATE phpbb_modules SET left_id = ?, right_id = ? WHERE module_id = ?")
->execute([$child_left, $child_right, $child_id]);
}
$right = $counter++;
$pdo->prepare("UPDATE phpbb_modules SET left_id = ?, right_id = ? WHERE module_id = ?")
->execute([$left, $right, $cat_id]);
}
}
echo " [phpBB] Installed $module_count modules\n";
}
/**
* Install phpBB forum database and config
*/
function install_phpbb_forum(PDO $pdo, array $config, string $admin_user, string $admin_pass, string $admin_email): bool
{
$forum_dir = __DIR__ . '/forum';
$schema_json = $forum_dir . '/install1/schemas/schema.json';
$schema_data_sql = $forum_dir . '/install1/schemas/schema_data.sql';
echo " [phpBB] Forum dir: $forum_dir\n";
// Generate and run schema
if (!file_exists($schema_json)) {
throw new Exception("phpBB schema.json not found at: $schema_json");
}
echo " [phpBB] Schema JSON found\n";
$schema_statements = generate_phpbb_schema($schema_json);
if (empty($schema_statements)) {
throw new Exception("Failed to generate phpBB schema from: $schema_json");
}
echo " [phpBB] Generated " . count($schema_statements) . " schema statements\n";
// Drop existing phpBB tables first (clean install)
$result = $pdo->query("SHOW TABLES LIKE 'phpbb_%'");
$tables = $result->fetchAll(PDO::FETCH_COLUMN);
if (!empty($tables)) {
echo " [phpBB] Dropping " . count($tables) . " existing tables\n";
$pdo->exec("SET FOREIGN_KEY_CHECKS = 0");
foreach ($tables as $table) {
$pdo->exec("DROP TABLE IF EXISTS `$table`");
}
$pdo->exec("SET FOREIGN_KEY_CHECKS = 1");
}
// Create tables
echo " [phpBB] Creating tables...\n";
$table_count = 0;
foreach ($schema_statements as $sql) {
try {
$pdo->exec($sql);
$table_count++;
} catch (PDOException $e) {
// Extract table name from CREATE TABLE statement for better error message
if (preg_match('/CREATE TABLE.*?`(\w+)`/i', $sql, $m)) {
throw new Exception("Failed to create table {$m[1]}: " . $e->getMessage());
}
throw $e;
}
}
echo " [phpBB] Created $table_count tables\n";
// Verify critical tables were created
$verify_tables = ['phpbb_styles', 'phpbb_config', 'phpbb_users', 'phpbb_forums', 'phpbb_topics', 'phpbb_posts', 'phpbb_modules'];
foreach ($verify_tables as $table) {
$check = $pdo->query("SHOW TABLES LIKE '$table'");
if (!$check->fetch()) {
throw new Exception("Critical table '$table' was not created. Schema generation may have failed.");
}
}
echo " [phpBB] Verified critical tables exist\n";
// Load schema_data.sql (initial configuration)
if (file_exists($schema_data_sql)) {
echo " [phpBB] Loading schema_data.sql...\n";
$data_sql = file_get_contents($schema_data_sql);
// The file has # POSTGRES BEGIN # and # POSTGRES COMMIT # markers as comments
// split_sql_statements already skips comment lines starting with #
// Replace phpBB language placeholders with actual English text
$lang_replacements = [
'{L_FORUMS_FIRST_CATEGORY}' => 'Your first category',
'{L_FORUMS_TEST_FORUM_TITLE}' => 'Your first forum',
'{L_FORUMS_TEST_FORUM_DESC}' => 'Description of your first forum.',
'{L_TOPICS_TOPIC_TITLE}' => 'Welcome to phpBB3',
];
$data_sql = str_replace(array_keys($lang_replacements), array_values($lang_replacements), $data_sql);
$statements = split_sql_statements($data_sql);
$data_count = 0;
foreach ($statements as $stmt) {
$stmt = trim($stmt);
if ($stmt === '' || strpos($stmt, '#') === 0) {
continue;