-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstaller.php
More file actions
3261 lines (2928 loc) · 140 KB
/
installer.php
File metadata and controls
3261 lines (2928 loc) · 140 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
declare(strict_types=1);
/**
* Webkernel Installer
*
* Single-file installer for the Webkernel framework.
* Operates in both HTTP (browser) and CLI modes without code duplication.
*
* @package webkernel/installer
* @repository https://github.com/webkernelphp/webkernel
* @packagist https://packagist.org/packages/webkernel/webkernel
* @license Webkernel Unified License + EPL Eclipse v2
* @requires PHP 8.4+
*/
// ---------------------------------------------------------------------------
// Bootstrap: enforce PHP version before any class declarations
// ---------------------------------------------------------------------------
if (PHP_VERSION_ID < 80400) {
$msg = sprintf('Webkernel requires PHP 8.4+. Found: %s', PHP_VERSION);
if (PHP_SAPI === 'cli') {
fwrite(STDERR, '[ERROR] ' . $msg . PHP_EOL);
exit(1);
}
http_response_code(500);
header('Content-Type: text/plain; charset=UTF-8');
echo $msg;
exit(1);
}
// ---------------------------------------------------------------------------
// Installer version & Webkernel codenames
// ---------------------------------------------------------------------------
const WEBKERNEL_INSTALLER_VERSION = '0.1.0';
/**
* Returns the codename series for a given Webkernel major version.
*
* @param int $major Major version number extracted from a semver string.
* @return string Human-readable codename series.
*/
function webkernelCodename(int $major): string
{
return match ($major) {
1 => 'Waterfall',
2 => 'Greenfields',
3 => 'Forester',
4 => 'Wildlife',
5 => 'Universe',
default => 'Unknown',
};
}
/**
* Attempts to read the installed Webkernel package version from composer.lock
* or the package composer.json inside vendor.
*
* @param string $targetDirectory Absolute path to the installation target.
* @return string|null Semver string or null when not determinable.
*/
function resolveWebkernelVersion(string $targetDirectory): ?string
{
$lockFile = rtrim($targetDirectory, '/') . '/composer.lock';
if (is_file($lockFile)) {
$lock = json_decode((string) file_get_contents($lockFile), true);
if (is_array($lock)) {
foreach ((array) ($lock['packages'] ?? []) as $pkg) {
if (($pkg['name'] ?? '') === 'webkernel/webkernel') {
$v = ltrim((string) ($pkg['version'] ?? ''), 'v');
return $v !== '' ? $v : null;
}
}
}
}
return null;
}
/**
* Strip ANSI escape sequences from a string.
* Defined as a global function — callable from any class or context.
*
* @param string $text Raw text potentially containing ANSI codes.
* @return string Clean text.
*/
function stripAnsi(string $text): string
{
return (string) preg_replace('/\x1B\[[0-9;]*[A-Za-z]|\x1B\[[0-9]*[A-Za-z]|\x1B\].*?\x07/u', '', $text);
}
/**
* Detect whether Webkernel is already installed in a given directory.
* Checks for the canonical markers that are only present after a successful install.
*
* @param string $directory Absolute path to the target directory.
* @return bool
*/
function is_webkernel_installed(string $directory): bool
{
$dir = rtrim($directory, '/');
// Must have composer.json with correct package name
$composerJson = $dir . '/composer.json';
if (!is_file($composerJson)) {
return false;
}
$decoded = json_decode((string) file_get_contents($composerJson), true);
if (!is_array($decoded) || ($decoded['name'] ?? '') !== 'webkernel/webkernel') {
return false;
}
// Must have vendor autoloader (Composer install completed)
if (!is_file($dir . '/vendor/autoload.php')) {
return false;
}
// Must have artisan (Laravel framework in place)
if (!is_file($dir . '/artisan')) {
return false;
}
return true;
}
// ---------------------------------------------------------------------------
// Interfaces
// ---------------------------------------------------------------------------
interface InstallerStageInterface
{
/** @return non-empty-string */
public function name(): string;
/** @return non-empty-string */
public function label(): string;
public function execute(InstallerContext $context): StageResult;
}
interface SessionStorageInterface
{
public function read(string $sessionId): ?InstallerSession;
public function write(InstallerSession $session): void;
public function delete(string $sessionId): void;
public function exists(string $sessionId): bool;
}
interface OutputInterface
{
public function info(string $message): void;
public function error(string $message): void;
public function success(string $message): void;
public function warning(string $message): void;
}
// ---------------------------------------------------------------------------
// Enums
// ---------------------------------------------------------------------------
enum InstallerPhase: string
{
case Preflight = 'preflight';
case Download = 'download';
case Verify = 'verify';
case Extract = 'extract';
case Configure = 'configure';
case Complete = 'complete';
case Failed = 'failed';
public function label(): string
{
return match ($this) {
self::Preflight => 'Preparation',
self::Download => 'Download',
self::Verify => 'Verification',
self::Extract => 'Extraction',
self::Configure => 'Configuration',
self::Complete => 'Complete',
self::Failed => 'Failed',
};
}
public function ordinal(): int
{
return match ($this) {
self::Preflight => 0,
self::Download => 1,
self::Verify => 2,
self::Extract => 3,
self::Configure => 4,
self::Complete => 5,
self::Failed => 6,
};
}
}
enum StageStatus: string
{
case Pending = 'pending';
case Running = 'running';
case Success = 'success';
case Failed = 'failed';
case Skipped = 'skipped';
}
enum ComposerState: string
{
case NotFound = 'not_found';
case OutdatedLocal = 'outdated_local';
case PharAvailable = 'phar_available';
case SystemOk = 'system_ok';
}
// ---------------------------------------------------------------------------
// Value Objects
// ---------------------------------------------------------------------------
final class InstallPath
{
private function __construct(
public readonly string $target,
public readonly string $userspace,
public readonly string $sessionBase,
) {}
public static function resolve(string $targetDirectory): self
{
$home = InstallerEnvironment::resolveHomeDirectory();
$hash = hash('sha256', realpath($targetDirectory) ?: $targetDirectory);
$userspace = $home . '/webkernel/installer/' . $hash;
return new self(
target: $targetDirectory,
userspace: $userspace,
sessionBase: $userspace . '/sessions',
);
}
public function sessionDirectory(string $sessionId): string
{
return $this->sessionBase . '/' . $sessionId;
}
public function composerPharPath(): string
{
return $this->userspace . '/composer.phar';
}
public function ensure(): void
{
foreach ([$this->userspace, $this->sessionBase] as $dir) {
if (!is_dir($dir)) {
mkdir($dir, 0700, true);
}
}
}
}
final class SecurityToken
{
private function __construct(
public readonly string $value,
public readonly int $createdAt,
) {}
public static function generate(): self
{
return new self(bin2hex(random_bytes(32)), time());
}
public static function fromRaw(string $value, int $createdAt): self
{
return new self($value, $createdAt);
}
public function verify(string $provided): bool
{
return hash_equals($this->value, $provided);
}
public function isExpired(int $ttlSeconds = 86400): bool
{
return (time() - $this->createdAt) > $ttlSeconds;
}
}
// ---------------------------------------------------------------------------
// Stage Result
// ---------------------------------------------------------------------------
final class StageResult
{
/** @param string[] $log */
private function __construct(
public readonly StageStatus $status,
public readonly string $message,
public readonly array $log = [],
) {}
/** @param string[] $log */
public static function success(string $message, array $log = []): self
{
return new self(StageStatus::Success, $message, $log);
}
/** @param string[] $log */
public static function failure(string $message, array $log = []): self
{
return new self(StageStatus::Failed, $message, $log);
}
public static function skipped(string $message): self
{
return new self(StageStatus::Skipped, $message);
}
}
// ---------------------------------------------------------------------------
// Installer Session
// ---------------------------------------------------------------------------
final class InstallerSession
{
/** @param string[] $log @param array<string, mixed> $stageData */
public function __construct(
public readonly string $id,
public InstallerPhase $phase,
public readonly InstallPath $paths,
public readonly SecurityToken $token,
public readonly int $startedAt,
public array $log,
public array $stageData,
public bool $locked,
public int $lastActivity,
) {}
public static function create(InstallPath $paths): self
{
$id = bin2hex(random_bytes(16));
return new self(
id: $id,
phase: InstallerPhase::Preflight,
paths: $paths,
token: SecurityToken::generate(),
startedAt: time(),
log: [],
stageData: [],
locked: false,
lastActivity: time(),
);
}
public function appendLog(string $line): void
{
$this->log[] = '[' . date('H:i:s') . '] ' . $line;
$this->lastActivity = time();
}
public function advanceTo(InstallerPhase $phase): void
{
$this->phase = $phase;
$this->lastActivity = time();
}
/** @return array<string, mixed> */
public function toArray(): array
{
return [
'id' => $this->id,
'phase' => $this->phase->value,
'token' => $this->token->value,
'token_at' => $this->token->createdAt,
'started_at' => $this->startedAt,
'log' => $this->log,
'stage_data' => $this->stageData,
'locked' => $this->locked,
'last_activity' => $this->lastActivity,
'target' => $this->paths->target,
];
}
/** @param array<string, mixed> $data */
public static function fromArray(array $data, InstallPath $paths): self
{
return new self(
id: (string) $data['id'],
phase: InstallerPhase::from((string) $data['phase']),
paths: $paths,
token: SecurityToken::fromRaw((string) $data['token'], (int) $data['token_at']),
startedAt: (int) $data['started_at'],
log: (array) $data['log'],
stageData: (array) ($data['stage_data'] ?? []),
locked: (bool) $data['locked'],
lastActivity: (int) $data['last_activity'],
);
}
}
// ---------------------------------------------------------------------------
// Session Storage
// ---------------------------------------------------------------------------
final class FilesystemSessionStorage implements SessionStorageInterface
{
public function read(string $sessionId): ?InstallerSession
{
$file = $this->locateFile($sessionId);
if ($file === null) {
return null;
}
$raw = file_get_contents($file);
if ($raw === false) {
return null;
}
$data = json_decode($raw, true);
if (!is_array($data)) {
return null;
}
$paths = InstallPath::resolve((string) ($data['target'] ?? getcwd()));
return InstallerSession::fromArray($data, $paths);
}
public function write(InstallerSession $session): void
{
$dir = $session->paths->sessionDirectory($session->id);
if (!is_dir($dir)) {
mkdir($dir, 0700, true);
}
file_put_contents(
$dir . '/state.json',
json_encode($session->toArray(), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES),
LOCK_EX,
);
}
public function delete(string $sessionId): void
{
$file = $this->locateFile($sessionId);
if ($file !== null && is_file($file)) {
unlink($file);
}
}
public function exists(string $sessionId): bool
{
return $this->locateFile($sessionId) !== null;
}
private function locateFile(string $sessionId): ?string
{
$home = InstallerEnvironment::resolveHomeDirectory();
$pattern = $home . '/webkernel/installer/*/sessions/' . $sessionId . '/state.json';
$matches = glob($pattern);
if (empty($matches)) {
return null;
}
return is_file($matches[0]) ? $matches[0] : null;
}
}
// ---------------------------------------------------------------------------
// Environment
// ---------------------------------------------------------------------------
final class InstallerEnvironment
{
public static function isCli(): bool
{
return PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg';
}
public static function resolveHomeDirectory(): string
{
$home = getenv('HOME');
if ($home !== false && is_string($home) && is_dir($home)) {
return rtrim($home, '/');
}
if (function_exists('posix_getuid') && function_exists('posix_getpwuid')) {
$pw = posix_getpwuid(posix_getuid());
if (is_array($pw) && isset($pw['dir']) && is_dir($pw['dir'])) {
return rtrim($pw['dir'], '/');
}
}
$user = getenv('USER') ?: 'webkernel';
foreach (['/home/' . $user, '/var/www/' . $user] as $candidate) {
if (is_dir($candidate)) {
return $candidate;
}
}
$fallback = sys_get_temp_dir() . '/webkernel-userspace';
if (!is_dir($fallback)) {
mkdir($fallback, 0700, true);
}
return $fallback;
}
public static function resolveTargetDirectory(): string
{
if (self::isCli()) {
global $argv;
if (is_array($argv)) {
foreach ($argv as $i => $arg) {
if ($arg === '--dir' && isset($argv[$i + 1])) {
return realpath($argv[$i + 1]) ?: $argv[$i + 1];
}
}
}
return getcwd() ?: '/tmp/webkernel';
}
return dirname((string) ($_SERVER['SCRIPT_FILENAME'] ?? __FILE__));
}
public static function phpBinary(): string
{
$binary = PHP_BINARY;
if (!empty($binary) && is_executable($binary)) {
return $binary;
}
return 'php';
}
public static function resolveComposerState(InstallPath $paths): ComposerState
{
// Use proc_open-safe approach: no shell_exec for detection, only which via PATH
$composerInPath = null;
foreach (explode(PATH_SEPARATOR, (string) getenv('PATH')) as $dir) {
$candidate = rtrim($dir, '/') . '/composer';
if (is_executable($candidate)) {
$composerInPath = $candidate;
break;
}
$candidate2 = $candidate . '.phar';
if (is_executable($candidate2)) {
$composerInPath = $candidate2;
break;
}
}
if ($composerInPath !== null) {
$result = SafeProcessRunner::run(
[InstallerEnvironment::phpBinary(), $composerInPath, '--version', '--no-interaction'],
null,
[],
10,
);
if ($result->successful() && str_contains($result->stdout, 'Composer version 2.')) {
return ComposerState::SystemOk;
}
return ComposerState::OutdatedLocal;
}
if (is_file($paths->composerPharPath())) {
return ComposerState::PharAvailable;
}
return ComposerState::NotFound;
}
}
// ---------------------------------------------------------------------------
// Process Runner (proc_open only — no shell_exec / exec)
// ---------------------------------------------------------------------------
final class ProcessResult
{
public function __construct(
public readonly int $exitCode,
public readonly string $stdout,
public readonly string $stderr,
public readonly bool $timedOut,
) {}
public function successful(): bool
{
return $this->exitCode === 0 && !$this->timedOut;
}
}
final class SafeProcessRunner
{
/**
* @param string[] $command
* @param array<string,string> $env
* @param callable|null $outputCallback fn(string $type, string $chunk): void
*/
public static function run(
array $command,
?string $cwd = null,
array $env = [],
int $timeoutSeconds = 300,
?callable $outputCallback = null,
): ProcessResult {
$descriptors = [
0 => ['pipe', 'r'],
1 => ['pipe', 'w'],
2 => ['pipe', 'w'],
];
$envFull = array_merge(getenv() ?: [], $env);
$process = proc_open($command, $descriptors, $pipes, $cwd, $envFull);
if (!is_resource($process)) {
return new ProcessResult(1, '', 'Failed to open process', false);
}
fclose($pipes[0]);
stream_set_blocking($pipes[1], false);
stream_set_blocking($pipes[2], false);
$stdout = '';
$stderr = '';
$timedOut = false;
$deadline = time() + $timeoutSeconds;
while (true) {
if (time() > $deadline) {
proc_terminate($process, 15);
$timedOut = true;
break;
}
$read = [$pipes[1], $pipes[2]];
$write = null;
$except = null;
$ready = stream_select($read, $write, $except, 0, 200000);
if ($ready === false) {
break;
}
foreach ($read as $stream) {
$chunk = fread($stream, 4096);
if ($chunk !== false && $chunk !== '') {
if ($stream === $pipes[1]) {
$stdout .= $chunk;
if ($outputCallback !== null) {
($outputCallback)('out', $chunk);
}
} else {
$stderr .= $chunk;
if ($outputCallback !== null) {
($outputCallback)('err', $chunk);
}
}
}
}
$status = proc_get_status($process);
if (!$status['running']) {
$stdout .= stream_get_contents($pipes[1]);
$stderr .= stream_get_contents($pipes[2]);
break;
}
}
fclose($pipes[1]);
fclose($pipes[2]);
$exitCode = proc_close($process);
return new ProcessResult($exitCode, $stdout, $stderr, $timedOut);
}
}
// ---------------------------------------------------------------------------
// Installer Context
// ---------------------------------------------------------------------------
final class InstallerContext
{
public function __construct(
public readonly InstallerSession $session,
public readonly OutputInterface $output,
) {}
}
// ---------------------------------------------------------------------------
// Stages
// ---------------------------------------------------------------------------
final class PreflightStage implements InstallerStageInterface
{
public function name(): string { return 'preflight'; }
public function label(): string { return 'Preparation'; }
public function execute(InstallerContext $context): StageResult
{
$log = [];
$errors = [];
// PHP version
$log[] = 'PHP version: ' . PHP_VERSION;
if (PHP_VERSION_ID < 80400) {
$errors[] = 'PHP 8.4+ required, found ' . PHP_VERSION;
}
// Required extensions
foreach (['json', 'zip', 'openssl', 'curl', 'mbstring', 'tokenizer', 'pdo'] as $ext) {
if (extension_loaded($ext)) {
$log[] = 'Extension ' . $ext . ': OK';
} else {
$errors[] = 'Missing extension: ' . $ext;
$log[] = 'Extension ' . $ext . ': MISSING';
}
}
// Target directory
$target = $context->session->paths->target;
if (is_dir($target) && is_writable($target)) {
$log[] = 'Target writable: ' . $target;
} else {
$errors[] = 'Target directory not writable: ' . $target;
}
// Userspace
try {
$context->session->paths->ensure();
$log[] = 'Userspace ready: ' . $context->session->paths->userspace;
} catch (\Throwable $e) {
$errors[] = 'Cannot create userspace: ' . $e->getMessage();
}
// Composer state
$composerState = InstallerEnvironment::resolveComposerState($context->session->paths);
$log[] = 'Composer state: ' . $composerState->value;
$context->session->stageData['composer_state'] = $composerState->value;
if (!empty($errors)) {
return StageResult::failure(
'Preparation failed: ' . implode('; ', $errors),
$log,
);
}
return StageResult::success('All pre-flight checks passed.', $log);
}
}
final class ComposerBootstrapStage implements InstallerStageInterface
{
public function name(): string { return 'composer_bootstrap'; }
public function label(): string { return 'Bootstrapping Composer'; }
public function execute(InstallerContext $context): StageResult
{
$log = [];
$stateValue = (string) ($context->session->stageData['composer_state'] ?? ComposerState::NotFound->value);
$state = ComposerState::from($stateValue);
if ($state === ComposerState::SystemOk) {
$log[] = 'System Composer 2.x found; skipping download.';
return StageResult::skipped('System Composer 2.x is available.');
}
if ($state === ComposerState::PharAvailable) {
$log[] = 'composer.phar found in userspace; skipping download.';
$context->session->stageData['composer_phar'] = $context->session->paths->composerPharPath();
return StageResult::skipped('Existing composer.phar will be used.');
}
$pharPath = $context->session->paths->composerPharPath();
$log[] = 'Downloading composer.phar installer...';
$installerPath = sys_get_temp_dir() . '/composer-setup-' . bin2hex(random_bytes(4)) . '.php';
$ch = curl_init('https://getcomposer.org/installer');
if ($ch === false) {
return StageResult::failure('Could not initialise cURL.', $log);
}
$fh = fopen($installerPath, 'wb');
if ($fh === false) {
curl_close($ch);
return StageResult::failure('Could not open temp file for Composer installer.', $log);
}
curl_setopt_array($ch, [
CURLOPT_FILE => $fh,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_TIMEOUT => 120,
CURLOPT_USERAGENT => 'WebkernelInstaller/1.0',
]);
$downloaded = curl_exec($ch);
$curlError = curl_error($ch);
curl_close($ch);
fclose($fh);
if ($downloaded === false || !empty($curlError)) {
@unlink($installerPath);
return StageResult::failure('cURL error: ' . $curlError, $log);
}
$log[] = 'Installer downloaded; running setup...';
$result = SafeProcessRunner::run(
[
InstallerEnvironment::phpBinary(),
$installerPath,
'--quiet',
'--install-dir=' . dirname($pharPath),
'--filename=composer.phar',
],
null,
[],
180,
);
@unlink($installerPath);
if (!$result->successful()) {
$cleanErr = stripAnsi(trim($result->stderr ?: $result->stdout));
return StageResult::failure(
'Composer setup failed: ' . (empty($cleanErr) ? 'exit code ' . $result->exitCode : $cleanErr),
$log,
);
}
if (!is_file($pharPath)) {
return StageResult::failure('composer.phar not present after setup.', $log);
}
$log[] = 'composer.phar installed at: ' . $pharPath;
$context->session->stageData['composer_phar'] = $pharPath;
return StageResult::success('Composer is ready.', $log);
}
}
final class DownloadStage implements InstallerStageInterface
{
public function name(): string { return 'download'; }
public function label(): string { return 'Download'; }
public function execute(InstallerContext $context): StageResult
{
$log = [];
$target = rtrim($context->session->paths->target, '/');
$userspace = $context->session->paths->userspace;
$sessionId = $context->session->id;
// Purge orphan staging dirs from previous sessions to keep userspace clean
$this->purgeOrphanStagingDirs($userspace, $sessionId, $log);
$stagingDir = $userspace . '/staging-' . substr($sessionId, 0, 8);
// Resume logic:
// - staging/vendor exists => Composer finished; skip straight to move
// - staging exists, no vendor => partial; wipe and restart
// - no staging dir => fresh start
$skipComposer = false;
if (is_dir($stagingDir)) {
if (is_dir($stagingDir . '/vendor')) {
$log[] = 'Composer already completed in staging. Resuming at move step.';
$skipComposer = true;
} else {
$log[] = 'Partial staging detected. Cleaning up for a fresh download.';
$this->removeDirectory($stagingDir);
}
}
if (!$skipComposer) {
mkdir($stagingDir, 0755, true);
$composerBin = $this->resolveComposerBin($context);
$log[] = 'Composer: ' . $composerBin;
// --no-scripts is critical here.
// Post-install scripts (package:discover, etc.) call artisan which
// requires bootstrap/app.php — that path is only valid in the FINAL
// target location, not the staging directory.
// We run scripts manually after the move, from the correct working dir.
$result = SafeProcessRunner::run(
[
InstallerEnvironment::phpBinary(),
$composerBin,
'create-project',
'webkernel/webkernel',
$stagingDir,
'--no-interaction',
'--prefer-dist',
'--no-progress',
'--no-scripts',
'--no-ansi',
],
null,
[
'COMPOSER_HOME' => $userspace . '/composer-home',
'WEBKERNEL_INSTALLER_MODE' => '1',
],
600,
function (string $type, string $chunk) use (&$log): void {
foreach (explode(PHP_EOL, $chunk) as $line) {
$line = stripAnsi(trim($line));
if ($line !== '') {
$log[] = $line;
}
}
},
);
if (!$result->successful()) {
$clean = stripAnsi(trim($result->stderr ?: $result->stdout));
return StageResult::failure(self::humanizeComposerError($clean), $log);
}
}
// Move staged files into the real target
$log[] = 'Moving files to: ' . $target;
if (!$this->moveStaging($stagingDir, $target, $log)) {
return StageResult::failure('Could not move files to target directory.', $log);
}
$this->removeDirectory($stagingDir);
$log[] = 'Staging directory removed.';
// Re-dump autoload from the final target so class maps are correct.
// We do NOT run post-autoload-dump script here — it calls
// "artisan package:discover" which requires bootstrap/app.php
// to be fully bootstrapped. The ConfigureStage handles that
// after .env is in place.
$composerBin = $this->resolveComposerBin($context);
$dumpResult = SafeProcessRunner::run(
[
InstallerEnvironment::phpBinary(),
$composerBin,
'dump-autoload',
'--optimize',
'--no-ansi',
'--no-interaction',
],
$target,
['COMPOSER_HOME' => $userspace . '/composer-home'],
60,
function (string $type, string $chunk) use (&$log): void {
foreach (explode(PHP_EOL, $chunk) as $line) {
$line = stripAnsi(trim($line));
if ($line !== '') {
$log[] = $line;
}
}
},
);
if (!$dumpResult->successful()) {
$log[] = 'Warning: dump-autoload exited with code ' . $dumpResult->exitCode;
} else {
$log[] = 'Autoload map regenerated.';
}
return StageResult::success('Webkernel downloaded successfully.', $log);
}
/**
* Remove staging directories that belong to other sessions.
*
* @param string[] $log
*/
private function purgeOrphanStagingDirs(string $userspace, string $activeSessionId, array &$log): void
{
$myStub = substr($activeSessionId, 0, 8);
$entries = glob($userspace . '/staging-*') ?: [];
foreach ($entries as $dir) {
if (!is_dir($dir)) {
continue;
}
$stub = substr(basename($dir), strlen('staging-'));
if ($stub !== $myStub) {
$this->removeDirectory($dir);
$log[] = 'Removed orphan staging: ' . basename($dir);
}
}
}
/**
* Recursively move all contents of $src into $dst.
*
* @param string[] $log
*/
private function moveStaging(string $src, string $dst, array &$log): bool
{
if (!is_dir($dst)) {
mkdir($dst, 0755, true);
}
$items = scandir($src);
if ($items === false) {
return false;
}
foreach ($items as $item) {
if ($item === '.' || $item === '..') {
continue;
}
$srcPath = $src . '/' . $item;
$dstPath = $dst . '/' . $item;
if (is_dir($srcPath)) {
if (!is_dir($dstPath)) {