Repository navigation
Expand file tree
/
Copy pathinstall.php
More file actions
830 lines (777 loc) · 46.7 KB
/
Copy pathinstall.php
File metadata and controls
830 lines (777 loc) · 46.7 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
<?php
/**
* TryHackX Tracker - Installation Wizard
* Delete this file after installation!
*/
// The installer had no access to the shared helpers at all — its only include was
// includes/schema.php, several hundred lines down, inside the branch that seeds the settings. It
// gets functions.php here so the Secure flag on its own session cookie is decided by the same
// function the rest of the site uses. There is no database yet by definition, so sessionCookieParams([])
// is `auto` with no proxy knowledge: this request's own transport, and nothing else. That is the
// right answer for an installer, and it is what the old inline expression was trying to be.
require_once __DIR__ . '/includes/functions.php';
session_start(sessionCookieParams([]));
// ── THE INSTALLER MAY RUN EVERY MIGRATION, INCLUDING THE ONES THE WEB NORMALLY DECLINES ──────────
//
// schemaHeavyAllowed() answers false outside the CLI, so an ALTER that rebuilds `index_hashes`
// (it carries a FULLTEXT index, so adding a column or an index is a full rebuild) is deferred on a
// web request — minutes of shared lock in the middle of a page view is not a trade worth making.
// ensureSchema() then deliberately does NOT record the new schema_version, because the schema
// really is not at that version yet.
//
// That is right for a live site and wrong for exactly one caller: this one. Here the tables were
// created seconds ago and are EMPTY — there is nothing to rebuild, the ALTER is instant, and a
// deferral means the installer below sees version 0, refuses to report a finished install, and
// writes no config/installed.lock. INSTALL.md tells the operator to open this file in a BROWSER
// (php-fpm, PHP_SAPI !== 'cli'), so that was the ordinary path, not an edge case.
//
// Defined before includes/schema.php is loaded anywhere below, which is all schemaHeavyAllowed()
// asks. Belt and braces: the base CREATE TABLEs in trackerSchemaStatements() now carry those
// columns and indexes themselves, so on a fresh install the guarded ALTERs find nothing to do and
// this constant changes nothing. It is here so that the NEXT column somebody adds to the guarded
// list only — and forgets to mirror — cannot silently stop a browser install again.
define('TRACKER_SCHEMA_FORCE_HEAVY', 1);
// Whether installation has already completed. Gates the installer's AJAX + wizard steps
// so that, if install.php is left on the server, it can't be used as an open endpoint.
$installed = file_exists(__DIR__ . '/config/installed.lock');
// Handle blacklist path test (AJAX from step 3)
if (isset($_GET['test_blacklist']) && $_SERVER['REQUEST_METHOD'] === 'POST') {
header('Content-Type: application/json; charset=utf-8');
// Refuse to probe the filesystem once installed — otherwise a left-behind installer is an
// unauthenticated path-enumeration / PHP-user disclosure endpoint.
if ($installed) {
echo json_encode(['ok' => false, 'msg' => 'Installer is locked (already installed). Delete install.php.']);
exit;
}
$path = trim($_POST['path'] ?? '');
$isWin = PHP_OS_FAMILY === 'Windows';
$phpUser = function_exists('posix_getpwuid') ? posix_getpwuid(posix_geteuid())['name'] : get_current_user();
if (empty($path)) {
echo json_encode(['ok' => false, 'msg' => 'Path is empty.']);
exit;
}
$dir = dirname($path);
if (!is_dir($dir)) {
$hint = $isWin ? 'Create the directory manually.' : "Create it: sudo mkdir -p $dir && sudo chown www-data:www-data $dir";
echo json_encode(['ok' => false, 'msg' => "Directory does not exist: $dir", 'hint' => $hint, 'user' => $phpUser]);
exit;
}
if (file_exists($path)) {
$readable = is_readable($path);
$writable = is_writable($path);
if ($readable && $writable) {
echo json_encode(['ok' => true, 'msg' => 'Path is accessible and writable.', 'user' => $phpUser]);
} else {
$errs = [];
if (!$readable) $errs[] = 'not readable';
if (!$writable) $errs[] = 'not writable';
echo json_encode(['ok' => false, 'msg' => 'File exists but is ' . implode(' and ', $errs) . '.', 'user' => $phpUser]);
}
} else {
if (is_writable($dir)) {
echo json_encode(['ok' => true, 'msg' => "File does not exist yet, but the directory is writable. File will be created automatically.", 'user' => $phpUser]);
} else {
$hint = $isWin ? 'Ensure the Apache/WAMP user has write permission on the directory.' : "Fix: sudo chown www-data:www-data $dir";
echo json_encode(['ok' => false, 'msg' => "Directory exists but is not writable: $dir", 'hint' => $hint, 'user' => $phpUser]);
}
}
exit;
}
// Handle cleanup request (delete installer files)
if (isset($_GET['cleanup']) && $_GET['cleanup'] === '1' && $_SERVER['REQUEST_METHOD'] === 'POST') {
$deleted = [];
$installFile = __DIR__ . '/install.php';
// Self-delete: we use unlink then redirect
if (file_exists($installFile)) {
@unlink($installFile);
$deleted[] = 'install.php';
}
// Redirect to homepage after deletion
header('Location: ./');
exit;
}
$step = (int)($_GET['step'] ?? 1);
$error = '';
// Check if already installed (the cleanup/self-delete handler above stays allowed on purpose)
if ($installed) {
die('<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Already Installed</title>
<style>body{background:#0a0a1a;color:#e0e0e0;font-family:monospace;display:flex;align-items:center;justify-content:center;min-height:100vh;}
.box{background:#111;border:1px solid #333;padding:2rem;border-radius:8px;text-align:center;max-width:400px;}
h2{color:#f44336;margin-bottom:1rem;}a{color:#4a9eff;}</style></head>
<body><div class="box"><h2>Already Installed</h2><p>The tracker is already configured. Delete <code>install.php</code> for security.</p>
<p><a href="./">Go to site</a></p></div></body></html>');
}
// Process Step 2 - Database
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $step === 2) {
$dbHost = trim($_POST['db_host'] ?? 'localhost');
$dbName = trim($_POST['db_name'] ?? '');
$dbUser = trim($_POST['db_user'] ?? '');
$dbPass = $_POST['db_pass'] ?? '';
try {
// Database name goes into `CREATE DATABASE ...` and the generated config, so restrict
// it to a safe identifier charset.
if (!preg_match('/^[A-Za-z0-9_]+$/', $dbName)) {
throw new PDOException('Database name may only contain letters, numbers and underscores.');
}
$pdo = new PDO(
"mysql:host=$dbHost;charset=utf8mb4",
$dbUser, $dbPass,
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);
// Create database if not exists
$pdo->exec("CREATE DATABASE IF NOT EXISTS `$dbName` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
$pdo->exec("USE `$dbName`");
// Create tables
$pdo->exec("CREATE TABLE IF NOT EXISTS `settings` (
`key` VARCHAR(100) PRIMARY KEY,
`value` TEXT NOT NULL,
`updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
$pdo->exec("CREATE TABLE IF NOT EXISTS `reports` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`name` VARCHAR(255) NOT NULL,
`representative` VARCHAR(255) NOT NULL,
`company` VARCHAR(255) NOT NULL,
`email` VARCHAR(255) NOT NULL,
`objectTitle` VARCHAR(255) NOT NULL,
`link` VARCHAR(500) NOT NULL,
`infoHash` VARCHAR(40) NOT NULL,
`magnet_link` TEXT DEFAULT NULL,
`ip` VARCHAR(45) NOT NULL,
`add_message` TEXT DEFAULT '',
`checked` TINYINT(1) DEFAULT 0,
`blocked` TINYINT(1) DEFAULT 0,
`timestamp` DATETIME DEFAULT CURRENT_TIMESTAMP,
INDEX `idx_reports_infohash` (`infoHash`),
INDEX `idx_reports_ip_time` (`ip`, `timestamp`),
INDEX `idx_reports_status` (`checked`, `blocked`, `timestamp`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
$pdo->exec("CREATE TABLE IF NOT EXISTS `sent_emails` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`report_id` INT NOT NULL,
`to_email` VARCHAR(255) NOT NULL,
`subject` VARCHAR(255) NOT NULL,
`message` TEXT,
`message_format` ENUM('plain','bbcode','markdown') NOT NULL DEFAULT 'plain',
`info_hash` VARCHAR(40),
`timestamp` DATETIME DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
$pdo->exec("CREATE TABLE IF NOT EXISTS `archives` (
`id` INT PRIMARY KEY,
`name` VARCHAR(255) NOT NULL,
`representative` VARCHAR(255) NOT NULL,
`company` VARCHAR(255) NOT NULL,
`email` VARCHAR(255) NOT NULL,
`objectTitle` VARCHAR(255) NOT NULL,
`link` VARCHAR(500) NOT NULL,
`infoHash` VARCHAR(40) NOT NULL,
`magnet_link` TEXT DEFAULT NULL,
`ip` VARCHAR(45) NOT NULL,
`add_message` TEXT DEFAULT '',
`checked` TINYINT(1) DEFAULT 0,
`blocked` TINYINT(1) DEFAULT 0,
`timestamp` DATETIME,
INDEX `idx_archives_infohash` (`infoHash`),
INDEX `idx_archives_status` (`checked`, `blocked`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
$pdo->exec("CREATE TABLE IF NOT EXISTS `appeals` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`infoHash` VARCHAR(40) NOT NULL,
`report_id` INT DEFAULT NULL,
`name` VARCHAR(255) NOT NULL,
`email` VARCHAR(255) NOT NULL,
`message` TEXT NOT NULL,
`appeal_type` VARCHAR(20) DEFAULT 'unblock',
`status` VARCHAR(20) DEFAULT 'pending',
`admin_response` TEXT DEFAULT NULL,
`admin_response_format` ENUM('plain','bbcode','markdown') NOT NULL DEFAULT 'plain',
`ip` VARCHAR(45) NOT NULL,
`timestamp` DATETIME DEFAULT CURRENT_TIMESTAMP,
INDEX `idx_appeals_infohash` (`infoHash`),
INDEX `idx_appeals_status_time` (`status`, `timestamp`),
INDEX `idx_appeals_ip_time` (`ip`, `timestamp`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
$pdo->exec("CREATE TABLE IF NOT EXISTS `appeal_archives` (
`id` INT PRIMARY KEY,
`infoHash` VARCHAR(40) NOT NULL,
`report_id` INT DEFAULT NULL,
`name` VARCHAR(255) NOT NULL,
`email` VARCHAR(255) NOT NULL,
`message` TEXT NOT NULL,
`appeal_type` VARCHAR(20) DEFAULT 'unblock',
`status` VARCHAR(20) DEFAULT 'pending',
`admin_response` TEXT DEFAULT NULL,
`admin_response_format` ENUM('plain','bbcode','markdown') NOT NULL DEFAULT 'plain',
`ip` VARCHAR(45) NOT NULL,
`timestamp` DATETIME DEFAULT CURRENT_TIMESTAMP,
`archived_at` DATETIME DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
$pdo->exec("CREATE TABLE IF NOT EXISTS `unsubscribed_emails` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`email` VARCHAR(255) NOT NULL UNIQUE,
`timestamp` DATETIME DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
$pdo->exec("CREATE TABLE IF NOT EXISTS `email_preferences` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`email` VARCHAR(255) NOT NULL,
`type` VARCHAR(30) NOT NULL,
`enabled` TINYINT(1) NOT NULL DEFAULT 1,
`updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY `email_type` (`email`, `type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
// Whitelist / API tables (schema v2) — shared definition with includes/schema.php so upgrades
// and fresh installs create exactly the same structures.
require_once __DIR__ . '/includes/schema.php';
foreach (trackerSchemaStatements() as $sql) {
$pdo->exec($sql);
}
// Save DB config
$_SESSION['install_db'] = [
'host' => $dbHost,
'name' => $dbName,
'user' => $dbUser,
'pass' => $dbPass,
];
header('Location: install.php?step=3');
exit;
} catch (PDOException $e) {
$error = 'Database error: ' . $e->getMessage();
$step = 2;
}
}
// Process Step 3 - Admin + Settings
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $step === 3) {
$adminUser = trim($_POST['admin_user'] ?? '');
$adminPass = $_POST['admin_pass'] ?? '';
$adminPass2 = $_POST['admin_pass2'] ?? '';
$siteUrl = rtrim(trim($_POST['site_url'] ?? ''), '/');
$siteEmail = trim($_POST['site_email'] ?? '');
$mailFrom = trim($_POST['mail_from_email'] ?? '');
$siteName = trim($_POST['site_name'] ?? 'My Tracker');
$announceUrl = trim($_POST['announce_url'] ?? '');
$announceUrlHttps = trim($_POST['announce_url_https'] ?? '');
// CAPTCHA: one provider, one key pair. The keys are stored under the provider's own setting names
// (see the CAPTCHA section of includes/functions.php) so switching providers later in Settings
// never loses the ones already entered here.
$captchaProviders = ['recaptcha', 'recaptcha_v3', 'turnstile', 'hcaptcha'];
$captchaProvider = in_array($_POST['captcha_provider'] ?? '', $captchaProviders, true) ? $_POST['captcha_provider'] : 'recaptcha';
$captchaSiteKey = trim($_POST['captcha_site_key'] ?? '');
$captchaSecret = trim($_POST['captcha_secret'] ?? '');
$captchaKeys = [
'recaptcha' => ['recaptcha_site_key', 'recaptcha_secret'],
'recaptcha_v3' => ['recaptcha_v3_site_key', 'recaptcha_v3_secret'],
'turnstile' => ['turnstile_site_key', 'turnstile_secret'],
'hcaptcha' => ['hcaptcha_site_key', 'hcaptcha_secret'],
][$captchaProvider];
$blacklistPath = trim($_POST['blacklist_path'] ?? '/home/tracker/accesslist/blacklist');
if (strlen($adminUser) < 3) { $error = 'Username must be at least 3 characters.'; }
elseif (strlen($adminPass) < 10) { $error = 'Password must be at least 10 characters long.'; }
elseif (!preg_match('/[a-z]/', $adminPass)) { $error = 'Password must contain at least one lowercase letter.'; }
elseif (!preg_match('/[A-Z]/', $adminPass)) { $error = 'Password must contain at least one uppercase letter.'; }
elseif (!preg_match('/[0-9]/', $adminPass)) { $error = 'Password must contain at least one digit.'; }
elseif (!preg_match('/[^a-zA-Z0-9]/', $adminPass)) { $error = 'Password must contain at least one special character.'; }
elseif ($adminPass !== $adminPass2) { $error = 'Passwords do not match.'; }
elseif (!$siteUrl) { $error = 'Site URL is required.'; }
elseif (!$siteEmail) { $error = 'Contact email is required.'; }
elseif ($mailFrom !== '' && !filter_var($mailFrom, FILTER_VALIDATE_EMAIL)) { $error = 'Sender (From) address is not a valid email.'; }
elseif ($mailFrom !== '' && ($mfHost = strtolower((string)parse_url($siteUrl, PHP_URL_HOST))) !== '' && !filter_var($mfHost, FILTER_VALIDATE_IP)
&& !in_array(strtolower(substr(strrchr($mailFrom, '@'), 1)),
(function ($h) { $l = explode('.', $h); $o = []; for ($i = 0; count($l) - $i >= 2; $i++) $o[] = implode('.', array_slice($l, $i)); return $o; })($mfHost), true)) {
$error = 'Sender (From) domain must match the Site URL domain or its parent (e.g. noreply@' . $mfHost . ').';
}
else {
$db = $_SESSION['install_db'] ?? null;
if (!$db) { header('Location: install.php?step=2'); exit; }
try {
$pdo = new PDO(
"mysql:host={$db['host']};dbname={$db['name']};charset=utf8mb4",
$db['user'], $db['pass'],
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);
// Generate HMAC secret
$hmacSecret = bin2hex(random_bytes(32));
// Hash the admin password and write to file
$hash = password_hash($adminPass, PASSWORD_BCRYPT);
file_put_contents(__DIR__ . '/config/hash.txt', $hash);
// Write database config. Every dynamic value (DSN, user, pass) is emitted via
// var_export so quotes/special chars can't break out of the generated PHP string.
//
// ATTR_TIMEOUT: without it a MariaDB that is down (rather than refusing) holds the connect
// for the TCP timeout, and a php-fpm pool of five is five stuck connects away from serving
// nobody. Three seconds is a lifetime for a local socket and short enough that the 503 the
// bootstrap sends instead still counts as an answer. This file is generated once and never
// rewritten, so an install from before this line has to add it by hand (INSTALL.md).
$dsn = 'mysql:host=' . $db['host'] . ';dbname=' . $db['name'] . ';charset=utf8mb4';
$dbConfig = "<?php\n\nfunction getDb(): PDO {\n static \$pdo = null;\n if (\$pdo === null) {\n \$pdo = new PDO(\n " . var_export($dsn, true) . ",\n " . var_export($db['user'], true) . ",\n " . var_export($db['pass'], true) . ",\n [\n PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,\n PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,\n PDO::ATTR_EMULATE_PREPARES => false,\n PDO::ATTR_TIMEOUT => 3,\n ]\n );\n // keep MySQL's session clock in the SAME zone as PHP so NOW()/CURRENT_TIMESTAMP\n // and PHP date() agree (date filters, samplers and DEFAULT columns mix both)\n \$pdo->exec(\"SET time_zone = '\" . date('P') . \"'\");\n }\n return \$pdo;\n}\n";
file_put_contents(__DIR__ . '/config/database.php', $dbConfig);
// Insert default settings into DB
$defaults = [
'site_name' => $siteName,
'site_email' => $siteEmail,
'mail_from_email' => $mailFrom,
'site_url' => $siteUrl,
'admin_username' => $adminUser,
'captcha_provider' => $captchaProvider,
$captchaKeys[0] => $captchaSiteKey,
$captchaKeys[1] => $captchaSecret,
// The CAPTCHA's master switch is the keys: on only when the chosen provider has BOTH its site key and
// its secret, off otherwise (the keys are optional, and a half pair protects nothing). Which forms it
// guards is not decided here: the five `recaptcha_on_*` switches come from trackerSchemaDefaultSettings()
// below — their one home. (This list used to carry its own copies, and its sign-in switch said 1 where
// the schema said 0: the same site answered differently by how it had been installed.)
'recaptcha_enabled' => ($captchaSiteKey !== '' && $captchaSecret !== '') ? '1' : '0',
'captcha_threshold' => '6',
'captcha_grace_minutes' => '5',
'captcha_pts_report' => '2',
'captcha_pts_status' => '1',
'captcha_pts_appeal' => '3',
'captcha_pts_block_check' => '1',
'delete_captcha_attempts' => '2',
'delete_lockout_attempts' => '5',
'delete_lockout_minutes' => '60',
'login_lockout_attempts' => '5',
'login_lockout_minutes' => '15',
'rate_limit_status' => '20',
'rate_limit_block_check' => '30',
'rate_limit_appeal' => '5',
'admin_session_idle_minutes' => '30',
'admin_session_absolute_hours' => '12',
'trusted_proxy_ips' => '',
'client_ip_header' => '',
'auto_archive_days' => '90',
'auto_archive_appeal_days' => '90',
'sent_emails_retention_days' => '0',
'max_magnet_link_length' => '0',
'blacklist_path' => $blacklistPath,
'rate_limit' => '5',
'items_per_page' => '15',
'max_message_length' => '2000',
'max_appeal_message_length' => '2000',
'hmac_secret' => $hmacSecret,
'announce_url' => $announceUrl,
'announce_url_https' => $announceUrlHttps,
'contact_visible' => '1',
'contact_obfuscate' => '1',
'donations_enabled' => '0',
'donation_fields' => '[]',
'transparency_enabled' => '1',
'transparency_per_page' => '150',
'github_url' => '',
'tracker_stats_enabled' => '0',
'tracker_stats_url' => '',
'tracker_stats_interval' => '10',
'tracker_stats_page_interval' => '5',
'tracker_stats_cache_ttl' => '60',
'tracker_stats_show_home' => '1',
'tracker_stats_timeout' => '30',
'tracker_stats_min_loading' => '1000',
'tracker_stats_max_loading' => '1000',
'tracker_stats_peer_label_style' => 'percent',
'tracker_stats_livesync_mode' => 'upstream',
'opentracker_service_name' => '',
'opentracker_restart_use_sudo' => '1',
'opentracker_auto_reload' => '1',
'tracker_blacklist_warn_count' => '1',
'tracker_blacklist_danger_count' => '5',
'tracker_uptime_warn_days' => '14',
'tracker_uptime_danger_days' => '30',
'footer_start_year' => date('Y'),
'footer_brand_name' => $siteName,
'footer_brand_url' => $siteUrl,
'footer_brand_enabled' => '1',
'footer_tracker_name' => 'OpenTracker',
'footer_tracker_url' => 'https://erdgeist.org/arts/software/opentracker/',
'footer_tracker_author' => 'Dirk Engling',
'footer_tracker_author_url' => 'https://erdgeist.org/',
'footer_tracker_enabled' => '1',
'footer_os_name' => 'Debian',
'footer_os_url' => 'https://www.debian.org/',
'footer_os_enabled' => '1',
'footer_os_since_year' => date('Y'),
];
// Whitelist / CAPTCHA provider / API defaults (see includes/schema.php)
require_once __DIR__ . '/includes/schema.php';
// ensureSchema() below runs the data migrations, which read the permission registry
// (userPermissionList / userLegacyDefault) and re-read settings. The installer loads
// only functions.php on its own, so those two come in here rather than being discovered
// as a fatal halfway through writing somebody's database.
require_once __DIR__ . '/includes/settings.php';
require_once __DIR__ . '/includes/mail.php';
require_once __DIR__ . '/includes/users.php';
$defaults += trackerSchemaDefaultSettings();
// schema_version deliberately 0 — see the block below.
$defaults['schema_version'] = '0';
$stmt = $pdo->prepare("INSERT INTO settings (`key`, `value`) VALUES (?, ?) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`)");
foreach ($defaults as $k => $v) {
$stmt->execute([$k, $v]);
}
// ── A FRESH INSTALL GOES THROUGH THE UPGRADE PATH, NOT AROUND IT ──────────────────
//
// This used to stamp schema_version = TRACKER_SCHEMA_VERSION and stop, on the reasoning
// that trackerSchemaStatements() above had just created every table. It had not. A
// column added after its table was written lives in trackerSchemaGuardedStatements(),
// and a group permission added later lives in trackerSchemaDataMigrations() — and
// ensureSchema() returns immediately when the version already matches, so neither ran.
//
// Measured against an upgraded database, a fresh install was short of: fourteen columns
// on `whitelist` (source_url, description, content_status, probe_status, dead_since, the
// four rating columns…), four on `index_hashes`, `users.bulk_optout`, the whole
// `moderator` group, and seven permissions on `guest`/`member`. The whitelist page
// selects some of those columns by name, so the site did not come up.
//
// The fix is to have ONE path: build the base tables, then let the ordinary migration
// run from zero. It is the path every upgrade takes and the one the whole test battery
// exercises on every run.
//
// That was necessary and, on its own, not sufficient — which is the later half of this
// story. Outside the CLI the migration DECLINES the ALTERs that rebuild `index_hashes`
// (see schemaHeavyAllowed()), and a declined migration leaves schema_version unwritten,
// so the check below refused a browser install and no config/installed.lock was ever
// written. Hence the two changes that go with this comment: those columns and indexes
// are now in the base CREATE TABLEs as well (trackerSchemaStatements(), where
// tests/install_test.php compares them against the migration's own, column type by
// column type), and TRACKER_SCHEMA_FORCE_HEAVY is defined at the top of this file so
// that the next column somebody adds to the guarded list ALONE still arrives here.
// Neither replaces this path: the group permissions below come only from the data
// migrations, and nothing but running them produces those.
$installCfg = [];
foreach ($pdo->query("SELECT `key`, `value` FROM settings")->fetchAll(PDO::FETCH_ASSOC) as $row) {
$installCfg[$row['key']] = $row['value'];
}
ensureSchema($pdo, $installCfg);
$landed = (int)($pdo->query("SELECT `value` FROM settings WHERE `key` = 'schema_version'")->fetchColumn() ?: 0);
if ($landed < TRACKER_SCHEMA_VERSION) {
// Never a half-built install reported as finished. schemaDeferHeavy() only defers a
// rebuild of a table that cannot exist yet, so on an empty database this means a
// migration actually failed — and its message is in the PHP error log.
throw new Exception('the database schema stopped at version ' . $landed . ' of '
. TRACKER_SCHEMA_VERSION . ' — see the PHP error log, then reload this page');
}
// Mirror the panel admin into the user system (admin group members pass every
// permission check). Upgraded installs get the same via trackerSchemaDataMigrations().
try {
if (preg_match('/^[A-Za-z0-9_.-]{3,32}$/', $adminUser)) {
$pdo->prepare("INSERT IGNORE INTO users (username, email, pass_hash) VALUES (?, NULL, ?)")->execute([$adminUser, $hash]);
$pdo->exec("INSERT IGNORE INTO user_group_members (user_id, group_id, granted_by, note)
SELECT u.id, g.id, 'install', 'panel admin' FROM users u JOIN user_groups g ON g.slug = 'admin'
WHERE u.username = " . $pdo->quote($adminUser));
}
} catch (Exception $e) { /* non-fatal — the admin can grant the group in the panel */ }
// Create lock file
file_put_contents(__DIR__ . '/config/installed.lock', date('Y-m-d H:i:s'));
$_SESSION = [];
session_destroy();
header('Location: install.php?step=4');
exit;
} catch (Exception $e) {
$error = 'Setup error: ' . $e->getMessage();
}
}
$step = 3;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Install - TryHackX Tracker</title>
<?php /* The icon font, through the same helper as every other page. There are no settings yet —
the database is what this page is configuring — so it is always Bootstrap Icons here. */ ?>
<?= iconFontTag([]) ?>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body { background: #0a0a1a; color: #e0e0e0; font-family: 'Courier New', monospace; min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 2rem; }
.installer { background: #111; border: 1px solid #333; border-radius: 8px; padding: 2rem; max-width: 600px; width: 100%; }
h1 { color: #4a9eff; margin-bottom: 0.5rem; font-size: 1.4rem; }
h2 { color: #BAD7FF; margin-bottom: 1rem; font-size: 1.1rem; }
.steps { display: flex; gap: 0.5rem; margin-bottom: 1.5rem; }
.step { padding: 0.3rem 0.8rem; border-radius: 4px; font-size: 0.8rem; background: #222; color: #666; }
.step.active { background: #4a9eff; color: #000; }
.step.done { background: #2a4a2a; color: #4caf50; }
.form-group { margin-bottom: 1rem; }
label { display: block; color: #bbb; margin-bottom: 0.3rem; font-size: 0.85rem; }
label small { color: #666; }
input[type="text"], input[type="password"], input[type="email"], input[type="url"], input[type="number"] {
width: 100%; padding: 0.5rem 0.7rem; background: #1a1a2e; border: 1px solid #333; border-radius: 4px;
color: #e0e0e0; font-family: inherit; font-size: 0.85rem;
}
input:focus { outline: none; border-color: #4a9eff; }
.btn { padding: 0.6rem 1.5rem; background: #4a9eff; color: #000; border: none; border-radius: 4px; cursor: pointer; font-family: inherit; font-size: 0.9rem; }
.btn:hover { opacity: 0.85; }
.error { background: rgba(244,67,54,0.15); border: 1px solid #f44336; color: #f44336; padding: 0.5rem; border-radius: 4px; margin-bottom: 1rem; font-size: 0.85rem; }
.success { background: rgba(76,175,80,0.15); border: 1px solid #4caf50; color: #4caf50; padding: 0.5rem; border-radius: 4px; margin-bottom: 1rem; font-size: 0.85rem; }
.info { background: rgba(74,158,255,0.1); border: 1px solid #4a9eff33; color: #8ab4f8; padding: 0.5rem; border-radius: 4px; margin-bottom: 1rem; font-size: 0.8rem; }
hr { border: none; border-top: 1px solid #333; margin: 1.25rem 0; }
a { color: #4a9eff; }
.two-col { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }
.pw-req { display: inline-block; width: 48%; color: #555; transition: color .2s; }
.pw-req.ok { color: #4caf50; }
.pw-req.fail { color: #f44336; }
.pw-dot { font-size: 0.55em; vertical-align: 0.15em; }
@media (max-width: 500px) { .two-col { grid-template-columns: 1fr; } .pw-req { width: 100%; } }
</style>
</head>
<body>
<div class="installer">
<h1>TryHackX Tracker</h1>
<div class="steps">
<span class="step <?= $step === 1 ? 'active' : ($step > 1 ? 'done' : '') ?>">1. Welcome</span>
<span class="step <?= $step === 2 ? 'active' : ($step > 2 ? 'done' : '') ?>">2. Database</span>
<span class="step <?= $step === 3 ? 'active' : ($step > 3 ? 'done' : '') ?>">3. Settings</span>
<span class="step <?= $step === 4 ? 'active' : '' ?>">4. Done</span>
</div>
<?php if ($error): ?><div class="error"><?= htmlspecialchars($error) ?></div><?php endif; ?>
<?php if ($step === 1): ?>
<h2>Installation Wizard</h2>
<p style="margin-bottom:1rem;color:#aaa;">This wizard will configure your BitTorrent tracker information and reporting system.</p>
<div class="info">
<strong>Requirements:</strong><br>
• PHP 8.0+ with PDO MySQL<br>
• MariaDB 10.6+ (MySQL is not supported)<br>
• Apache with mod_rewrite (optional)
</div>
<p style="margin-bottom:1rem;">
<?php
$checks = [
'PHP ' . PHP_VERSION => version_compare(PHP_VERSION, '8.0.0', '>='),
'PDO MySQL' => extension_loaded('pdo_mysql'),
'JSON' => extension_loaded('json'),
// The HTML sanitizer of a bulk message and a rich notification (includes/htmlsafe.php) parses with it.
'DOM (php-xml)' => extension_loaded('dom'),
'OpenSSL' => extension_loaded('openssl'),
'Config writable' => is_writable(__DIR__ . '/config/'),
];
foreach ($checks as $name => $ok): ?>
<span style="color:<?= $ok ? '#4caf50' : '#f44336' ?>;"><?= $ok ? '<i class="bi bi-check-lg" aria-hidden="true"></i>' : '<i class="bi bi-x-lg" aria-hidden="true"></i>' ?> <?= $name ?></span><br>
<?php endforeach; ?>
</p>
<a href="install.php?step=2" class="btn">Start Installation</a>
<?php elseif ($step === 2): ?>
<h2>Database Configuration</h2>
<form method="post" action="install.php?step=2">
<div class="form-group">
<label>Database Host</label>
<input type="text" name="db_host" value="<?= htmlspecialchars($_POST['db_host'] ?? 'localhost') ?>" required>
</div>
<div class="form-group">
<label>Database Name <small>(will be created if missing)</small></label>
<input type="text" name="db_name" value="<?= htmlspecialchars($_POST['db_name'] ?? 'tracker') ?>" required>
</div>
<div class="two-col">
<div class="form-group">
<label>Database User</label>
<input type="text" name="db_user" value="<?= htmlspecialchars($_POST['db_user'] ?? 'root') ?>" required>
</div>
<div class="form-group">
<label>Database Password</label>
<input type="password" name="db_pass" value="">
</div>
</div>
<button type="submit" class="btn">Test & Create Database</button>
</form>
<?php elseif ($step === 3): ?>
<h2>Site & Admin Settings</h2>
<form method="post" action="install.php?step=3">
<h3 style="color:#4a9eff;margin-bottom:0.5rem;font-size:0.95rem;">Admin Account</h3>
<div class="form-group">
<label>Admin Username</label>
<input type="text" name="admin_user" value="<?= htmlspecialchars($_POST['admin_user'] ?? 'admin') ?>" minlength="3" required>
</div>
<div class="two-col">
<div class="form-group">
<label>Password</label>
<input type="password" name="admin_pass" id="admin_pass" minlength="10" required>
</div>
<div class="form-group">
<label>Confirm Password</label>
<input type="password" name="admin_pass2" id="admin_pass2" minlength="10" required>
</div>
</div>
<div id="pw-reqs" style="margin:-0.5rem 0 1rem;font-size:0.78rem;line-height:1.7;">
<span id="pw-len" class="pw-req"><i class="bi bi-circle-fill pw-dot" aria-hidden="true"></i> At least 10 characters</span>
<span id="pw-low" class="pw-req"><i class="bi bi-circle-fill pw-dot" aria-hidden="true"></i> Lowercase letter (a-z)</span>
<span id="pw-up" class="pw-req"><i class="bi bi-circle-fill pw-dot" aria-hidden="true"></i> Uppercase letter (A-Z)</span>
<span id="pw-dig" class="pw-req"><i class="bi bi-circle-fill pw-dot" aria-hidden="true"></i> Digit (0-9)</span>
<span id="pw-spc" class="pw-req"><i class="bi bi-circle-fill pw-dot" aria-hidden="true"></i> Special character (!@#$...)</span>
<span id="pw-match" class="pw-req" style="display:none;"><i class="bi bi-circle-fill pw-dot" aria-hidden="true"></i> Passwords match</span>
</div>
<div id="pw-strength" style="margin:-0.5rem 0 1rem;">
<div style="height:4px;background:#222;border-radius:2px;overflow:hidden;">
<div id="pw-bar" style="height:100%;width:0;transition:all .3s;border-radius:2px;"></div>
</div>
<small id="pw-label" style="color:#666;font-size:0.75rem;"></small>
</div>
<hr>
<h3 style="color:#4a9eff;margin-bottom:0.5rem;font-size:0.95rem;">Site Configuration</h3>
<div class="form-group">
<label>Site Name</label>
<input type="text" name="site_name" value="<?= htmlspecialchars($_POST['site_name'] ?? 'My Tracker') ?>" required>
</div>
<div class="two-col">
<div class="form-group">
<label>Site URL <small>(no trailing slash)</small></label>
<input type="url" name="site_url" value="<?= htmlspecialchars($_POST['site_url'] ?? '') ?>" placeholder="https://tracker.example.com" required>
</div>
<div class="form-group">
<label>Contact Email</label>
<input type="email" name="site_email" value="<?= htmlspecialchars($_POST['site_email'] ?? '') ?>" placeholder="tracker@example.com" required>
</div>
</div>
<div class="form-group">
<label>Sender (From) Email <small>(optional — mails are sent FROM this address, replies go to the contact email; must be on the Site URL domain or its parent, e.g. noreply@example.com)</small></label>
<input type="email" name="mail_from_email" value="<?= htmlspecialchars($_POST['mail_from_email'] ?? '') ?>" placeholder="noreply@example.com">
</div>
<hr>
<h3 style="color:#4a9eff;margin-bottom:0.5rem;font-size:0.95rem;">Tracker Announce URLs</h3>
<div class="two-col">
<div class="form-group">
<label>Announce URL (HTTP/S)</label>
<input type="text" name="announce_url_https" value="<?= htmlspecialchars($_POST['announce_url_https'] ?? '') ?>" placeholder="https://tracker.example.com:6969/announce">
</div>
<div class="form-group">
<label>Announce URL (UDP)</label>
<input type="text" name="announce_url" value="<?= htmlspecialchars($_POST['announce_url'] ?? '') ?>" placeholder="udp://tracker.example.com:6969/announce">
</div>
</div>
<hr>
<?php $cpSel = $_POST['captcha_provider'] ?? 'recaptcha'; ?>
<h3 style="color:#4a9eff;margin-bottom:0.5rem;font-size:0.95rem;">CAPTCHA <small style="color:#666;">(optional — switched on only when both keys are given)</small></h3>
<div class="form-group">
<label>Provider</label>
<select name="captcha_provider">
<option value="recaptcha" <?= $cpSel === 'recaptcha' ? 'selected' : '' ?>>Google reCAPTCHA v2 (checkbox)</option>
<option value="recaptcha_v3" <?= $cpSel === 'recaptcha_v3' ? 'selected' : '' ?>>Google reCAPTCHA v3 (invisible, score)</option>
<option value="turnstile" <?= $cpSel === 'turnstile' ? 'selected' : '' ?>>Cloudflare Turnstile</option>
<option value="hcaptcha" <?= $cpSel === 'hcaptcha' ? 'selected' : '' ?>>hCaptcha</option>
</select>
</div>
<div class="two-col">
<div class="form-group">
<label>Site Key</label>
<input type="text" name="captcha_site_key" value="<?= htmlspecialchars($_POST['captcha_site_key'] ?? '') ?>">
</div>
<div class="form-group">
<label>Secret Key</label>
<input type="password" name="captcha_secret" value="<?= htmlspecialchars($_POST['captcha_secret'] ?? '') ?>" autocomplete="off">
</div>
</div>
<p style="color:#666;font-size:0.8rem;margin:-0.4rem 0 0;">Leave both keys empty to keep the CAPTCHA off and set it up later; with both given it is on and guards the abuse-report form (the other forms' switches are in Admin → Settings → CAPTCHA). The keys of the other providers can be added there too. If your site sits behind a strict Content-Security-Policy of your own, remember to allow the provider's script host.</p>
<hr>
<h3 style="color:#4a9eff;margin-bottom:0.5rem;font-size:0.95rem;">Blacklist File <small style="color:#666;">(newline-separated hash list)</small></h3>
<div class="form-group">
<label>Blacklist File Path</label>
<div style="display:flex;gap:0.5rem;">
<input type="text" name="blacklist_path" id="blacklist_path" value="<?= htmlspecialchars($_POST['blacklist_path'] ?? '/home/tracker/accesslist/blacklist') ?>" style="flex:1;">
<button type="button" class="btn" style="background:#333;color:#4a9eff;padding:0.5rem 1rem;font-size:0.8rem;white-space:nowrap;" onclick="testBlacklist()">Test</button>
</div>
<div id="bl-result" style="margin-top:0.4rem;font-size:0.8rem;"></div>
</div>
<button type="submit" class="btn">Complete Installation</button>
</form>
<?php elseif ($step === 4): ?>
<h2>Installation Complete!</h2>
<div class="success">Your tracker has been configured successfully.</div>
<div class="info" style="margin-top:1rem;">
<strong>Important:</strong> Delete the installer file from your server for security!
</div>
<div style="margin:1.25rem 0;display:flex;flex-wrap:wrap;gap:0.75rem;align-items:center;">
<a href="./" class="btn">Open Tracker</a>
<a href="./?action=admin" style="color:#aaa;">Go to Admin Panel</a>
</div>
<hr>
<form method="post" action="install.php?step=4&cleanup=1" style="margin-top:1rem;" id="cleanup-form">
<p style="color:#ff9800;font-size:0.85rem;margin-bottom:0.75rem;"><strong><i class="bi bi-exclamation-triangle" aria-hidden="true"></i> Security Cleanup</strong> — This will permanently delete the installer file so it cannot be accessed by anyone.</p>
<button type="submit" class="btn" style="background:#f44336;color:#fff;" onclick="return confirm('Are you sure? This will permanently delete the install file.')">
<i class="bi bi-trash" aria-hidden="true"></i> Delete install.php
</button>
</form>
<?php endif; ?>
</div>
<!--
NO NONCE HERE, on purpose. The installer never sends a Content-Security-Policy: cspSend() needs
$cfg, and $cfg needs the database this page is still being asked to configure. So this block and
the onclick= on the cleanup button above both run, exactly as they always have.
If a policy is ever added to this file, a nonce on this <script> is NOT enough — the onclick has
to become a listener first, because script-src without 'unsafe-inline' blocks an attribute handler
whatever nonce the page carries. install.php is also excluded from deploy/deploy.py, so it is the
one entry point that never reaches a server with a policy in front of it.
-->
<script>
async function testBlacklist() {
const el = document.getElementById('bl-result');
const path = document.getElementById('blacklist_path');
if (!path) return;
el.innerHTML = '<span style="color:#4a9eff;">Testing...</span>';
try {
const form = new FormData();
form.append('path', path.value);
const res = await fetch('install.php?test_blacklist=1', { method: 'POST', body: form });
const json = await res.json();
if (json.ok) {
el.innerHTML = '<span style="color:#4caf50;"><i class="bi bi-check-lg" aria-hidden="true"></i> ' + json.msg + '</span>' +
(json.user ? '<br><small style="color:#a0a0b0;">PHP user: ' + json.user + '</small>' : '');
} else {
el.innerHTML = '<span style="color:#f44336;"><i class="bi bi-x-lg" aria-hidden="true"></i> ' + json.msg + '</span>' +
(json.hint ? '<br><small style="color:#ff9800;">' + json.hint + '</small>' : '') +
(json.user ? '<br><small style="color:#a0a0b0;">PHP user: ' + json.user + '</small>' : '');
}
} catch {
el.innerHTML = '<span style="color:#f44336;">Network error</span>';
}
}
// Password validation
(function() {
const p1 = document.getElementById('admin_pass');
const p2 = document.getElementById('admin_pass2');
if (!p1 || !p2) return;
const rules = {
'pw-len': v => v.length >= 10,
'pw-low': v => /[a-z]/.test(v),
'pw-up': v => /[A-Z]/.test(v),
'pw-dig': v => /[0-9]/.test(v),
'pw-spc': v => /[^a-zA-Z0-9]/.test(v),
};
const bar = document.getElementById('pw-bar');
const label = document.getElementById('pw-label');
const matchEl = document.getElementById('pw-match');
function check() {
const v = p1.value;
let score = 0;
for (const [id, fn] of Object.entries(rules)) {
const el = document.getElementById(id);
const ok = fn(v);
if (ok) score++;
el.className = v.length === 0 ? 'pw-req' : ('pw-req ' + (ok ? 'ok' : 'fail'));
}
// Match check
if (p2.value.length > 0) {
matchEl.style.display = 'inline-block';
const m = v === p2.value;
matchEl.className = 'pw-req ' + (m ? 'ok' : 'fail');
} else {
matchEl.style.display = v.length > 0 ? 'inline-block' : 'none';
matchEl.className = 'pw-req';
}
// Strength bar
if (v.length === 0) {
bar.style.width = '0';
label.textContent = '';
return;
}
// Bonus for length
if (v.length >= 14) score += 0.5;
if (v.length >= 18) score += 0.5;
const pct = Math.min(100, (score / 6) * 100);
bar.style.width = pct + '%';
if (pct < 40) { bar.style.background = '#f44336'; label.textContent = 'Weak'; label.style.color = '#f44336'; }
else if (pct < 70) { bar.style.background = '#ff9800'; label.textContent = 'Moderate'; label.style.color = '#ff9800'; }
else if (pct < 100) { bar.style.background = '#8bc34a'; label.textContent = 'Strong'; label.style.color = '#8bc34a'; }
else { bar.style.background = '#4caf50'; label.textContent = 'Excellent'; label.style.color = '#4caf50'; }
}
p1.addEventListener('input', check);
p2.addEventListener('input', check);
})();
</script>
</body>
</html>