forked from inex/IXP-Manager
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate.php
More file actions
executable file
·745 lines (624 loc) · 26.8 KB
/
Copy pathvalidate.php
File metadata and controls
executable file
·745 lines (624 loc) · 26.8 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
#!/usr/bin/env php
<?php
/*
* Copyright (C) 2009 - 2026 Internet Neutral Exchange Association Company Limited By Guarantee.
* All Rights Reserved.
*
* This file is part of IXP Manager.
*
* IXP Manager is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version v2.0 of the License.
*
* IXP Manager is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License v2.0
* along with IXP Manager. If not, see:
*
* http://www.gnu.org/licenses/gpl-2.0.html
*/
declare(strict_types=1);
/*
* Copyright (C) 2009 - 2026 Internet Neutral Exchange Association Company Limited By Guarantee.
* All Rights Reserved.
*
* This file is part of IXP Manager.
*
* IXP Manager is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version v2.0 of the License.
*
* IXP Manager is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License v2.0
* along with IXP Manager. If not, see:
*
* http://www.gnu.org/licenses/gpl-2.0.html
*/
/**
* This function prints a pre-populated GitHub Issue Template.
*/
function print_issue_assistance_info(): void {
// OS Detection
switch (PHP_OS_FAMILY) {
case 'BSD':
$osInfo = file_get_contents('/etc/os-release');
if ($osInfo === false) {
exec("uname -mrs", $uname, $exitCode);
if ($exitCode === 0) {
$osInfo = implode("\n", $uname);
}
unset($uname, $exitCode);
}
break;
case 'Linux':
$osInfo = file_get_contents('/etc/os-release');
if ($osInfo === false) {
$osInfo = file_get_contents('/etc/lsb-release');
}
break;
case 'Darwin':
if ($pfile = file_get_contents('/System/Library/CoreServices/SystemVersion.plist')) {
// The regex pattern
$pattern = '/<key>ProductUserVisibleVersion<\/key>\s*<string>([^<]+)<\/string>/';
if (preg_match($pattern, $pfile, $matches)) {
// $matches[1] contains the value inside the capture group
$osInfo = "macOS " . $matches[1];
}
}
break;
default:
$osInfo = false;
break;
}
// IXP Manager version
$versionInfo = false;
if ($versionFile = file_get_contents(__DIR__ . "/version.php")) {
// Regex targeting both constants with named capture groups
$pattern = "/define\s*\(\s*['\"]APPLICATION_VERSION['\"]\s*,\s*['\"](?<version>[^'\"]+)['\"]\s*\).*?define\s*\(\s*['\"]APPLICATION_VERDATE['\"]\s*,\s*['\"](?<verdate>[^'\"]+)['\"]\s*\)/s";
if (preg_match($pattern, $versionFile, $matches)) {
$version = $matches['version'];
$verdate = $matches['verdate'];
$versionInfo =
"APPLICATION_VERSION: " . $version . "\n" .
"APPLICATION_VERDATE: " . $verdate . "\n";
}
}
try {
$env = load_env( dirname( __FILE__ ) . "/.env", $errorMsg);
// Generate the DSN from our configuration
$dsn = "mysql:host={$env['DB_HOST']};dbname={$env['DB_DATABASE']}"
. (array_key_exists( 'DB_PORT', $env ) ? ";port={$env['DB_PORT']}" : "");
$pdo = new \PDO( $dsn, $env['DB_USERNAME'], $env['DB_PASSWORD'], [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::ATTR_EMULATE_PREPARES => false,
] );
$mysqlVersion = $pdo->query( "SELECT VERSION() as version" )->fetchColumn();
$schemaVersion = $pdo->query( "SELECT migration FROM migrations ORDER BY id DESC LIMIT 1" )->fetchColumn();
$versionInfo .= "MySQL server version: " . $mysqlVersion . "\n";
$versionInfo .= "Schema version: " . $schemaVersion . "\n";
} catch (\Throwable $t) {
// guess we can't provide SQL info
}
// PHP Environment
$environmentInfoPhp = false;
exec("php -v", $output, $exitCode);
if ($exitCode === 0) {
$environmentInfoPhp = implode("\n", $output) . "\n\n";
}
$exitCode = null;
$output = null;
if (PHP_OS_FAMILY === "BSD") {
exec("pkg list | grep php", $output, $exitCode);
} if (PHP_OS_FAMILY === "Linux") {
if (!empty(shell_exec("which dpkg"))) {
exec("dpkg -l | grep php", $output, $exitCode);
} elseif (!empty(shell_exec("which yum"))) {
exec("yum list installed | grep php", $output, $exitCode);
} elseif (!empty(shell_exec("which dnf"))) {
exec("dnf list installed | grep php", $output, $exitCode);
}
}
if ($exitCode === 0) {
$environmentInfoPackages = implode("\n", $output);
} else {
$environmentInfoPackages = "PHP extensions:\n";
foreach (get_loaded_extensions(false) as $ext) {
$environmentInfoPackages .= " - " . $ext . "\n";
}
}
unset($output, $exitCode);
// Configuration: Non-critical environment variables.
$envInfo = false;
if (PHP_OS_FAMILY === "Linux" || PHP_OS_FAMILY === "BSD" || PHP_OS_FAMILY === "Darwin") {
exec("grep -Ev '(^#|^\s*$|^APP_KEY|^APP_PREVIOUS_KEYS|^ATLAS_MEASUREMENT_KEY|^AWS_ACCESS_KEY_ID|^AWS_SECRET_ACCESS_KEY|^DB_|^GRAPHER.*SNMPPASSWD|^HELPDESK|^IDENTITY|^IXP_API_RIR_PASSWORD|^IXP_API_PEERING_DB_|^IXP_RIPE_API_KEY|^.*JSONEXPORTSCHEMA_ACCESS_KEY|^.*LAYER2_ADDRESSES_EMAIL|^LOG_SLACK_|^MAIL_|^MAILGUN|^PAPERTRAIL|^POSTMARK|^PEERINGDB_OAUTH_|^REDIS|^STRIPE)' .env", $output, $exitCode);
if ($exitCode === 0) {
$envInfo = implode("\n", $output);
}
unset($output, $exitCode);
}
echo "
##### ISSUE SUMMARY
*Explain your issue here*
##### OS
" . $osInfo . "
##### VERSION
```
$versionInfo
```
##### ENVIRONMENT
```
" .
$environmentInfoPhp .
$environmentInfoPackages . "
```
##### CONFIGURATION
```
" . $envInfo . "
```
##### STEPS TO REPRODUCE
##### EXPECTED RESULTS
_What did you expect to happen when running the steps above?_
##### ACTUAL RESULTS
_What actually happened?_
##### IMPORTANCE
_Please let us know if the issue is affecting you in a production environment_
";
}
/**
* Discourage running this script as root.
*/
function require_confirmation_if_running_as_root(): void
{
exec( 'id -u', $idOutput, $idExitCode );
if ( $idExitCode !== 0 ) {
echo "Warning: unable to determine if running as root.";
} else {
$id = (int) trim( $idOutput[0] );
if ( $id === 0 ) {
echo "WARNING: you are running this script as root, this is not recommended. You should run this as your www user. Are you sure you want to continue? (y/N)?: ";
$stdin = fopen( "php://stdin", "r" );
$line = fgets( $stdin );
if ( trim( $line ) === 'y' ) {
return;
} else {
echo "Terminating script.\n";
exit(0);
}
}
}
}
/**
* Parses a .env file at $path and returns an array of vars if successful. False on failure
* ($errorMessage will be written in this case)
*/
function load_env( string $path, &$errorMessage): array|false
{
$env = [];
if ( !file_exists( $path ) ) {
$errorMessage = "env file not found: {$path}";
return false;
}
if ( ($lines = file( $path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES ) ) === false ) {
$errorMessage = "failed to read env file: $path";
return false;
}
foreach ( $lines as $line ) {
// ignore whole line comment
if ( str_starts_with( trim( $line ), '#' ) ) {
continue;
}
// look for a setting
if ( str_contains( $line, '=' ) ) {
// split into name & value
[$name, $value] = explode( '=', $line, 2 );
$name = trim( $name );
$value = trim( $value );
// handle inline comments:
[$value, ] = split_env_value_and_comment($value);
// extract from optional quotes
$value = preg_replace( '/^["\'](.*)["\']$/', '$1', $value );
$env[$name] = $value;
}
}
return $env;
}
/**
* dotenv value & inline comment parser based on listerr's
*
* @psalm-return array{0: string, 1: string|null}
*/
function split_env_value_and_comment( string $valueElement ): array
{
// avoid loop if there's no inline comment
if( !str_contains($valueElement, "#") ) {
return [ $valueElement, null ];
}
$quote = null;
/** @var bool $escaped */
$escaped = false;
for( $i = 0, $length = strlen( $valueElement ); $i < $length; $i++ ) {
$character = $valueElement[ $i ];
if( $escaped ) {
$escaped = false;
} else if( $character === '\\' && $quote === '"' ) {
$escaped = true;
} else if( $quote !== null ) {
if( $character === $quote ) {
$quote = null;
}
} else if( $character === '"' || $character === "'" ) {
$quote = $character;
} else if( $character === '#' ) {
return [
substr( $valueElement, 0, $i ),
trim( substr( $valueElement, $i + 1 ) ),
];
}
}
return [ $valueElement, null ];
}
function do_minimum_php_version_check( string $minVersion, string $recommendedPrefix, ?string $maxVersion): array
{
$results = [];
$version = phpversion();
$results[] = new SoftwareVersion('PHP', $version);
if ( version_compare( $version, $minVersion, '<' ) ) {
$results[] = new CheckResult( ResultStatus::ERROR, [ "PHP version " . $minVersion . " or higher required - running " . $version ] );
} else if ($maxVersion !== null && version_compare( $version, $maxVersion, '>')) {
$results[] = new CheckResult( ResultStatus::ERROR, [ "PHP version exceeds max supported version " . $maxVersion ] );
} else if ( !str_starts_with( $version, $recommendedPrefix ) ) {
$results[] = new CheckResult( ResultStatus::WARNING, [ "Not running a recommended PHP version - running " . $version ] );
}
if ( !extension_loaded('pdo_mysql') ) {
$results[] = new CheckResult( ResultStatus::ERROR, [ 'PDO MySQL extension is not installed' ] );
}
return $results;
}
function do_composer_check(): array
{
$results = [];
if ( !file_exists( dirname(__FILE__) . "/vendor/autoload.php" ) ) {
$results[] = new CheckResult( ResultStatus::ERROR, ['composer install has not been run'] );
}
return $results;
}
function do_env_file_check(): array
{
$results = [];
$envfile = dirname(__FILE__) . "/.env";
if ( !file_exists($envfile)) {
$results[] = new CheckResult( ResultStatus::ERROR, [ '.env file does not exist' ] );
return $results;
}
if ( ( $parseEnv = load_env($envfile, $errorMessage ) ) === false ) {
$results[] = new CheckResult( ResultStatus::ERROR, [ $errorMessage ] );
return $results;
}
if ( !array_key_exists('APP_KEY', $parseEnv) ) {
$results[] = new CheckResult( ResultStatus::ERROR, [ 'APP_KEY is not set in .env' ] );
}
return $results;
}
function do_mysql_check( string $minVersion, string $recommendedPrefix, ?string $maxVersion): array|CheckResult
{
$results = [];
// Laravel uses pdo-mysql extension to interact with MySQL databases
if ( !extension_loaded( 'pdo_mysql' ) ) {
return new CheckResult( ResultStatus::ERROR, [ 'PDO MySQL extension is not installed' ] );
}
// Load env file to perform configuration checks
if ( ( $env = load_env( dirname(__FILE__) . "/.env", $errorMessage ) ) === false ) {
return new CheckResult( ResultStatus::ERROR, [ $errorMessage ] );
}
// There are several required keys in the env file.
$allKeysPresent = true;
foreach ( [ 'DB_HOST', 'DB_DATABASE', 'DB_USERNAME' ] as $key ) {
if ( !array_key_exists( $key, $env ) ) {
$results[] = new CheckResult( ResultStatus::ERROR, [ ".env is missing required environment variable: {$key}" ] );
$allKeysPresent = false;
} else if ( empty( $env[$key] ) ) {
$results[] = new CheckResult( ResultStatus::ERROR, [ ".env is missing required environment variable: {$key} (empty value)" ] );
$allKeysPresent = false;
}
}
if ( !$allKeysPresent ) {
return $results;
}
// If DB_CONNECTION is set, it must be mysql.
// Note: if we implement the corresponding config check here (catch defaults) then we protect against accidental sqlite3 default in later versions
if ( array_key_exists( 'DB_CONNECTION', $env ) && $env['DB_CONNECTION'] !== 'mysql' ) {
return new CheckResult( ResultStatus::ERROR, [ "DB_CONNECTION must be set to 'mysql'" ] );
}
// Generate the DSN from our configuration
$dsn = "mysql:host={$env['DB_HOST']};dbname={$env['DB_DATABASE']}"
. (array_key_exists( 'DB_PORT', $env ) ? ";port={$env['DB_PORT']}" : "");
// Attempt to connect using credentials from Env File
try {
$pdo = new \PDO( $dsn, $env['DB_USERNAME'], $env['DB_PASSWORD'], [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::ATTR_EMULATE_PREPARES => false,
] );
} catch (\PDOException $e) {
return new CheckResult( ResultStatus::ERROR, [ "Connection failed: " . $e->getMessage() ] );
}
// Determine MySQL server version
try {
$version = $pdo->query( "SELECT VERSION() as version" )->fetchColumn();
} catch (\PDOException $e) {
return new CheckResult( ResultStatus::ERROR, [ "Failed to determine server version: " . $e->getMessage() ] );
}
// Min/Max/Recommended MySQL server checks:
if ( version_compare( $version, $minVersion, '<' ) ) {
$results[] = new CheckResult( ResultStatus::ERROR, [ "MySQL version $minVersion or higher required" ] );
} else if ($maxVersion !== null && version_compare( $version, $maxVersion, '>')) {
$results[] = new CheckResult( ResultStatus::ERROR, [ "MySQL version exceeds max supported version " . $maxVersion ] );
} else if ( !str_starts_with( $version, $recommendedPrefix ) ) {
$results[] = new CheckResult( ResultStatus::WARNING, [ "Not running a recommended MySQL version." ] );
}
// What schema/migration are we running?
try {
$schemaVersion = $pdo->query( "SELECT migration FROM migrations ORDER BY id DESC LIMIT 1" )->fetchColumn();
$results[] = new SoftwareVersion( "DB Schema", $schemaVersion );
} catch (\PDOException $e) {
$results[] = new CheckResult( ResultStatus::ERROR, [ "failed to determine schema version: " . $e->getMessage() ] );
}
return $results;
}
function do_laravel_required_extension_checks( array $requiredByLaravel): array
{
$results = [];
// Check that required extensions are installed
$missingExtensions = [];
foreach ( $requiredByLaravel as $extension ) {
if ( !extension_loaded( $extension ) ) {
$missingExtensions[] = $extension;
}
}
if ( count( $missingExtensions ) > 0 ) {
$results[] = new CheckResult( ResultStatus::ERROR, [ 'Missing required PHP extensions: ' . implode(', ', $missingExtensions) ] );
}
return $results;
}
function do_laravel_writable_directory_checks(): array
{
$storageDirectories = ["bootstrap/cache/", "storage/app/", "storage/docstore/", "storage/docstore_customers/", "storage/files/",
"storage/framework/cache/", "storage/framework/sessions/", "storage/framework/views/",
"storage/logs/", "storage/tmp/", "storage/"];
$fileFail = [];
$dirFail = [];
foreach ( $storageDirectories as $storageDirectory ) {
$testFile = rtrim(dirname( __FILE__ ), "/" ) . "/" . rtrim($storageDirectory, "/") . "/.permission-test-" . bin2hex(random_bytes(4));
try {
$written = @file_put_contents($testFile, "This file is part of the IXP Manager storage directory permission check. If found outside of testing it can safely be deleted.");
if ($written === false) {
$fileFail[] = $storageDirectory;
}
} catch (\Throwable $t) {
$fileFail[] = $storageDirectory;
} finally {
if (file_exists($testFile)) {
@unlink($testFile);
}
}
// Ability to create a directory is required at least in the case of storage/grapher
$testDir = rtrim(dirname( __FILE__ ), "/" ) . "/" . rtrim($storageDirectory, "/") . "/.permission-test-" . bin2hex(random_bytes(4));
try {
$written = @mkdir($testDir);
if ($written === false) {
$dirFail[] = $storageDirectory;
}
} catch (\Throwable $t) {
$dirFail[] = $storageDirectory;
} finally {
if (file_exists($testDir)) {
@rmdir($testDir);
}
}
}
$results = [];
if (count($fileFail) > 0) {
$results[] = new CheckResult( ResultStatus::ERROR, [ 'Missing file write permission in these storage directories: ' . implode( ', ', $fileFail ) ] );
}
if (count($dirFail) > 0) {
$results[] = new CheckResult( ResultStatus::ERROR, [ 'Missing directory write permission in these storage directories: ' . implode( ', ', $dirFail ) ] );
}
if (count($results)) {
// Not using multiple messages as we want it to be easy to copy/paste.
$results[] = new CheckResult( ResultStatus::WARNING, [ #
"These commands should be run to fix the above errors. If your web server does not run as user www-data, replace www-data with the actual webserver user on your system.\n" .
" chown -R www-data: \$IXPROOT/{bootstrap/cache,composer.lock,storage,vendor}\n" .
" chmod -R ug+rwX \$IXPROOT/{bootstrap/cache,composer.lock,storage,vendor}"
] );
}
return $results;
}
/**
* Checks local version against latest version on Github
* See https://docs.github.com/en/rest/repos/repos?apiVersion=2026-03-10#list-repository-tags for this api call
* A user agent is required for this call
* @param string $localVersion
* @return array
*/
function do_ixp_manager_release_check(string $localVersion): array
{
$results = [];
// Include the current IXP Manager version
$results[] = new SoftwareVersion( "IXP-Manager", APPLICATION_VERSION );
// Lookup tags. Use file_get_contents with curl fallback
if ( ini_get( 'allow_url_fopen' ) == 1 ) {
// Create stream context containing required HTTP headers
$context = stream_context_create( [
"http" => [
"method" => "GET",
"header" => "User-Agent: IXP-Manager-validation-tool\r\n",
]
] );
if ( ( $tagsJson = file_get_contents( 'https://api.github.com/repos/inex/IXP-Manager/tags', false, $context ) ) === false ) {
$results[] = new CheckResult( ResultStatus::WARNING, [ "Failed to fetch IXP-Manager release information (file_get_contents)" ] );
return $results;
}
// Extract HTTP response code
$regexReturnCode = preg_match( '/([0-9])\d+/', $http_response_header[0],$matches );
if ( $regexReturnCode === false ) {
$results[] = new CheckResult(ResultStatus::WARNING, [ "Failed to fetch IXP-Manager release information. Invalid regex for HTTP response code" ] );
return $results;
} else if ( $regexReturnCode === 0 ) {
$results[] = new CheckResult(ResultStatus::WARNING, [ "Failed to fetch IXP-Manager release information. Did not find a status in HTTP response" ] );
return $results;
}
// Ensure HTTP response was OK
$responsecode = intval( $matches[0] );
if ( $responsecode !== 200 ) {
$results[] = new CheckResult( ResultStatus::WARNING, [ "Received non-OK response code when fetching IXP-Manager release information (file_get_contents): $responsecode" ] );
return $results;
}
// we have $tagsJson and the response was OK
} else if ( extension_loaded( 'curl' ) ) {
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, 'https://api.github.com/repos/inex/IXP-Manager/tags' );
curl_setopt( $ch, CURLOPT_USERAGENT, 'IXP-Manager-validation-tool' );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
if ( ( $tagsJson = curl_exec($ch) ) === false ) {
$results[] = new CheckResult(ResultStatus::WARNING, [ "Failed to fetch IXP-Manager release information (curl): " . curl_error($ch) ]);
return $results;
}
// Ensure HTTP response was OK
$info = curl_getinfo( $ch );
if ( $info['http_code'] !== 200 ) {
$results[] = new CheckResult( ResultStatus::WARNING, [ "Received non-OK response code when fetching IXP-Manager release information (curl): " . $info['http_code'] ] );
return $results;
}
// we have $tagsJson and the response was OK
} else {
$results[] = new CheckResult( ResultStatus::WARNING, [ "There was no usable method to fetch IXP-Manager release information" ] );
return $results;
}
// Extract IXP Manager published versions and compare against the installed version
$tags = json_decode( $tagsJson );
if ( version_compare( $localVersion, ltrim( $tags[0]->name, "v" ), '<' ) ) {
$results[] = new CheckResult( ResultStatus::WARNING, [ "A newer version of IXP-Manager is available: " . $tags[0]->name ] );
}
return $results;
}
class BasicValidation
{
/** @var CheckResult[]|SoftwareVersion[] */
private(set) array $results = [];
public function __construct(public readonly string $name, private \Closure $callable, private ?array $params = null) {}
public function run(): void
{
$results = call_user_func_array($this->callable, $this->params ?? []);
// can return a single result, or an array of results
if ($results instanceof CheckResult) {
$results = [$results];
}
$this->results = $results;
}
public function hasErrors(): bool
{
return array_any( $this->results, fn( $result ) => $result instanceof CheckResult && $result->status === ResultStatus::ERROR );
}
}
enum ResultStatus
{
case WARNING;
case ERROR;
}
readonly class CheckResult
{
public function __construct( public ResultStatus $status, public array $messages = []) {}
}
readonly class SoftwareVersion
{
public function __construct( public string $software, public string $version) {}
}
require_confirmation_if_running_as_root();
include "version.php";
$manifest = APPLICATION_MANIFEST;
if (array_any($argv, fn($v) => $v === '--github-issue')) {
print_issue_assistance_info();
return;
}
$logLevel = null;
foreach ($argv as $i => $value) {
// If they pass the flag with equals, log level immediately follows =
// or if they pass the flag by itself, and we have more parameters to come, treat the following parameter as the log level
if(
( str_starts_with( $value, '--log-level=' ) && ( $tmp = substr( $value, strlen( '--log-level=' ) ) ) ) ||
( $value === "--log-level" && $argc > $i && ($tmp = $argv[$i + 1] ) ) ) {
// check log level is in the whitelist
if (in_array($tmp, ['debug', 'info', 'suggest', 'warning', 'error'])) {
$logLevel = $tmp;
}
break;
}
}
$tasks = [];
$tasks[] = new BasicValidation( 'PHP', do_minimum_php_version_check(...), [ $manifest['php_version']['min'], $manifest['php_version']['recommended'], $manifest['php_version']['max'] ] );
$tasks[] = new BasicValidation( 'Composer', do_composer_check(...), [] );
$tasks[] = new BasicValidation( 'Env File', do_env_file_check(...), [] );
$tasks[] = new BasicValidation( 'MySQL', do_mysql_check(...), [ $manifest['mysql_version']['min'], $manifest['mysql_version']['recommended'], $manifest['mysql_version']['max'] ] );
$tasks[] = new BasicValidation( 'Laravel Required Extensions', do_laravel_required_extension_checks(...), [ $manifest['laravel_required_extensions'] ] );
$tasks[] = new BasicValidation( 'Laravel Storage Directories', do_laravel_writable_directory_checks(...), [ $manifest['laravel_required_extensions'] ] );
$tasks[] = new BasicValidation( 'IXP Manager', do_ixp_manager_release_check(...), [ APPLICATION_VERSION ] );
$softwareVersionResults = [];
$checkResults = [];
$haveErrors = false;
$haveWarnings = false;
foreach ( $tasks as $task ) {
$task->run();
foreach ( $task->results as $taskResult ) {
if ( $taskResult instanceof SoftwareVersion ) {
$softwareVersionResults[$taskResult->software] = $taskResult->version;
} else {
$checkResults[$task->name][] = $taskResult;
$haveErrors = $haveErrors || $taskResult->status === ResultStatus::ERROR;
$haveWarnings = $haveWarnings || $taskResult->status === ResultStatus::WARNING;
}
}
}
$basicReport = "Software Versions:\n";
foreach ( $softwareVersionResults as $software => $result ) {
$basicReport .= "$software: " . $result . "\n";
}
$basicReport .= "\n";
$basicReport .= "Results:\n";
foreach ( $checkResults as $taskName => $taskResults ) {
if (count($taskResults) === 0) {
continue;
}
$basicReport .= "task: " . $taskName . "\n";
foreach ( $taskResults as $result ) {
$basicReport .= " * " . $result->status->name . ": " . implode("\n * ", $result->messages) . "\n";
}
$basicReport .= "\n";
}
if ( $haveErrors || $haveWarnings ) {
echo $basicReport;
}
if ( $haveErrors ) {
echo "There were errors during the validation process. Please review the checks above for details.\n";
exit(1);
}
echo "No errors detected during basic validations\n";
// psalm gets giddy about using parameters in shell exec, so we'll take the long way. NB: log level is only set if in the whitelist.
$command = sprintf("%s validator:run %s", escapeshellcmd(__DIR__ . '/artisan'), $logLevel ? '--log-level=' . escapeshellarg($logLevel) : '' );
$descriptors = [
1 => ['pipe', 'w'],
2 => ['redirect', 1], // redirect stderr into stdout
];
$process = proc_open($command, $descriptors, $pipes);
if (is_resource($process)) {
echo stream_get_contents($pipes[1]);
fclose($pipes[1]);
proc_close($process);
}