Repository navigation
Expand file tree
/
Copy pathKeyHelp.module.php
More file actions
704 lines (618 loc) · 29.3 KB
/
Copy pathKeyHelp.module.php
File metadata and controls
704 lines (618 loc) · 29.3 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
<?php namespace ProcessWire;
/**
* KeyHelp
*
* Core module: configuration storage and API client for the KeyHelp hosting panel.
* UI is provided by the companion ProcessKeyHelp module.
*
* @author Maxim Semenov <maxim@smnv.org> (smnv.org)
* @link https://smnv.org
* @license MIT
* @version 100
*
* @property string $api_url KeyHelp panel base URL
* @property string $api_key Admin API token
* @property int $cache_time GET response cache TTL in seconds (0 = off)
* @property bool $verify_ssl Verify SSL certificate on API requests
* @property string $api_resolve_ip Optional IP address for cURL DNS override
*/
class KeyHelp extends WireData implements Module, ConfigurableModule {
// -----------------------------------------------------------------------
// Module info
// -----------------------------------------------------------------------
public static function getModuleInfo(): array {
return [
'title' => 'KeyHelp',
'version' => 100,
'summary' => 'KeyHelp hosting panel API client and configuration. Requires ProcessKeyHelp for the admin UI.',
'author' => 'Maxim Semenov',
'href' => 'https://smnv.org',
'singular' => true,
'autoload' => false,
'icon' => 'server',
'requires' => ['ProcessWire>=3.0.200', 'PHP>=8.0.0'],
'installs' => ['ProcessKeyHelp'],
];
}
// -----------------------------------------------------------------------
// Constants
// -----------------------------------------------------------------------
const CACHE_NS = 'KeyHelp';
const API_TIMEOUT = 15;
const ENDPOINTS = [
'status' => '/api/v2/server',
'server' => '/api/v2/server',
'server_reboot' => '/api/v2/server/reboot',
'clients' => '/api/v2/clients',
'client' => '/api/v2/clients/{id}',
'domains' => '/api/v2/domains',
'domain' => '/api/v2/domains/{id}',
'domain_ssl' => '/api/v2/domains/{id}',
'domain_php' => '/api/v2/domains/{id}',
'domain_dns' => '/api/v2/dns/{id}',
'databases' => '/api/v2/databases',
'database' => '/api/v2/databases/{id}',
'emails' => '/api/v2/emails',
'email' => '/api/v2/emails/{id}',
'hosting_plans' => '/api/v2/hosting-plans',
'ftp_accounts' => '/api/v2/ftp-users',
'ftp_account' => '/api/v2/ftp-users/{id}',
'ssl_certs' => '/api/v2/certificates',
'ssl_cert' => '/api/v2/certificates/{id}',
'cron_tasks' => '/api/v2/scheduled-tasks',
'cron_task' => '/api/v2/scheduled-tasks/{id}',
];
// -----------------------------------------------------------------------
// Defaults
// -----------------------------------------------------------------------
public static function getDefaultConfig(): array {
return [
'api_url' => '',
'api_key' => '',
'api_resolve_ip' => '',
'cache_time' => 60,
'verify_ssl' => 1,
'ui_language' => 'auto', // 'auto' | 'en' | 'de'
'debug_mode' => 0,
'document_root_pattern' => '/home/users/{username}/www/{domain}',
'installer_deploy_mode' => 'auto',
'installer_ssh_host' => '',
'installer_ssh_port' => 22,
'installer_ssh_user' => '{username}',
'installer_ssh_key_path' => '',
'installer_ssh_password' => '',
'installer_ssh_php' => 'php',
'tenant_mode' => 'multi', // 'multi' | 'single'
'tenant_client_id'=> 0, // KeyHelp client ID for single-tenant mode
];
}
public function __construct() {
parent::__construct();
foreach (self::getDefaultConfig() as $k => $v) {
$this->set($k, $v);
}
}
// -----------------------------------------------------------------------
// Install / Uninstall
// -----------------------------------------------------------------------
public function ___install(): void {
if (!$this->wire('modules')->isInstalled('ProcessKeyHelp')) {
$this->wire('modules')->install('ProcessKeyHelp');
}
}
public function ___uninstall(): void {
$this->wire('cache')->deleteFor(self::CACHE_NS);
}
// -----------------------------------------------------------------------
// API: public methods
// -----------------------------------------------------------------------
/**
* GET with optional caching.
*/
public function apiGet(string $endpoint, array $params = [], bool $fresh = false): array {
$cacheKey = $endpoint . ($params ? ':' . http_build_query($params) : '');
$ttl = (int) $this->cache_time;
if (!$fresh && $ttl > 0) {
$cached = $this->wire('cache')->getFor(self::CACHE_NS, $cacheKey, $ttl);
if ($cached !== null) {
$this->debugLog('API cache hit', [
'endpoint' => $endpoint,
'params' => $params,
'cache_key' => $cacheKey,
]);
return (array) $cached;
}
}
$result = $this->request('GET', $this->url($endpoint, $params), [], [
'endpoint' => $endpoint,
'params' => $params,
'fresh' => $fresh,
]);
if (!isset($result['error']) && $ttl > 0) {
$this->wire('cache')->saveFor(self::CACHE_NS, $cacheKey, $result, $ttl);
}
return $result;
}
/**
* POST — create resource, then flush cached API responses.
*/
public function apiPost(string $endpoint, array $data = [], array $params = []): array {
$result = $this->request('POST', $this->url($endpoint, $params), $data, [
'endpoint' => $endpoint,
'params' => $params,
]);
$this->flushCache();
return $result;
}
/**
* PUT — update resource.
* @param string $endpoint Endpoint key, e.g. 'domain_ssl'
* @param array $params URL params, e.g. ['id' => 5]
* @param array $data Request body
* @param string $bustKey Deprecated; all KeyHelp cache entries are flushed after writes.
*/
public function apiPut(string $endpoint, array $params = [], array $data = [], string $bustKey = ''): array {
$result = $this->request('PUT', $this->url($endpoint, $params), $data, [
'endpoint' => $endpoint,
'params' => $params,
]);
$this->flushCache();
return $result;
}
/**
* DELETE resource.
*/
public function apiDelete(string $endpoint, array $params = []): array {
$result = $this->request('DELETE', $this->url($endpoint, $params), [], [
'endpoint' => $endpoint,
'params' => $params,
]);
$this->flushCache();
return $result;
}
/**
* Flush entire KeyHelp cache namespace.
*/
public function flushCache(): void {
$this->wire('cache')->deleteFor(self::CACHE_NS);
}
/**
* True if the module has been configured.
*/
public function isConfigured(): bool {
return (bool) $this->api_url && (bool) $this->api_key;
}
/**
* True when running in single-tenant mode.
*/
public function isSingleTenant(): bool {
return $this->tenant_mode === 'single' && (int) $this->tenant_client_id > 0;
}
/**
* Return the locked client ID in single-tenant mode, or 0 in multi-tenant.
*/
public function tenantClientId(): int {
return $this->isSingleTenant() ? (int) $this->tenant_client_id : 0;
}
/**
* Filter a list API response to only items belonging to the tenant client.
* In multi-tenant mode returns the list unchanged.
*
* @param array $list Raw API list response
* @param string $field The field that contains the client_id (default: 'client_id')
*/
public function filterByTenant(array $list, string $field = 'client_id'): array {
if (!$this->isSingleTenant()) return $list;
$cid = $this->tenantClientId();
return array_values(array_filter($list, function($item) use ($field, $cid) {
$value = $item[$field] ?? $item['id_user'] ?? 0;
return (int) $value === $cid;
}));
}
/**
* Assert that a resource belongs to the tenant client.
* Returns true if allowed, false if access denied.
*/
public function tenantCan(array $resource, string $field = 'client_id'): bool {
if (!$this->isSingleTenant()) return true;
return (int)($resource[$field] ?? $resource['id_user'] ?? 0) === $this->tenantClientId();
}
public function debugLog(string $message, array $context = []): void {
if (empty($this->debug_mode)) return;
$entry = [
'message' => $message,
'context' => $this->redactDebugData($context),
];
$json = json_encode($entry, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
$this->wire('log')->save('keyhelp-debug', $json ?: $message);
}
// -----------------------------------------------------------------------
// Internal helpers
// -----------------------------------------------------------------------
private function url(string $key, array $params = []): string {
$path = self::ENDPOINTS[$key] ?? "/api/v2/{$key}";
foreach ($params as $k => $v) {
$path = str_replace('{' . $k . '}', (string) $v, $path);
}
return rtrim($this->api_url, '/') . $path;
}
private function request(string $method, string $url, array $body = [], array $context = []): array {
if (!function_exists('curl_init')) {
$this->debugLog('API request failed before cURL', [
'method' => $method,
'url' => $this->redactUrl($url),
'request' => $context,
'error' => 'PHP cURL extension is not available.',
]);
return ['error' => true, 'message' => 'PHP cURL extension is not available.'];
}
$requestId = bin2hex(random_bytes(4));
$started = microtime(true);
$this->debugLog('API request', [
'request_id' => $requestId,
'method' => $method,
'url' => $this->redactUrl($url),
'request' => $context,
'body' => $body,
'verify_ssl' => (bool)$this->verify_ssl,
'api_resolve_ip' => $this->api_resolve_ip ?: '',
]);
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => self::API_TIMEOUT,
CURLOPT_SSL_VERIFYPEER => (bool) $this->verify_ssl,
CURLOPT_SSL_VERIFYHOST => $this->verify_ssl ? 2 : 0,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Accept: application/json',
'X-API-Key: ' . $this->api_key,
],
]);
$resolve = $this->curlResolveEntry($url);
if ($resolve) {
curl_setopt($ch, CURLOPT_RESOLVE, [$resolve]);
}
if ($method === 'POST') {
curl_setopt($ch, CURLOPT_POST, true);
$json = json_encode($body);
if ($json === false) {
$this->debugLog('API request JSON encode failed', [
'request_id' => $requestId,
'method' => $method,
'url' => $this->redactUrl($url),
'json_error' => json_last_error_msg(),
'body' => $body,
]);
return ['error' => true, 'message' => 'Cannot encode request body as JSON.'];
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
} elseif ($method === 'PUT') {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
$json = json_encode($body);
if ($json === false) {
$this->debugLog('API request JSON encode failed', [
'request_id' => $requestId,
'method' => $method,
'url' => $this->redactUrl($url),
'json_error' => json_last_error_msg(),
'body' => $body,
]);
return ['error' => true, 'message' => 'Cannot encode request body as JSON.'];
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
} elseif ($method === 'DELETE') {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
}
$raw = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$err = curl_error($ch);
$durationMs = round((microtime(true) - $started) * 1000, 2);
if ($err) {
$this->debugLog('API cURL error', [
'request_id' => $requestId,
'method' => $method,
'url' => $this->redactUrl($url),
'http_code' => $code,
'duration_ms' => $durationMs,
'error' => $err,
]);
return ['error' => true, 'message' => "cURL: $err"];
}
$decoded = json_decode($raw, true);
if ($decoded === null && $raw !== '') {
$this->debugLog('API invalid JSON response', [
'request_id' => $requestId,
'method' => $method,
'url' => $this->redactUrl($url),
'http_code' => $code,
'duration_ms' => $durationMs,
'raw_response' => $this->truncateDebugString((string)$raw),
]);
return ['error' => true, 'message' => "Invalid JSON (HTTP $code)"];
}
$result = is_array($decoded) ? $decoded : [];
if ($code >= 400) {
$result['error'] = true;
$result['message'] = $result['message'] ?? "HTTP $code";
}
$this->debugLog('API response', [
'request_id' => $requestId,
'method' => $method,
'url' => $this->redactUrl($url),
'http_code' => $code,
'duration_ms' => $durationMs,
'response' => $result,
]);
return $result;
}
private function redactUrl(string $url): string {
if ($this->api_key) {
$url = str_replace($this->api_key, '[redacted]', $url);
}
return $url;
}
private function redactDebugData($value) {
if (is_array($value)) {
$out = [];
foreach ($value as $key => $item) {
$keyString = strtolower((string)$key);
if (preg_match('/(api[_-]?key|password|pass|token|secret|credential|dkim)/', $keyString)) {
$out[$key] = '[redacted]';
} else {
$out[$key] = $this->redactDebugData($item);
}
}
return $out;
}
if (is_string($value)) {
if ($this->api_key && strpos($value, $this->api_key) !== false) {
$value = str_replace($this->api_key, '[redacted]', $value);
}
return $this->truncateDebugString($value);
}
return $value;
}
private function truncateDebugString(string $value): string {
return strlen($value) > 4000 ? substr($value, 0, 4000) . '… [truncated]' : $value;
}
private function curlResolveEntry(string $url): string {
$ip = trim((string) $this->api_resolve_ip);
if ($ip === '' || !filter_var($ip, FILTER_VALIDATE_IP)) return '';
$host = parse_url($url, PHP_URL_HOST);
if (!$host) return '';
$port = parse_url($url, PHP_URL_PORT);
if (!$port) {
$scheme = strtolower((string) parse_url($url, PHP_URL_SCHEME));
$port = $scheme === 'http' ? 80 : 443;
}
return "{$host}:{$port}:{$ip}";
}
// -----------------------------------------------------------------------
// Module config
// -----------------------------------------------------------------------
public static function getModuleConfigInputfields(array $data): InputfieldWrapper {
$modules = wire('modules');
$defaults = self::getDefaultConfig();
foreach ($defaults as $k => $v) {
if (!isset($data[$k])) $data[$k] = $v;
}
$wrap = new InputfieldWrapper();
$configured = !empty($data['api_url']) && !empty($data['api_key']);
$panelUrl = trim((string)$data['api_url']);
$panelLink = $panelUrl
? '<a href="' . htmlspecialchars(rtrim($panelUrl, '/') . '/index.php?page=admin_api') . '" target="_blank" rel="noopener">Open KeyHelp API settings</a>'
: '<span class="uk-text-muted">Add a panel URL to enable the KeyHelp API shortcut.</span>';
$intro = $modules->get('InputfieldMarkup');
$intro->label = '';
$intro->value = '
<style>
.KeyHelpConfigIntro { margin: 0 0 18px; }
.KeyHelpConfigIntro__grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; }
.KeyHelpConfigIntro__item { border: 1px solid var(--pw-border-color, #d9d9d9); background: var(--pw-blocks-background, #fff); padding: 14px 16px; }
.KeyHelpConfigIntro__label { color: var(--pw-muted-color, #777); font-size: 12px; text-transform: uppercase; letter-spacing: .04em; margin-bottom: 5px; }
.KeyHelpConfigIntro__value { font-size: 16px; font-weight: 600; }
.KeyHelpConfigIntro__text { margin-top: 10px; color: var(--pw-muted-color, #777); max-width: 780px; }
@media (max-width: 900px) { .KeyHelpConfigIntro__grid { grid-template-columns: 1fr; } }
</style>
<div class="KeyHelpConfigIntro">
<div class="KeyHelpConfigIntro__grid">
<div class="KeyHelpConfigIntro__item">
<div class="KeyHelpConfigIntro__label">Connection</div>
<div class="KeyHelpConfigIntro__value">' . ($configured ? 'Configured' : 'Not configured') . '</div>
</div>
<div class="KeyHelpConfigIntro__item">
<div class="KeyHelpConfigIntro__label">Deployment</div>
<div class="KeyHelpConfigIntro__value">' . htmlspecialchars(strtoupper((string)$data['installer_deploy_mode'])) . '</div>
</div>
<div class="KeyHelpConfigIntro__item">
<div class="KeyHelpConfigIntro__label">Tenant mode</div>
<div class="KeyHelpConfigIntro__value">' . htmlspecialchars($data['tenant_mode'] === 'single' ? 'Single client' : 'All clients') . '</div>
</div>
</div>
<p class="KeyHelpConfigIntro__text">Configure the KeyHelp API, ProcessWire installer, remote deployment and tenant restrictions here. ' . $panelLink . '</p>
</div>';
$wrap->add($intro);
// Connection
/** @var InputfieldFieldset $fs */
$fs = $modules->get('InputfieldFieldset');
$fs->label = 'KeyHelp Connection';
$fs->icon = 'plug';
$fs->description = 'Required API connection settings for the German KeyHelp hosting panel.';
$f = $modules->get('InputfieldURL');
$f->attr('name', 'api_url');
$f->attr('value', $data['api_url']);
$f->label = 'Panel URL';
$f->description = 'Base URL of your KeyHelp panel, e.g. https://panel.example.com';
$f->required = true;
$f->columnWidth = 50;
$fs->add($f);
$f = $modules->get('InputfieldText');
$f->attr('name', 'api_key');
$f->attr('value', $data['api_key']);
$f->attr('type', 'password');
$f->label = 'API Key';
$f->required = true;
// Detect the server's outbound IP to show a helpful hint
$serverIp = $_SERVER['SERVER_ADDR'] ?? null;
$isLocalhost = $serverIp && in_array($serverIp, ['127.0.0.1', '::1'], true);
$ipHint = $serverIp
? ($isLocalhost
? "This ProcessWire and KeyHelp appear to be on the same server. Whitelist 127.0.0.1 in KeyHelp → Settings → Configuration → API → Allowed IPs."
: "This ProcessWire server IP is " . htmlspecialchars($serverIp) . ". If KeyHelp is on a different server, add this IP to KeyHelp → Settings → Configuration → API → Allowed IPs. If on the same server, whitelist 127.0.0.1.")
: "If KeyHelp restricts API access by IP, add this server's outbound IP to KeyHelp → Settings → Configuration → API → Allowed IPs.";
$f->description = "Admin API token from KeyHelp → Settings → Configuration → API → API Keys. " . $ipHint;
$f->notes = "Leave Allowed IPs empty in KeyHelp to allow access from any IP (less secure).";
$f->columnWidth = 50;
$fs->add($f);
$f = $modules->get('InputfieldText');
$f->attr('name', 'api_resolve_ip');
$f->attr('value', $data['api_resolve_ip']);
$f->label = 'API Host IP Override';
$f->description = 'Optional. Use only when the local server cannot resolve the KeyHelp hostname via system DNS. Example: 78.46.211.133';
$f->notes = 'When set, cURL connects to this IP while keeping the configured panel hostname for HTTPS and Host headers.';
$f->columnWidth = 50;
$fs->add($f);
$wrap->add($fs);
// Interface and diagnostics
$fs2 = $modules->get('InputfieldFieldset');
$fs2->label = 'Interface and Diagnostics';
$fs2->icon = 'cog';
$fs2->description = 'Control admin language, API caching, SSL verification and debug logging.';
$f = $modules->get('InputfieldInteger');
$f->attr('name', 'cache_time');
$f->attr('value', (int) $data['cache_time']);
$f->label = 'Cache TTL (seconds)';
$f->description = 'How long to cache API GET responses. 0 = disabled.';
$f->min = 0;
$f->columnWidth = 33;
$fs2->add($f);
$f = $modules->get('InputfieldCheckbox');
$f->attr('name', 'verify_ssl');
$f->attr('value', 1);
$f->label = 'Verify SSL Certificate';
$f->description = 'Uncheck only for self-signed certificates on dev servers.';
if (!empty($data['verify_ssl'])) $f->attr('checked', 'checked');
$f->columnWidth = 33;
$fs2->add($f);
$f = $modules->get('InputfieldSelect');
$f->attr('name', 'ui_language');
$f->attr('value', $data['ui_language'] ?? 'auto');
$f->label = __('Interface language', __FILE__);
$f->description = __('Auto follows the current ProcessWire user language when LanguageSupport is installed.', __FILE__);
$f->addOption('auto', __('Auto', __FILE__));
$f->addOption('en', __('English', __FILE__));
$f->addOption('de', __('Deutsch', __FILE__));
$f->columnWidth = 34;
$fs2->add($f);
$f = $modules->get('InputfieldCheckbox');
$f->attr('name', 'debug_mode');
$f->attr('value', 1);
$f->label = __('Debug mode', __FILE__);
$f->description = __('Write sanitized API requests, payloads, responses, cache hits and timings to the ProcessWire log keyhelp-debug.', __FILE__);
$f->notes = __('Sensitive values such as API keys, passwords, tokens, secrets and DKIM records are redacted automatically. Disable this on production after debugging.', __FILE__);
if (!empty($data['debug_mode'])) $f->attr('checked', 'checked');
$f->columnWidth = 100;
$fs2->add($f);
$wrap->add($fs2);
// Installer
$fsInstaller = $modules->get('InputfieldFieldset');
$fsInstaller->label = __('ProcessWire Installer', __FILE__);
$fsInstaller->icon = 'download';
$fsInstaller->description = __('Settings used when installing ProcessWire on KeyHelp domains.', __FILE__);
$f = $modules->get('InputfieldText');
$f->attr('name', 'document_root_pattern');
$f->attr('value', $data['document_root_pattern'] ?? '/home/users/{username}/www/{domain}');
$f->label = __('Document root pattern', __FILE__);
$f->description = __('Local or mounted absolute path used by the ProcessWire installer when KeyHelp API does not return a document root. This must be visible to the ProcessWire/PHP server, not only inside the KeyHelp panel. Available placeholders: {username}, {domain}, {domain_utf8}.', __FILE__);
$f->columnWidth = 66;
$fsInstaller->add($f);
$f = $modules->get('InputfieldSelect');
$f->attr('name', 'installer_deploy_mode');
$f->attr('value', $data['installer_deploy_mode'] ?? 'auto');
$f->label = __('Installer deployment mode', __FILE__);
$f->description = __('Auto uses the local filesystem when the document root is on this ProcessWire server and SSH when KeyHelp is on another host.', __FILE__);
$f->addOption('auto', __('Auto', __FILE__));
$f->addOption('local', __('Local filesystem', __FILE__));
$f->addOption('ssh', __('SSH remote server', __FILE__));
$f->columnWidth = 34;
$fsInstaller->add($f);
$wrap->add($fsInstaller);
// SSH deployment
$fsSsh = $modules->get('InputfieldFieldset');
$fsSsh->label = __('SSH Remote Deployment', __FILE__);
$fsSsh->icon = 'terminal';
$fsSsh->collapsed = Inputfield::collapsedYes;
$fsSsh->description = __('Use these settings when the KeyHelp domain document root is on a remote server or not mounted on the ProcessWire host.', __FILE__);
$f = $modules->get('InputfieldText');
$f->attr('name', 'installer_ssh_host');
$f->attr('value', $data['installer_ssh_host'] ?? '');
$f->label = __('SSH host', __FILE__);
$f->description = __('Optional. Defaults to the KeyHelp API hostname. Available placeholders: {keyhelp_host}, {domain}, {username}.', __FILE__);
$f->columnWidth = 50;
$fsSsh->add($f);
$f = $modules->get('InputfieldInteger');
$f->attr('name', 'installer_ssh_port');
$f->attr('value', (int)($data['installer_ssh_port'] ?? 22));
$f->label = __('SSH port', __FILE__);
$f->min = 1;
$f->columnWidth = 25;
$fsSsh->add($f);
$f = $modules->get('InputfieldText');
$f->attr('name', 'installer_ssh_user');
$f->attr('value', $data['installer_ssh_user'] ?? '{username}');
$f->label = __('SSH user', __FILE__);
$f->description = __('Available placeholders: {username}, {domain}, {keyhelp_host}. Leave as {username} for typical KeyHelp client SSH users.', __FILE__);
$f->columnWidth = 25;
$fsSsh->add($f);
$f = $modules->get('InputfieldText');
$f->attr('name', 'installer_ssh_key_path');
$f->attr('value', $data['installer_ssh_key_path'] ?? '');
$f->label = __('SSH private key path', __FILE__);
$f->description = __('Optional. If empty, SSH uses the default key/agent of the PHP server user.', __FILE__);
$f->columnWidth = 50;
$fsSsh->add($f);
$f = $modules->get('InputfieldText');
$f->attr('name', 'installer_ssh_password');
$f->attr('type', 'password');
$f->attr('value', $data['installer_ssh_password'] ?? '');
$f->label = __('SSH password', __FILE__);
$f->description = __('Optional. Used only when no private key is configured. For production, prefer SSH keys.', __FILE__);
$f->columnWidth = 25;
$fsSsh->add($f);
$f = $modules->get('InputfieldText');
$f->attr('name', 'installer_ssh_php');
$f->attr('value', $data['installer_ssh_php'] ?? 'php');
$f->label = __('Remote PHP binary', __FILE__);
$f->description = __('Command used on the remote server to run ProcessWire installer, for example php or /usr/bin/php8.3.', __FILE__);
$f->columnWidth = 25;
$fsSsh->add($f);
$wrap->add($fsSsh);
// Tenant mode
$fs3 = $modules->get('InputfieldFieldset');
$fs3->label = 'Tenant Mode';
$fs3->icon = 'user-circle';
$fs3->collapsed = Inputfield::collapsedYes;
$fs3->description = 'Single-tenant restricts the module to one KeyHelp client. Use this when a PW site serves a single customer who manages only their own resources.';
$f = $modules->get('InputfieldSelect');
$f->attr('name', 'tenant_mode');
$f->attr('value', $data['tenant_mode'] ?? 'multi');
$f->label = 'Mode';
$f->addOption('multi', 'Multi-tenant — show all clients and resources (default admin use)');
$f->addOption('single', 'Single-tenant — restrict to one client');
$f->columnWidth = 50;
$fs3->add($f);
$f = $modules->get('InputfieldInteger');
$f->attr('name', 'tenant_client_id');
$f->attr('value', (int)($data['tenant_client_id'] ?? 0));
$f->label = 'Client ID';
$f->description = 'KeyHelp client ID to lock to. Find it in KeyHelp → Clients → client detail URL (?id=X). Only used in single-tenant mode.';
$f->showIf = 'tenant_mode=single';
$f->min = 0;
$f->columnWidth = 50;
$fs3->add($f);
$wrap->add($fs3);
return $wrap;
}
}