-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup.php
More file actions
4282 lines (3749 loc) · 171 KB
/
Copy pathsetup.php
File metadata and controls
4282 lines (3749 loc) · 171 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
/**
* ignis Setup Script
*
* Lädt das Release-ZIP (oder cloned einen Branch), führt `composer install`
* aus, schreibt die .env, lässt Phinx die DB-Migrations laufen und löscht
* sich anschließend selbst. Der komplette Flow läuft in einem einzigen
* POST-Request, damit die Session-Cookies konsistent bleiben — das UI
* zeigt während der Wartezeit eine mehrstufige Progress-Animation.
*/
// ── Debug / Error-Display ────────────────────────────────────────────
// Produktion: Errors nur loggen, nicht an den Browser ausgeben (sonst
// leaken Pfade/DB-Credentials ins HTML). Mit `?debug` sichtbar machen.
if (isset($_GET['debug'])) {
error_reporting(E_ALL);
ini_set('display_errors', '1');
} else {
error_reporting(E_ALL);
ini_set('display_errors', '0');
ini_set('log_errors', '1');
}
// Setup-Session lebt 4 h: deckt längere Recherche-Pausen zwischen den
// Wizard-Schritten ab, ohne nach Abschluss noch lange offen zu sein.
// `cookie_lifetime` wirkt clientseitig garantiert; `gc_maxlifetime` per
// `ini_set` ist auf Shared-Hosting nicht immer respektiert — der
// Token-Refresh weiter unten dient als Sicherheitsnetz für diesen Fall.
$setupSessionLifetime = 4 * 60 * 60;
ini_set('session.gc_maxlifetime', (string) $setupSessionLifetime);
ini_set('session.cookie_lifetime', (string) $setupSessionLifetime);
session_start();
// ── Exception Handler — styled error page, secrets sanitized ────────
set_exception_handler(function (\Throwable $e) {
$isDebug = isset($_GET['debug']);
$message = $e->getMessage();
// Sanitize secrets from message and trace
$secrets = ['DB_PASS', 'DISCORD_CLIENT_SECRET', 'APP_KEY'];
foreach ($secrets as $key) {
$val = $_ENV[$key] ?? $_POST[$key] ?? null;
if ($val && is_string($val) && strlen($val) > 2) {
$message = str_replace($val, '[REDACTED]', $message);
}
}
// AJAX request? Return JSON error
if (!empty($_SERVER['HTTP_X_SETUP_AJAX'])) {
header('Content-Type: application/json', true, 500);
echo json_encode([
'success' => false,
'errors' => ['Interner Fehler: ' . ($isDebug ? $message : 'Bitte mit ?debug erneut versuchen.')],
]);
exit;
}
http_response_code(500);
$phpVer = htmlspecialchars(phpversion());
$reqUri = htmlspecialchars(($_SERVER['REQUEST_METHOD'] ?? '') . ' ' . ($_SERVER['REQUEST_URI'] ?? ''));
$referrer = htmlspecialchars($_SERVER['HTTP_REFERER'] ?? '—');
$memory = round(memory_get_peak_usage() / 1024 / 1024, 1) . ' MiB';
echo '<!DOCTYPE html><html lang="de"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">';
echo '<title>Setup-Fehler</title><style>';
echo '*{margin:0;padding:0;box-sizing:border-box}';
echo 'body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",system-ui,sans-serif;background:#f5f5f5;color:#333;min-height:100vh}';
echo '@media(prefers-color-scheme:dark){body{background:#0a0a0f;color:#e4e4ed}.header{background:#b91c1c}.content{color:#e4e4ed}.section{border-color:#2a2a3a}.label{color:#ff6b2c}.trace{background:#16161e;color:#8b8ba0;border-color:#2a2a3a}}';
echo '.header{background:#c80000;color:#fff;padding:16px 24px;font-size:1.1em;font-weight:600}';
echo '.content{max-width:100%;padding:24px}';
echo '.section{border-bottom:1px solid #e2e2ea;padding-bottom:16px;margin-bottom:24px}';
echo '.section h3{font-size:1.1em;font-weight:300;color:inherit;margin-bottom:12px}';
echo '.info-grid{display:grid;grid-template-columns:160px 1fr;gap:8px 16px;font-size:0.9em}';
echo '.label{color:#c80000;font-size:0.82em;font-weight:600}';
echo '.value{word-break:break-all}';
echo '.trace{background:#f8f8f8;border:1px solid #e2e2ea;border-radius:4px;padding:12px;font-family:monospace;font-size:0.8em;overflow:auto;max-height:300px;white-space:pre-wrap;margin-top:8px}';
echo '</style></head><body>';
echo '<div class="header">Ein Fehler ist aufgetreten</div>';
echo '<div class="content">';
// System Information
echo '<div class="section"><h3>System Information</h3>';
echo '<div class="info-grid">';
echo '<span class="label">PHP Version</span><span class="value">' . $phpVer . '</span>';
echo '<span class="label">Request URI</span><span class="value">' . $reqUri . '</span>';
echo '<span class="label">Peak Memory</span><span class="value">' . $memory . '</span>';
echo '<span class="label">Referrer</span><span class="value">' . $referrer . '</span>';
echo '</div></div>';
// Error details
echo '<div class="section"><h3>Error</h3>';
echo '<div class="info-grid">';
echo '<span class="label">Error Type</span><span class="value">' . htmlspecialchars(get_class($e)) . '</span>';
echo '<span class="label">Error Message</span><span class="value">' . htmlspecialchars($message) . '</span>';
if ($isDebug) {
echo '<span class="label">File</span><span class="value">' . htmlspecialchars($e->getFile()) . ' (' . $e->getLine() . ')</span>';
}
echo '</div>';
if ($isDebug) {
echo '<div class="trace">' . htmlspecialchars($e->getTraceAsString()) . '</div>';
} else {
echo '<p style="margin-top:12px;font-size:0.9em;opacity:0.7;">Fügen Sie <code style="background:rgba(128,128,128,0.15);padding:2px 6px;border-radius:3px;">?debug</code> an die URL an für den vollständigen Stack Trace.</p>';
}
echo '</div>';
echo '</div></body></html>';
exit;
});
set_error_handler(function (int $severity, string $message, string $file, int $line) {
if (!(error_reporting() & $severity)) return false;
throw new ErrorException($message, 0, $severity, $file, $line);
});
$devMode = isset($_GET['dev']);
// ── Re-Run-Schutz: Lockfile + .env-Detection ────────────────────────
// Wenn das Setup schon einmal erfolgreich gelaufen ist, lehnen wir
// jeden weiteren Aufruf ab — egal ob setup.php noch existiert (z.B.
// weil unlink() beim Self-Destruct fehlgeschlagen ist) oder erneut
// hochgeladen wurde. Indikatoren in absteigender Stärke:
// 1. `.setup-locked` Lockfile (definitiver Marker, vom Setup selbst
// geschrieben — sticht immer)
// 2. existierende `.env` (Heuristik — wenn die schon liegt, ist das
// System mindestens teil-installiert)
//
// Bypass: ?force_delete=confirm im Fehlerfall, ?dev=1 fuer Re-Setup
// in der lokalen Entwicklung. ?force_unlock=<token> setzt das Lockfile
// zurueck — Token muss der Operator aus den Server-Logs lesen.
$baseDir = __DIR__;
$lockFile = $baseDir . '/.setup-locked';
$envFile = $baseDir . '/.env';
$alreadyInstalled = file_exists($lockFile) || file_exists($envFile);
// Force-Unlock: erlaubt Re-Setup, wenn Operator den Token aus dem
// Server-Log uebergibt (nur lokale Filesystem-Lese-Berechtigung
// koennte den Token sehen, also kein Self-Service-Reset im Web).
if ($alreadyInstalled
&& isset($_GET['force_unlock'])
&& file_exists($lockFile)
&& hash_equals(trim((string) @file_get_contents($lockFile)), (string) $_GET['force_unlock'])
) {
@unlink($lockFile);
@unlink($envFile);
$alreadyInstalled = false;
setupLog('Setup-Lock per force_unlock zurueckgesetzt.');
}
if ($alreadyInstalled && !isset($_GET['force_delete']) && !$devMode) {
http_response_code(423);
header('Content-Type: text/html; charset=utf-8');
echo '<!DOCTYPE html><html lang="de"><head><meta charset="UTF-8"><title>Setup gesperrt</title>';
echo '<style>body{font-family:-apple-system,BlinkMacSystemFont,system-ui,sans-serif;background:#0a0a0f;color:#e4e4ed;padding:48px;max-width:720px;margin:0 auto;line-height:1.6}h1{color:#ff6b2c;font-weight:300;margin-bottom:24px}code{background:#1d1d24;padding:2px 8px;border-radius:4px;color:#ff6b2c;font-size:.9em}.box{background:#16161e;border:1px solid #2a2a3a;border-radius:8px;padding:24px;margin:24px 0}</style>';
echo '</head><body>';
echo '<h1>Setup bereits abgeschlossen</h1>';
echo '<p>Dieser Setup-Wizard wurde bereits ausgeführt. Ein erneuter Aufruf ist gesperrt, damit niemand die Datenbank versehentlich oder boeswillig zuruecksetzen kann.</p>';
echo '<div class="box"><strong>Pflicht-Schritt:</strong><br>Bitte loesche <code>setup.php</code> jetzt manuell vom Webspace. Das Lockfile <code>.setup-locked</code> sollte ebenfalls geloescht werden, sobald setup.php weg ist.</div>';
echo '<p style="opacity:.7;font-size:.9em;">Falls du das System wirklich neu installieren willst: setup.php loeschen, ' . htmlspecialchars(basename($lockFile)) . ' loeschen, .env loeschen — oder Setup-Wizard erneut hochladen und mit <code>?force_unlock=<TOKEN></code> aufrufen, wobei TOKEN der Inhalt des Lockfiles ist (per FTP/SSH lesbar).</p>';
echo '</body></html>';
exit;
}
// ── CSRF-Token für das Setup ────────────────────────────────────────
// Das Setup steht temporär öffentlich im Web — ohne Token könnte ein
// fremder Request einen halbfertigen Install auslösen. Token wird per
// Session gebunden und in allen POSTs erwartet.
if (empty($_SESSION['setup_csrf'])) {
$_SESSION['setup_csrf'] = bin2hex(random_bytes(32));
}
$csrfToken = $_SESSION['setup_csrf'];
function verifyCsrf(): bool
{
$sent = $_POST['_token'] ?? $_SERVER['HTTP_X_SETUP_TOKEN'] ?? '';
return is_string($sent) && hash_equals($_SESSION['setup_csrf'] ?? '', $sent);
}
/**
* Erzeugt einen neuen Session-CSRF-Token und gibt ihn zurück. Wird nach
* einem CSRF-Miss in den AJAX-Endpoints aufgerufen, damit der neue
* Wert in der Failure-Response mitgereicht und vom Client transparent
* übernommen werden kann (siehe `postWithCsrfRetry` im JS).
*/
function freshCsrfToken(): string
{
$_SESSION['setup_csrf'] = bin2hex(random_bytes(32));
return $_SESSION['setup_csrf'];
}
// ── Basis-Systemchecks ───────────────────────────────────────────────
$phpVersion = phpversion();
// ignis verlangt PHP 8.3 (composer.json: "php": ">=8.3") — Composer bricht
// auf älteren Versionen mit einem kryptischen Plattform-Fehler ab, deshalb
// blockiert das Setup hier früh und verständlich. CI-Baseline liegt auf 8.4.
$requiredPhpVersion = '8.3.0';
$phpVersionOk = version_compare($phpVersion, $requiredPhpVersion, '>=');
$execAvailable = function_exists('exec') && !in_array('exec', array_map('trim', explode(',', (string) ini_get('disable_functions'))), true);
$gitAvailable = false;
if ($execAvailable) {
$gitOutput = [];
$gitReturnVar = 0;
@exec('git --version 2>&1', $gitOutput, $gitReturnVar);
$gitAvailable = ($gitReturnVar === 0);
}
// PHP-Extension-Check. Jede Extension hat eine Begründung warum intraRP
// sie braucht — der Screen zeigt das als Tooltip, damit der User weiß
// *warum* `intl` oder `gd` fehlt.
$requiredExtensions = [
'pdo' => 'Datenbank-Verbindung (PDO-Basis)',
'pdo_mysql' => 'MySQL-Treiber',
'mbstring' => 'String-Handling (Twig, OAuth2)',
'openssl' => 'HTTPS, OAuth2-Tokens',
'fileinfo' => 'Upload-Validierung (MIME-Type)',
'dom' => 'XML/HTML-Parser (Twig, dompdf)',
'xml' => 'XML-Parser',
'json' => 'JSON-Serialisierung',
'session' => 'Benutzer-Sessions',
'intl' => 'Internationalisierung (Validation, Formatierung)',
'zip' => 'Release-ZIP entpacken',
'curl' => 'HTTPS-Downloads (GitHub, Discord)',
'filter' => 'Input-Validierung',
'ctype' => 'String-Validierung',
];
$extensionStatus = [];
$missingRequired = [];
foreach ($requiredExtensions as $ext => $purpose) {
$loaded = extension_loaded($ext);
$extensionStatus[$ext] = ['ok' => $loaded, 'purpose' => $purpose];
if (!$loaded) {
$missingRequired[] = $ext;
}
}
// GD ODER Imagick — PDF-Rendering braucht eins von beiden
$hasGd = extension_loaded('gd');
$hasImagick = extension_loaded('imagick');
$extensionStatus['gd/imagick'] = [
'ok' => $hasGd || $hasImagick,
'purpose' => 'PDF-Generierung (dompdf) — ' . ($hasGd ? 'gd aktiv' : ($hasImagick ? 'imagick aktiv' : 'FEHLT')),
];
if (!($hasGd || $hasImagick)) {
$missingRequired[] = 'gd/imagick';
}
$allExtensionsOk = empty($missingRequired);
function parsePhpSize($size)
{
$size = trim((string) $size);
$unit = strtolower(substr($size, -1));
$value = (int) $size;
return match ($unit) {
'g' => $value * 1024,
'm' => $value,
'k' => $value / 1024,
default => $value / (1024 * 1024),
};
}
$phpLimits = [
'memory_limit' => ['current' => ini_get('memory_limit'), 'recommended' => 512, 'unit' => 'M'],
'max_execution_time' => ['current' => ini_get('max_execution_time'), 'recommended' => 300, 'unit' => 's'],
'upload_max_filesize' => ['current' => ini_get('upload_max_filesize'), 'recommended' => 256, 'unit' => 'M'],
'post_max_size' => ['current' => ini_get('post_max_size'), 'recommended' => 256, 'unit' => 'M'],
];
$phpLimitsOk = true;
$phpLimitWarnings = [];
foreach ($phpLimits as $key => $limit) {
if ($key === 'max_execution_time') {
$currentVal = (int) $limit['current'];
$ok = ($currentVal === 0 || $currentVal >= $limit['recommended']);
$currentDisplay = $currentVal === 0 ? 'Unbegrenzt' : $currentVal . 's';
} else {
$currentVal = parsePhpSize($limit['current']);
$ok = ($limit['current'] === '-1' || $currentVal >= $limit['recommended']);
$currentDisplay = $limit['current'] === '-1' ? 'Unbegrenzt' : $limit['current'];
}
$phpLimits[$key]['ok'] = $ok;
$phpLimits[$key]['display'] = $currentDisplay;
if (!$ok) {
$phpLimitsOk = false;
$phpLimitWarnings[] = "{$key}: {$currentDisplay} (empfohlen: {$limit['recommended']}{$limit['unit']})";
}
}
$curlAvailable = function_exists('curl_init');
$allowUrlFopen = (bool) ini_get('allow_url_fopen');
/**
* Mitgeliefertes Release-Archiv neben setup.php suchen (Install-Package).
* Liegt ein ignis-*.zip / intraRP-*.zip im selben Verzeichnis, wird es
* direkt entpackt — kein GitHub-Download nötig. Bei mehreren Treffern
* gewinnt alphabetisch das letzte (= höchste Version).
*/
function findBundledArchive(): ?string
{
foreach (['ignis-*.zip', 'intraRP-*.zip'] as $pattern) {
$matches = glob(__DIR__ . DIRECTORY_SEPARATOR . $pattern);
if (!empty($matches)) {
sort($matches, SORT_NATURAL);
return end($matches);
}
}
return null;
}
$bundledArchive = findBundledArchive();
// Writable-Check auf das Verzeichnis in dem setup.php liegt — dort wird
// die .env geschrieben und das ZIP extrahiert. Wenn das nicht writable
// ist, kann das Setup sofort scheitern, ohne vorher 100MB runterzuladen.
$setupDir = __DIR__;
$setupDirWritable = is_writable($setupDir);
// ── Rate-Limit gegen Setup-Bruteforce ────────────────────────────────
// Token + IP-Rate-Limit verhindern, dass ein Bot das Setup 1000× pro
// Minute aufruft und Downloads triggert.
$rateLimitKey = 'setup_rate_' . sha1($_SERVER['REMOTE_ADDR'] ?? 'unknown');
if (!isset($_SESSION[$rateLimitKey])) {
$_SESSION[$rateLimitKey] = ['count' => 0, 'reset' => time() + 60];
}
if (time() > $_SESSION[$rateLimitKey]['reset']) {
$_SESSION[$rateLimitKey] = ['count' => 0, 'reset' => time() + 60];
}
function hitRateLimit(int $max = 20): bool
{
global $rateLimitKey;
$_SESSION[$rateLimitKey]['count']++;
return $_SESSION[$rateLimitKey]['count'] > $max;
}
// ── HTTP-Helper ──────────────────────────────────────────────────────
function httpGet(string $url, ?string $saveTo = null, int $timeout = 30, array $extraHeaders = []): array
{
$headers = array_merge(['User-Agent: ignis-Setup'], $extraHeaders);
if (function_exists('curl_init')) {
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_HTTPHEADER => $headers,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 5,
CURLOPT_TIMEOUT => $timeout,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_HEADER => false,
]);
if ($saveTo) {
$fp = fopen($saveTo, 'wb');
if (!$fp) {
return ['ok' => false, 'error' => 'Konnte Zieldatei nicht erstellen: ' . $saveTo];
}
curl_setopt($ch, CURLOPT_FILE, $fp);
// Real-time progress reporting via callback
curl_setopt($ch, CURLOPT_NOPROGRESS, false);
$lastProgress = 0;
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION,
function ($resource, $dlTotal, $dlNow, $ulTotal, $ulNow) use (&$lastProgress) {
if ($dlTotal > 0) {
$pct = (int)(($dlNow / $dlTotal) * 100);
// Only write every 5% to avoid I/O spam
if ($pct >= $lastProgress + 5 || $pct === 100) {
$lastProgress = $pct;
$mbNow = round($dlNow / 1048576, 1);
$mbTotal = round($dlTotal / 1048576, 1);
writeProgress('download', "{$mbNow} MB / {$mbTotal} MB", $pct);
}
}
return 0; // 0 = continue, non-zero = abort
}
);
} else {
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
}
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
unset($ch);
if ($saveTo) {
fclose($fp);
if ($httpCode >= 400 || !empty($curlError)) {
@unlink($saveTo);
return ['ok' => false, 'error' => $curlError ?: "HTTP {$httpCode}", 'http_code' => $httpCode];
}
return ['ok' => true];
}
if ($httpCode >= 400 || $result === false) {
return ['ok' => false, 'error' => $curlError ?: "HTTP {$httpCode}", 'http_code' => $httpCode];
}
return ['ok' => true, 'body' => $result, 'http_code' => $httpCode];
}
if (!ini_get('allow_url_fopen')) {
return ['ok' => false, 'error' => 'Weder cURL noch allow_url_fopen verfügbar.'];
}
$context = stream_context_create(['http' => [
'header' => implode("\r\n", $headers),
'timeout' => $timeout,
'follow_location' => true,
'max_redirects' => 5,
]]);
if ($saveTo) {
$source = @fopen($url, 'rb', false, $context);
if (!$source) {
return ['ok' => false, 'error' => 'Konnte URL nicht öffnen: ' . $url];
}
$dest = @fopen($saveTo, 'wb');
if (!$dest) {
fclose($source);
return ['ok' => false, 'error' => 'Konnte Zieldatei nicht erstellen.'];
}
while (!feof($source)) {
fwrite($dest, fread($source, 8192));
}
fclose($source);
fclose($dest);
return ['ok' => true];
}
$result = @file_get_contents($url, false, $context);
if ($result === false) {
return ['ok' => false, 'error' => 'Verbindung fehlgeschlagen: ' . $url];
}
return ['ok' => true, 'body' => $result];
}
// Defaults für BASE_PATH / DOMAIN
$defaultDomain = $_SERVER['HTTP_HOST'] ?? 'localhost';
$scriptDir = dirname($_SERVER['SCRIPT_NAME'] ?? '/');
$defaultBasePath = ($scriptDir === '/' || $scriptDir === '\\') ? '/' : rtrim($scriptDir, '/\\') . '/';
// ── Sanitize / Escape-Helper ─────────────────────────────────────────
function sanitizeEnvValue(string $value): string
{
$value = str_replace(["\r", "\n"], '', $value);
return trim($value);
}
function formatEnvValue(string $value): string
{
$value = sanitizeEnvValue($value);
$value = str_replace(['\\', '"'], ['\\\\', '\\"'], $value);
return '"' . $value . '"';
}
// Das Setup log-buffert Fehler in der Session statt in einer Datei, die
// nach erfolgreichem Setup liegenbleiben könnte und ggf. Credentials/Pfade
// leaked. Bei `?debug` werden die Einträge unten im UI angezeigt.
function setupLog(string $message): void
{
if (!isset($_SESSION['setup_log'])) {
$_SESSION['setup_log'] = [];
}
$_SESSION['setup_log'][] = '[' . date('Y-m-d H:i:s') . '] ' . $message;
}
// Validator für Custom-Branch-Namen. Whitelist statt escapeshellarg:
// escapeshellarg schützt vor Injection, erlaubt aber weiterhin exotische
// Zeichen die Git verwirren würden.
function isValidBranchName(string $name): bool
{
return (bool) preg_match('~^[a-zA-Z0-9._/\\-]{1,100}$~', $name)
&& !str_contains($name, '..');
}
// BASE_PATH muss ein absoluter HTTP-Pfad sein. Regex verhindert Traversal
// und Shell-Metazeichen in der .env.
function isValidBasePath(string $path): bool
{
return (bool) preg_match('~^/[a-zA-Z0-9._/\\-]*$~', $path)
&& !str_contains($path, '..');
}
// Domain — keine Schemes, kein Pfad, erlaubte Zeichen
function isValidDomain(string $domain): bool
{
return (bool) preg_match('~^[a-zA-Z0-9.\\-]{1,253}(:[0-9]{1,5})?$~', $domain);
}
// ── AJAX: Setup-Fortschritt abfragen ─────────────────────────────────
// Der Setup-POST schreibt Fortschritt in ein Temp-File. Dieses Endpoint
// liest es aus und gibt den aktuellen Stand als JSON zurück.
if (($_GET['action'] ?? '') === 'progress') {
header('Content-Type: application/json');
$progressFile = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'intrarp_setup_progress_' . session_id() . '.json';
if (file_exists($progressFile)) {
$data = @file_get_contents($progressFile);
echo $data ?: '{"phase":"waiting"}';
} else {
echo '{"phase":"waiting"}';
}
exit;
}
// ── Progress-Helper ─────────────────────────────────────────────────
function writeProgress(string $phase, string $detail = '', int $percent = 0): void {
$file = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'intrarp_setup_progress_' . session_id() . '.json';
$data = json_encode([
'phase' => $phase,
'detail' => $detail,
'percent' => $percent,
'time' => time(),
]);
@file_put_contents($file, $data, LOCK_EX);
}
function cleanupProgress(): void {
$file = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'intrarp_setup_progress_' . session_id() . '.json';
@unlink($file);
}
// ── AJAX: Datenbankverbindung testen ─────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'test_db') {
header('Content-Type: application/json');
if (!verifyCsrf()) {
echo json_encode([
'success' => false,
'message' => 'CSRF-Token ungültig. Seite neu laden.',
'csrf_token' => freshCsrfToken(),
'csrf_retry' => true,
]);
exit;
}
if (hitRateLimit()) {
echo json_encode(['success' => false, 'message' => 'Zu viele Anfragen — bitte kurz warten.']);
exit;
}
$host = sanitizeEnvValue($_POST['db_host'] ?? 'localhost');
$port = (int) ($_POST['db_port'] ?? 3306);
$user = sanitizeEnvValue($_POST['db_user'] ?? 'root');
$pass = sanitizeEnvValue($_POST['db_pass'] ?? '');
$name = sanitizeEnvValue($_POST['db_name'] ?? '');
if (empty($name)) {
echo json_encode(['success' => false, 'message' => 'Datenbank-Name ist erforderlich.']);
exit;
}
try {
$dsn = 'mysql:host=' . $host . ';port=' . ($port ?: 3306) . ';dbname=' . $name . ';charset=utf8mb4';
$pdo = new PDO($dsn, $user, $pass, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_TIMEOUT => 5,
]);
$serverVersion = $pdo->getAttribute(PDO::ATTR_SERVER_VERSION);
echo json_encode(['success' => true, 'message' => 'Verbindung erfolgreich! (Server: MySQL ' . $serverVersion . ')']);
} catch (PDOException $e) {
$msg = $e->getMessage();
if (str_contains($msg, 'Access denied')) {
$msg = 'Zugriff verweigert – Benutzername oder Passwort falsch.';
} elseif (str_contains($msg, 'Unknown database')) {
$msg = 'Die Datenbank "' . htmlspecialchars($name) . '" existiert nicht.';
} elseif (str_contains($msg, 'Connection refused') || str_contains($msg, 'No such file or directory')) {
$msg = 'Verbindung zum Host "' . htmlspecialchars($host) . '" fehlgeschlagen – Server nicht erreichbar.';
} elseif (str_contains($msg, 'getaddrinfo') || str_contains($msg, 'Name or service not known')) {
$msg = 'Der Host "' . htmlspecialchars($host) . '" konnte nicht aufgelöst werden.';
}
echo json_encode(['success' => false, 'message' => $msg]);
}
exit;
}
// ── AJAX: Discord Credentials testen ─────────────────────────────────
// Probe gegen den /oauth2/token-Endpoint mit Client-Credentials-Grant.
// Discord gibt hier entweder ein Token oder einen sauberen Fehler
// (invalid_client) zurück — reicht völlig aus, um falsche Credentials
// abzufangen, bevor der User das Setup durchzieht.
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'test_discord') {
header('Content-Type: application/json');
if (!verifyCsrf()) {
echo json_encode([
'success' => false,
'message' => 'CSRF-Token ungültig. Seite neu laden.',
'csrf_token' => freshCsrfToken(),
'csrf_retry' => true,
]);
exit;
}
if (hitRateLimit()) {
echo json_encode(['success' => false, 'message' => 'Zu viele Anfragen — bitte kurz warten.']);
exit;
}
$clientId = sanitizeEnvValue($_POST['discord_client_id'] ?? '');
$clientSecret = sanitizeEnvValue($_POST['discord_client_secret'] ?? '');
if ($clientId === '' || $clientSecret === '') {
echo json_encode(['success' => false, 'message' => 'Client ID und Secret erforderlich.']);
exit;
}
if (!preg_match('~^\d{17,20}$~', $clientId)) {
echo json_encode(['success' => false, 'message' => 'Client ID muss eine 17–20-stellige Zahl sein (Discord Snowflake).']);
exit;
}
if (!function_exists('curl_init')) {
echo json_encode(['success' => true, 'message' => 'Format gültig. cURL nicht verfügbar — Live-Test übersprungen.']);
exit;
}
$ch = curl_init('https://discord.com/api/v10/oauth2/token');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 8,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_USERPWD => $clientId . ':' . $clientSecret,
CURLOPT_HTTPHEADER => [
'Content-Type: application/x-www-form-urlencoded',
'User-Agent: ignis-Setup',
],
CURLOPT_POSTFIELDS => http_build_query([
'grant_type' => 'client_credentials',
'scope' => 'identify',
]),
]);
$body = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$err = curl_error($ch);
unset($ch);
if ($body === false || $code === 0) {
echo json_encode(['success' => false, 'message' => 'Discord nicht erreichbar: ' . ($err ?: 'unbekannt')]);
exit;
}
$data = json_decode((string) $body, true) ?: [];
if ($code === 200 && !empty($data['access_token'])) {
echo json_encode(['success' => true, 'message' => 'Discord-Credentials gültig.']);
exit;
}
$reason = $data['error_description'] ?? $data['error'] ?? "HTTP {$code}";
if (($data['error'] ?? '') === 'invalid_client') {
$reason = 'Client ID oder Secret ist falsch.';
}
echo json_encode(['success' => false, 'message' => 'Discord lehnte ab: ' . $reason]);
exit;
}
// ── force_delete — manueller Self-Destruct bei Fehlerzuständen ───────
if (isset($_GET['force_delete']) && $_GET['force_delete'] === 'confirm') {
$setupFile = __FILE__;
@unlink($setupFile);
clearstatcache(true, $setupFile);
if (!file_exists($setupFile)) {
header('Location: index.php');
exit;
}
die('Fehler: setup.php konnte nicht gelöscht werden. Bitte manuell entfernen.');
}
// ── Flow-Status für das HTML ─────────────────────────────────────────
$errors = [];
$success = [];
$downloadMethodOk = $curlAvailable || $allowUrlFopen;
// Mit mitgeliefertem Archiv ist kein Download nötig — die fehlende
// Download-Methode blockiert das Setup dann nicht.
$canProceed = $phpVersionOk
&& ($downloadMethodOk || $bundledArchive !== null)
&& class_exists('ZipArchive')
&& $allExtensionsOk
&& $setupDirWritable;
if (!$phpVersionOk) {
$errors[] = "PHP Version {$phpVersion} ist zu alt. Mindestens PHP {$requiredPhpVersion} wird benötigt!";
setupLog("PHP Version Check fehlgeschlagen: {$phpVersion} < {$requiredPhpVersion}");
}
if (!$allExtensionsOk) {
$errors[] = 'Fehlende PHP-Extensions: ' . implode(', ', $missingRequired);
setupLog('Fehlende PHP-Extensions: ' . implode(', ', $missingRequired));
}
if (!$setupDirWritable) {
$errors[] = 'Das Setup-Verzeichnis ist nicht beschreibbar — ZIP/.env können nicht geschrieben werden.';
setupLog('Setup-Dir nicht writable: ' . $setupDir);
}
$isAjaxSetup = ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_SERVER['HTTP_X_SETUP_AJAX']));
/**
* Versucht GitHub-API → bei 403 (Rate-Limit) Fallback via Redirect-Parse
* von github.com/<owner>/<repo>/releases/latest, das ohne Auth die Tag
* in der Location-Header zurückgibt.
*/
function fetchLatestRelease(string $repoOwner, string $repoName): array
{
$apiUrl = "https://api.github.com/repos/{$repoOwner}/{$repoName}/releases/latest";
$apiResult = httpGet($apiUrl, null, 30, ['Accept: application/vnd.github+json']);
if ($apiResult['ok']) {
$release = json_decode($apiResult['body'], true);
if ($release && !empty($release['tag_name'])) {
return ['ok' => true, 'release' => $release, 'source' => 'api'];
}
}
// Fallback: Non-API redirect. `/releases/latest` HTTP-301t auf
// `/releases/tag/<tag>` weiter. Wir folgen nicht, parsen den Header.
if (function_exists('curl_init')) {
$ch = curl_init("https://github.com/{$repoOwner}/{$repoName}/releases/latest");
curl_setopt_array($ch, [
CURLOPT_NOBODY => true,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['User-Agent: ignis-Setup'],
CURLOPT_TIMEOUT => 10,
]);
curl_exec($ch);
$redirect = curl_getinfo($ch, CURLINFO_REDIRECT_URL);
unset($ch);
if ($redirect && preg_match('~/releases/tag/([^/?#]+)~', $redirect, $m)) {
$tag = $m[1];
// Asset-Name raten anhand der Konvention "ignis-<tag>.zip"
// (Legacy-Fallback "intraRP-<tag>.zip" wird vom GitHub-Release parallel mitgeliefert.)
$zipName = 'ignis-' . ltrim($tag, 'v') . '.zip';
$zipUrl = "https://github.com/{$repoOwner}/{$repoName}/releases/download/{$tag}/{$zipName}";
return [
'ok' => true,
'source' => 'fallback',
'release' => [
'tag_name' => $tag,
'assets' => [[
'name' => $zipName,
'browser_download_url' => $zipUrl,
]],
],
];
}
}
return ['ok' => false, 'error' => $apiResult['error'] ?? 'Unbekannter GitHub-Fehler'];
}
/**
* Bootstrap Phinx programmatisch und führt alle ausstehenden Migrations
* aus. Liest die DB-Credentials aus der bereits geschriebenen .env.
* Return: ['ok' => bool, 'output' => string]
*/
function runPhinxMigrations(string $baseDir): array
{
$autoload = $baseDir . '/vendor/autoload.php';
$phinxCfg = $baseDir . '/phinx.php';
if (!file_exists($autoload)) {
return ['ok' => false, 'output' => 'vendor/autoload.php fehlt — kein Composer-Install vorhanden.'];
}
if (!file_exists($phinxCfg)) {
return ['ok' => false, 'output' => 'phinx.php fehlt im Projekt-Root.'];
}
try {
require_once $autoload;
if (!class_exists(\Phinx\Console\PhinxApplication::class)) {
return ['ok' => false, 'output' => 'Phinx ist in vendor/ nicht verfügbar.'];
}
// phinx.php liest DB-Credentials aus $_ENV — wir sourcen die .env
// die gerade geschrieben wurde, damit Phinx die richtigen
// Credentials sieht.
if (class_exists(\Dotenv\Dotenv::class) && file_exists($baseDir . '/.env')) {
$dotenv = \Dotenv\Dotenv::createImmutable($baseDir);
$dotenv->safeLoad();
}
$app = new \Phinx\Console\PhinxApplication();
$app->setAutoExit(false);
$input = new \Symfony\Component\Console\Input\ArrayInput([
'command' => 'migrate',
'--configuration' => $phinxCfg,
'--environment' => 'production',
]);
$output = new \Symfony\Component\Console\Output\BufferedOutput();
$exitCode = $app->run($input, $output);
$outputText = $output->fetch();
return [
'ok' => $exitCode === 0,
'output' => $outputText,
];
} catch (\Throwable $e) {
return ['ok' => false, 'output' => 'Exception: ' . $e->getMessage()];
}
}
/**
* Lädt composer.phar herunter und führt `install --no-dev -o` im
* Zielverzeichnis aus. Gibt bei fehlendem exec() einen klaren Fehler
* zurück, damit der Client dem User Anleitung zeigen kann.
*/
function installComposer(string $baseDir, bool $execAvailable): array
{
if (!$execAvailable) {
return [
'ok' => false,
'output' => 'exec() ist auf diesem Server deaktiviert.',
'manual' => true,
];
}
$composerPhar = $baseDir . '/composer.phar';
if (!file_exists($composerPhar)) {
$dl = httpGet('https://getcomposer.org/composer-stable.phar', $composerPhar, 120);
if (!$dl['ok']) {
return [
'ok' => false,
'output' => 'composer.phar Download fehlgeschlagen: ' . ($dl['error'] ?? ''),
'manual' => true,
];
}
}
$phpBin = defined('PHP_BINARY') ? PHP_BINARY : 'php';
$cwd = getcwd();
@chdir($baseDir);
$cmd = escapeshellarg($phpBin) . ' '
. escapeshellarg($composerPhar) . ' install --no-dev --no-interaction --prefer-dist --optimize-autoloader 2>&1';
$execOutput = [];
$execReturn = 1;
@exec($cmd, $execOutput, $execReturn);
@chdir($cwd);
return [
'ok' => $execReturn === 0,
'output' => implode("\n", $execOutput),
'manual' => false,
];
}
/**
* Verifiziert ZIP-Integrität per SHA256 gegen den Digest aus der Release-
* Response (kommt als "sha256:xxxxx"). Fällt stumm durch, wenn kein
* Digest bekannt ist — GitHub liefert den nicht bei allen Releases.
*/
function verifyZipDigest(string $zipPath, ?string $expectedDigest): array
{
if (!$expectedDigest) {
return ['ok' => true, 'skipped' => true];
}
if (!preg_match('~^sha256:([a-f0-9]{64})$~i', $expectedDigest, $m)) {
return ['ok' => true, 'skipped' => true];
}
$actual = hash_file('sha256', $zipPath);
if (!hash_equals(strtolower($m[1]), strtolower((string) $actual))) {
return [
'ok' => false,
'error' => 'SHA256-Prüfsumme stimmt nicht — Download könnte manipuliert oder korrupt sein.',
];
}
return ['ok' => true];
}
/**
* Prüft nach dem Entpacken, ob alle storage/-Unterverzeichnisse
* tatsächlich writable sind. Versucht chmod als letzten Ausweg.
*/
function checkStorageWritables(string $baseDir): array
{
$dirs = [
'storage/cache',
'storage/documents',
'storage/logs',
'storage/temp',
'storage/template-assets',
];
$warnings = [];
foreach ($dirs as $rel) {
$abs = $baseDir . '/' . $rel;
if (!is_dir($abs)) {
@mkdir($abs, 0775, true);
}
if (!is_writable($abs)) {
@chmod($abs, 0775);
clearstatcache(true, $abs);
if (!is_writable($abs)) {
$warnings[] = $rel . ' ist nicht beschreibbar — bitte chmod 0775 setzen.';
}
}
}
return $warnings;
}
/**
* Sichere Git-Clone/-Pull-Wrapper mit escapeshellarg + Whitelist-Check,
* und Safeguard gegen versehentliches reset auf fremde Repos.
*/
function runGitInstall(string $baseDir, string $branchMode, string $customBranch, bool $execAvailable): array
{
if (!$execAvailable) {
return ['ok' => false, 'error' => 'exec() ist deaktiviert — Branch-Install nicht möglich.'];
}
$repoUrl = 'https://github.com/EmergencyForge/intraRP.git';
$expected = 'EmergencyForge/intraRP';
$branch = $branchMode === 'custom' ? $customBranch : 'main';
if (!isValidBranchName($branch)) {
return ['ok' => false, 'error' => 'Ungültiger Branch-Name.'];
}
$cwd = getcwd();
@chdir($baseDir);
$cmds = [];
$log = [];
if (!is_dir($baseDir . '/.git')) {
// Frisches Repo — init + remote + fetch + checkout
$cmds[] = 'git init 2>&1';
$cmds[] = 'git remote add origin ' . escapeshellarg($repoUrl) . ' 2>&1';
$cmds[] = 'git fetch origin ' . escapeshellarg($branch) . ' 2>&1';
$cmds[] = 'git checkout -b ' . escapeshellarg($branch) . ' ' . escapeshellarg('origin/' . $branch) . ' 2>&1';
$cmds[] = 'git reset --hard ' . escapeshellarg('origin/' . $branch) . ' 2>&1';
} else {
// Existierendes .git — prüfen ob Remote wirklich EmergencyForge/intraRP ist
$remoteOutput = [];
@exec('git remote get-url origin 2>&1', $remoteOutput);
$remoteUrl = trim((string) ($remoteOutput[0] ?? ''));
if (!str_contains($remoteUrl, $expected)) {
@chdir($cwd);
return [
'ok' => false,
'error' => 'Bestehendes .git-Verzeichnis zeigt auf ' . htmlspecialchars($remoteUrl) . ' statt ' . $expected . ' — Setup abgebrochen, um fremde Repos nicht zu überschreiben.',
];
}
$cmds[] = 'git fetch origin ' . escapeshellarg($branch) . ' 2>&1';
$cmds[] = 'git checkout ' . escapeshellarg($branch) . ' 2>&1';
$cmds[] = 'git reset --hard ' . escapeshellarg('origin/' . $branch) . ' 2>&1';
}
foreach ($cmds as $cmd) {
$out = [];
$rc = 1;
@exec($cmd, $out, $rc);
$log[] = '$ ' . $cmd . "\n" . implode("\n", $out);
if ($rc !== 0) {
@chdir($cwd);
return ['ok' => false, 'error' => 'Git-Fehler bei: ' . $cmd, 'log' => implode("\n\n", $log)];
}
}
@chdir($cwd);
return ['ok' => true, 'log' => implode("\n\n", $log)];
}
// ── Haupt-Setup-Flow (POST ohne `action`) ────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $canProceed && !isset($_POST['action'])) {
if (!verifyCsrf()) {
$errors[] = 'CSRF-Token ungültig. Bitte Seite neu laden und erneut versuchen.';
if ($isAjaxSetup) {
header('Content-Type: application/json');
echo json_encode(['success' => false, 'errors' => $errors]);
exit;
}
}
if (empty($errors) && hitRateLimit()) {
$errors[] = 'Zu viele Setup-Versuche in kurzer Zeit. Bitte kurz warten.';
}
$gitBranch = $_POST['git_branch'] ?? ($bundledArchive !== null ? 'local' : 'release');
$customBranch = trim($_POST['custom_branch'] ?? '');
// Whitelist
if (!in_array($gitBranch, ['local', 'release', 'main', 'custom'], true)) {
$errors[] = 'Ungültiger Branch-Modus.';
$gitBranch = $bundledArchive !== null ? 'local' : 'release';
}
if ($gitBranch === 'local' && $bundledArchive === null) {
$errors[] = 'Kein mitgeliefertes Archiv (ignis-*.zip) neben setup.php gefunden.';
}
if ($gitBranch === 'custom' && !isValidBranchName($customBranch)) {
$errors[] = 'Custom Branch-Name enthält ungültige Zeichen.';
}