Repository navigation
Expand file tree
/
Copy pathPluginTcadmin3.php
More file actions
891 lines (763 loc) · 32.7 KB
/
Copy pathPluginTcadmin3.php
File metadata and controls
891 lines (763 loc) · 32.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
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
<?php
use Composer\CaBundle\CaBundle;
require_once 'modules/admin/models/ServerPlugin.php';
/**
* TCAdmin 3 server plugin
*
* Uses the TCAdmin 3 REST API (https://<panel>/api/) with an API key. Services
* are linked to Clientexec packages through TCAdmin's billingId: the package id
* for the game service and the client id for the TCAdmin user.
*/
class PluginTcadmin3 extends ServerPlugin
{
public $features = [
'packageName' => false,
'testConnection' => true,
'showNameservers' => false,
'directlink' => true,
'upgrades' => true
];
private const USERNAME_MAX_LENGTH = 15;
private const USERNAME_MAX_ATTEMPTS = 50;
private const SEARCH_PAGE_SIZE = 500;
private const BYTES_PER_MB = 1048576;
private const LOCATION_FIELDS = [
'datacenter' => 'datacenterId',
'region' => 'regionId',
'server' => 'serverId',
'virtualserver' => 'virtualServerId'
];
private const MASKED_FIELDS = ['password', 'newPassword', 'confirmNewPassword', 'privatepassword', 'RconPassword'];
public function getVariables(): array
{
$variables = [
'Name' => [
'type' => 'hidden',
'description' => 'Used by CE to show plugin',
'value' => 'TCAdmin 3'
],
'Description' => [
'type' => 'hidden',
'description' => 'Description viewable by admin in server settings',
'value' => 'TCAdmin 3 game server integration'
],
'API Key' => [
'type' => 'password',
'description' => lang('API key from Account > API Keys in TCAdmin. The key must belong to an Admin or SubAdmin user.'),
'value' => '',
'encryptable' => true
],
'Port' => [
'type' => 'text',
'description' => lang('TCAdmin panel HTTPS port. Leave blank to use 31001.'),
'value' => '31001'
],
'Verify SSL Certificate' => [
'type' => 'yesno',
'description' => lang('Verify the panel SSL certificate. Only disable this for panels using a self-signed certificate.'),
'value' => '1'
],
'Location Custom Field' => [
'type' => 'text',
'description' => lang('Optional. Name of the package custom field that holds the TCAdmin location ID chosen by the client. Overrides the package Location ID.'),
'value' => ''
],
'Server Name Custom Field' => [
'type' => 'text',
'description' => lang('Optional. Name of the package custom field that holds the game server name.'),
'value' => ''
],
'RCON Password Custom Field' => [
'type' => 'text',
'description' => lang('Optional. Name of the package custom field that holds the game server RCON password.'),
'value' => ''
],
'Private Password Custom Field' => [
'type' => 'text',
'description' => lang('Optional. Name of the package custom field that holds the game server private (join) password.'),
'value' => ''
],
'Actions' => [
'type' => 'hidden',
'description' => 'Current actions that are active for this plugin per server',
'value' => 'Create,Delete,Suspend,UnSuspend'
],
'Registered Actions For Customer' => [
'type' => 'hidden',
'description' => 'Current actions that are active for this plugin per server for customers',
'value' => ''
],
'package_addons' => [
'type' => 'hidden',
'description' => 'Supported signup addons variables',
'value' => []
],
'package_vars' => [
'type' => 'hidden',
'description' => 'Whether package settings are set',
'value' => '1'
],
'package_vars_values' => [
'type' => 'hidden',
'description' => lang('Package Settings'),
'value' => [
'game_id' => [
'type' => 'dropdown',
'multiple' => false,
'getValues' => 'getGameValues',
'label' => lang('Game'),
'description' => lang('The TCAdmin game to install.'),
'value' => ''
],
'slots' => [
'type' => 'text',
'label' => lang('Slots'),
'description' => lang('Number of player slots. Leave blank to use the TCAdmin game default.'),
'value' => ''
],
'memory_limit' => [
'type' => 'text',
'label' => lang('Memory Limit (MB)'),
'description' => lang('Memory limit in MB. Leave blank to use the TCAdmin default.'),
'value' => ''
],
'disk_space' => [
'type' => 'text',
'label' => lang('Disk Space (MB)'),
'description' => lang('Disk space limit in MB. Leave blank to use the TCAdmin default.'),
'value' => ''
],
'cpu_limit' => [
'type' => 'text',
'label' => lang('CPU Limit (%)'),
'description' => lang('CPU limit as a percentage, where 100 is one CPU thread. Leave blank to use the TCAdmin default.'),
'value' => ''
],
'location_type' => [
'type' => 'dropdown',
'multiple' => false,
'getValues' => 'getLocationTypeValues',
'label' => lang('Location Type'),
'description' => lang('What the Location ID refers to.'),
'value' => 'datacenter'
],
'location_id' => [
'type' => 'text',
'label' => lang('Location ID'),
'description' => lang('ID of the TCAdmin datacenter, region, server or virtual server to create the game server on. Required unless the Location Custom Field provides it.'),
'value' => ''
]
]
]
];
return $variables;
}
public function doCreate($args): string
{
$userPackage = new UserPackage($args['userPackageId']);
$args = $this->buildParams($userPackage);
$this->create($args);
return 'Package has been created.';
}
public function doDelete($args): string
{
$userPackage = new UserPackage($args['userPackageId']);
$args = $this->buildParams($userPackage);
$this->delete($args);
return 'Package has been deleted.';
}
public function doUpdate($args): string
{
$userPackage = new UserPackage($args['userPackageId']);
$args = $this->buildParams($userPackage, $args);
$this->update($args);
return 'Package has been updated.';
}
public function doSuspend($args): string
{
$userPackage = new UserPackage($args['userPackageId']);
$args = $this->buildParams($userPackage);
$this->suspend($args);
return 'Package has been suspended.';
}
public function doUnSuspend($args): string
{
$userPackage = new UserPackage($args['userPackageId']);
$args = $this->buildParams($userPackage);
$this->unsuspend($args);
return 'Package has been unsuspended.';
}
public function create($args): void
{
$userPackage = new UserPackage($args['package']['id']);
if ($this->findService($args) !== null) {
throw new CE_Exception($this->user->lang('A TCAdmin service already exists for this package.'));
}
$data = $this->buildServiceParams($args, $userPackage);
if (empty(array_intersect_key($data, array_flip(self::LOCATION_FIELDS)))) {
throw new CE_Exception($this->user->lang('No TCAdmin location is set for this package. Set the Location ID in the package settings.'));
}
$data['ownerId'] = $this->findOrCreateUser($args, $userPackage);
$this->request($args, 'POST', 'GameService/CreateGameService', [], $data);
}
public function delete($args): void
{
if ($this->findService($args) === null) {
CE_Lib::log(4, 'TCAdmin 3: no service found for package ' . $args['package']['id'] . ', treating as already terminated');
return;
}
// Waits until TCAdmin has deleted the service
$this->request($args, 'POST', 'Billing/Terminate', ['billingId' => (string) $args['package']['id']]);
$this->deleteUserIfEmpty($args);
}
public function suspend($args): void
{
$this->request($args, 'POST', 'Billing/Suspend', ['billingId' => (string) $args['package']['id']]);
}
public function unsuspend($args): void
{
$this->request($args, 'POST', 'Billing/Unsuspend', ['billingId' => (string) $args['package']['id']]);
}
public function update($args): void
{
$unsupported = [];
foreach ($args['changes'] as $key => $value) {
switch ($key) {
case 'password':
$service = $this->getService($args);
$this->request($args, 'POST', 'User/' . (int) $service['ownerId'] . '/ChangePassword', [], [
'newPassword' => (string) $value,
'confirmNewPassword' => (string) $value
]);
break;
case 'package':
$this->changePackage($args);
break;
case 'username':
$unsupported[] = $this->user->lang('TCAdmin does not allow changing the username of an account.');
break;
}
}
if (!empty($unsupported)) {
throw new CE_Exception(implode("\n", $unsupported));
}
}
public function getAvailableActions($userPackage): array
{
$actions = parent::getAvailableActions($userPackage);
$args = $this->buildParams($userPackage);
try {
$service = $this->findService($args);
} catch (CE_Exception $e) {
CE_Lib::log(4, 'TCAdmin 3: unable to look up the service for package ' . $userPackage->getId() . ': ' . $e->getMessage());
return $actions;
}
if ($service === null) {
return ['Create'];
}
// The service exists on TCAdmin, so base the actions on its TCAdmin status, never offering Create
$billingStatus = mb_strtolower((string) ($service['billingStatus'] ?? ''));
if ($billingStatus === 'suspended') {
return ['UnSuspend', 'Delete'];
}
if ($billingStatus === 'active') {
return ['Suspend', 'Delete'];
}
if (in_array('Create', $actions, true)) {
return ['Suspend', 'UnSuspend', 'Delete'];
}
return $actions;
}
public function testConnection($args): void
{
CE_Lib::log(4, 'Testing connection to TCAdmin 3');
$this->request($args, 'GET', 'Game/Search', ['Page' => 1, 'PageSize' => 1]);
}
public function getDirectLink($userPackage, $getRealLink = true, $fromAdmin = false, $isReseller = false): array
{
$linkText = $this->user->lang('Login to TCAdmin');
if ($fromAdmin) {
return [
'cmd' => 'panellogin',
'label' => $linkText
];
}
if (!$getRealLink) {
$link = 'index.php?fuse=clients&controller=products&action=openpackagedirectlink&packageId=' . $userPackage->getId() . '&sessionHash=' . CE_Lib::getSessionHash();
return [
'fa' => 'fa fa-user fa-fw',
'link' => $link,
'text' => $linkText,
'form' => ''
];
}
// SSO tokens are short-lived and single use, so only request one when the link is opened
$args = $this->buildParams($userPackage);
$payload = ['billingId' => (string) $args['customer']['id']];
$returnUrl = $this->getServiceManagerPath($args);
if ($returnUrl !== null) {
$payload['returnUrl'] = $returnUrl;
}
$response = $this->request($args, 'POST', 'Sso/Token', [], $payload);
if (empty($response['token'])) {
throw new CE_Exception($this->user->lang('TCAdmin did not return a login token.'));
}
return [
'fa' => 'fa fa-user fa-fw',
'link' => $this->getPanelUrl($args) . '/Auth/Sso?token=' . urlencode((string) $response['token']),
'text' => $linkText,
'form' => ''
];
}
public function dopanellogin($args): string
{
$userPackage = new UserPackage($args['userPackageId']);
$response = $this->getDirectLink($userPackage);
return $response['link'];
}
/**
* Games for the package Game dropdown
*
* @param int $serverId Server id
*
* @return array<string, string> Game names keyed by TCAdmin game id
*/
public function getGameValues($serverId): array
{
$values = ['' => lang('-- Select Game --')];
try {
$server = new Server($serverId);
$args = ['server' => ['variables' => $server->getAllServerPluginVariables($this->user, 'tcadmin3')]];
$games = [];
foreach ($this->searchAll($args, 'Game/Search') as $game) {
// Game/Search returns the game id as blueprintId
$gameId = $game['gameId'] ?? $game['blueprintId'] ?? null;
if ($gameId === null) {
continue;
}
$name = (string) ($game['name'] ?? $gameId);
if (!empty($game['operatingSystem'])) {
$name .= ' (' . $game['operatingSystem'] . ')';
}
$games[(string) $gameId] = $name;
}
asort($games, SORT_NATURAL | SORT_FLAG_CASE);
$values += $games;
} catch (Exception $e) {
// Don't break the package editor when the panel can't be reached
CE_Lib::log(4, 'TCAdmin 3: unable to load games: ' . $e->getMessage());
}
return $values;
}
/**
* Options for the package Location Type dropdown
*
* @param int $serverId Server id
*
* @return array<string, string>
*/
public function getLocationTypeValues($serverId): array
{
return [
'datacenter' => lang('Datacenter'),
'region' => lang('Region'),
'server' => lang('Server'),
'virtualserver' => lang('Virtual Server')
];
}
private function changePackage(array $args): void
{
$userPackage = new UserPackage($args['package']['id']);
$service = $this->getService($args);
$serviceId = (int) $service['serviceId'];
$current = $this->request($args, 'GET', 'GameService/' . $serviceId);
$data = array_merge($current, $this->buildServiceParams($args, $userPackage));
unset($data['startAfterCreation']);
$response = $this->request($args, 'PUT', 'GameService/' . $serviceId . '/UpdateGameService', [], $data);
if (!empty($response['scriptError']) && is_string($response['scriptError'])) {
throw new CE_Exception($this->user->lang('TCAdmin updated the service, but a script failed: %s', $response['scriptError']));
}
}
/**
* Find the TCAdmin user for the client, or create one
*
* The TCAdmin username is saved to the package's User Name field.
*
* @return int TCAdmin user id
*/
private function findOrCreateUser(array $args, UserPackage $userPackage): int
{
$response = $this->request($args, 'GET', 'User/Search', ['Filter' => 'billingId=' . (int) $args['customer']['id']]);
$count = (int) ($response['count'] ?? 0);
if ($count > 1) {
throw new CE_Exception($this->user->lang('More than one TCAdmin user is linked to client #%s.', $args['customer']['id']));
}
if ($count === 1 && !empty($response['data'][0]['userId'])) {
$user = $response['data'][0];
if (!empty($user['username'])) {
$userPackage->setCustomField('User Name', (string) $user['username']);
}
return (int) $user['userId'];
}
$password = (string) $args['package']['password'];
if ($password === '') {
$password = CE_Lib::generatePassword();
$userPackage->setPassword($password);
}
$username = $this->getAvailableUsername($args, $this->getBaseUsername($args));
$user = $this->request($args, 'POST', 'User', [], [
'billingId' => (string) $args['customer']['id'],
'email' => (string) $args['customer']['email'],
'firstName' => (string) $args['customer']['first_name'],
'lastName' => (string) $args['customer']['last_name'],
'username' => $username,
'password' => $password,
'userStatus' => 'Active',
'userType' => 'User'
]);
if (empty($user['userId'])) {
throw new CE_Exception($this->user->lang('TCAdmin created the user but did not return a user id.'));
}
$userId = (int) $user['userId'];
$this->request($args, 'PUT', 'User/' . $userId . '/SetRoleType', ['roleType' => 'User']);
$userPackage->setCustomField('User Name', (string) ($user['username'] ?? $username));
return $userId;
}
private function getBaseUsername(array $args): string
{
$username = trim((string) $args['package']['username']);
if ($username === '') {
$username = $args['customer']['first_name'] . mb_substr((string) $args['customer']['last_name'], 0, 1);
}
$username = preg_replace('/[^a-z0-9_-]/', '', mb_strtolower($username));
if ($username === '') {
$username = CE_Lib::generateUsername();
}
return mb_substr($username, 0, self::USERNAME_MAX_LENGTH);
}
private function getAvailableUsername(array $args, string $base): string
{
for ($i = 0; $i < self::USERNAME_MAX_ATTEMPTS; $i++) {
$suffix = $i === 0 ? '' : (string) $i;
$candidate = mb_substr($base, 0, self::USERNAME_MAX_LENGTH - mb_strlen($suffix)) . $suffix;
$response = $this->request($args, 'GET', 'User/Search', ['Filter' => 'username=' . $candidate]);
if ((int) ($response['count'] ?? 0) === 0) {
return $candidate;
}
}
throw new CE_Exception($this->user->lang('Unable to find an available TCAdmin username for %s.', $base));
}
/**
* After a terminate, remove the client's TCAdmin user when it owns nothing else.
* Failures are logged and ignored, since the service itself is already gone.
*/
private function deleteUserIfEmpty(array $args): void
{
try {
$response = $this->request($args, 'GET', 'User/Search', ['Filter' => 'billingId=' . (int) $args['customer']['id']]);
if ((int) ($response['count'] ?? 0) !== 1 || empty($response['data'][0]['userId'])) {
return;
}
$ownerId = (int) $response['data'][0]['userId'];
foreach (['GameService', 'DockerService', 'Server', 'VirtualServer'] as $type) {
$owned = $this->request($args, 'GET', $type . '/Search', ['Filter' => 'ownerId=' . $ownerId]);
if ((int) ($owned['count'] ?? 0) > 0) {
return;
}
}
$this->request($args, 'DELETE', 'User/' . $ownerId);
} catch (CE_Exception $e) {
CE_Lib::log(4, 'TCAdmin 3: unable to remove the empty user for client ' . $args['customer']['id'] . ': ' . $e->getMessage());
}
}
/**
* Build the CreateGameService / UpdateGameService fields from the package
*/
private function buildServiceParams(array $args, UserPackage $userPackage): array
{
$gameId = (int) $this->getOption($args, 'game_id');
if ($gameId <= 0) {
throw new CE_Exception($this->user->lang('No TCAdmin game is selected for this package.'));
}
$data = ['gameId' => $gameId];
$slots = trim((string) $this->getOption($args, 'slots'));
if ($slots !== '') {
$data['slots'] = (int) $slots;
}
// TCAdmin takes memory and disk in bytes and CPU as a percentage
$memoryLimit = $this->getLimit($args, 'memory_limit', lang('Memory Limit (MB)'));
if ($memoryLimit !== null) {
$data['memoryLimit'] = $memoryLimit * self::BYTES_PER_MB;
}
$diskSpace = $this->getLimit($args, 'disk_space', lang('Disk Space (MB)'));
if ($diskSpace !== null) {
$data['diskSpace'] = $diskSpace * self::BYTES_PER_MB;
}
$cpuLimit = $this->getLimit($args, 'cpu_limit', lang('CPU Limit (%)'));
if ($cpuLimit !== null) {
$data['cpuLimit'] = $cpuLimit;
}
$locationId = $this->parseLocationId($this->getCustomFieldValue($args, $userPackage, 'Location_Custom_Field'));
if ($locationId === null) {
$locationId = $this->parseLocationId($this->getOption($args, 'location_id'));
}
if ($locationId !== null) {
$locationType = str_replace(' ', '', mb_strtolower((string) $this->getOption($args, 'location_type')));
$data[self::LOCATION_FIELDS[$locationType] ?? 'datacenterId'] = $locationId;
}
$name = $this->getCustomFieldValue($args, $userPackage, 'Server_Name_Custom_Field');
if ($name !== '') {
$data['name'] = $name;
}
$privatePassword = $this->getCustomFieldValue($args, $userPackage, 'Private_Password_Custom_Field');
if ($privatePassword !== '') {
$data['privatepassword'] = $privatePassword;
}
$rconPassword = $this->getCustomFieldValue($args, $userPackage, 'RCON_Password_Custom_Field');
if ($rconPassword !== '') {
$data['variables'] = ['RconPassword' => $rconPassword];
}
$data['billingId'] = (string) $args['package']['id'];
$data['startAfterCreation'] = true;
return $data;
}
/**
* Get a package setting, letting an addon named CUSTOM_<key> override it
*/
private function getOption(array $args, string $key): string
{
$addonValue = $args['package']['addons']['CUSTOM_' . $key] ?? '';
if ($addonValue !== '' && $addonValue !== null) {
return (string) $addonValue;
}
return (string) ($args['package']['variables'][$key] ?? '');
}
/**
* Get a resource limit setting as a whole number
*
* @param string $label Setting label, for the error message
*
* @return int|null The limit, or null when blank so TCAdmin uses its default
*/
private function getLimit(array $args, string $key, string $label): ?int
{
$value = trim($this->getOption($args, $key));
if ($value === '') {
return null;
}
if (!ctype_digit($value) || (int) $value <= 0) {
throw new CE_Exception($this->user->lang('%s must be a whole number greater than 0.', $label));
}
return (int) $value;
}
/**
* Get the value of the package custom field named in a server setting
*
* @param string $setting Server setting name, such as Location_Custom_Field
*/
private function getCustomFieldValue(array $args, UserPackage $userPackage, string $setting): string
{
$fieldName = trim((string) ($args['server']['variables']['plugin_tcadmin3_' . $setting] ?? ''));
if ($fieldName === '') {
return '';
}
return trim((string) $userPackage->getCustomField($fieldName, CUSTOM_FIELDS_FOR_PACKAGE));
}
/**
* Accept a plain id, or a dropdown value such as "West (12)"
*/
private function parseLocationId(?string $value): ?int
{
$value = trim((string) $value);
if ($value === '') {
return null;
}
if (ctype_digit($value)) {
return (int) $value > 0 ? (int) $value : null;
}
if (preg_match('/\((\d+)\)\s*$/u', $value, $matches)) {
return (int) $matches[1];
}
return null;
}
private function findService(array $args): ?array
{
$response = $this->request($args, 'GET', 'Service/Search', ['Filter' => 'billingId=' . (int) $args['package']['id']]);
$count = (int) ($response['count'] ?? 0);
if ($count === 0) {
return null;
}
if ($count > 1) {
throw new CE_Exception($this->user->lang('More than one TCAdmin service is linked to package #%s.', $args['package']['id']));
}
return $response['data'][0] ?? null;
}
private function getService(array $args): array
{
$service = $this->findService($args);
if ($service === null || empty($service['serviceId'])) {
throw new CE_Exception($this->user->lang('Unable to find the service for package #%s on TCAdmin.', $args['package']['id']));
}
return $service;
}
/**
* Path of the service's page in TCAdmin, so SSO lands on the game server
*/
private function getServiceManagerPath(array $args): ?string
{
try {
$service = $this->findService($args);
if ($service === null || empty($service['serviceId']) || empty($service['categoryId'])) {
return null;
}
$category = $this->request($args, 'GET', 'ServiceCategory/' . (int) $service['categoryId']);
if (empty($category['slug'])) {
return null;
}
return '/Managers/' . rawurlencode((string) $category['slug']) . '/' . (int) $service['serviceId'];
} catch (CE_Exception $e) {
CE_Lib::log(4, 'TCAdmin 3: unable to find the service page for SSO: ' . $e->getMessage());
return null;
}
}
/**
* Fetch every page of a search endpoint
*/
private function searchAll(array $args, string $endpoint): array
{
$items = [];
$page = 1;
do {
$response = $this->request($args, 'GET', $endpoint, ['Page' => $page, 'PageSize' => self::SEARCH_PAGE_SIZE]);
$data = is_array($response['data'] ?? null) ? $response['data'] : [];
$items = array_merge($items, $data);
$total = (int) ($response['count'] ?? 0);
$page++;
} while (!empty($data) && count($items) < $total);
return $items;
}
private function getPanelUrl(array $args): string
{
$host = trim((string) ($args['server']['variables']['ServerHostName'] ?? ''));
$host = preg_replace('#^https?://#iu', '', $host);
$host = preg_replace('#/.*$#u', '', $host);
if ($host === '') {
throw new CE_Exception($this->user->lang('The server hostname is not set.'));
}
$port = trim((string) ($args['server']['variables']['plugin_tcadmin3_Port'] ?? ''));
if (!ctype_digit($port)) {
$port = '31001';
}
if ($port !== '443' && !preg_match('/:\d+$/u', $host)) {
$host .= ':' . $port;
}
return 'https://' . $host;
}
/**
* Send a request to the TCAdmin 3 API
*
* @param array $query Query string parameters
* @param array|null $body JSON body, or null to send none
*
* @return array Decoded JSON response ([] when the response has no body)
*/
private function request(array $args, string $method, string $endpoint, array $query = [], ?array $body = null): array
{
$url = $this->getPanelUrl($args) . '/api/' . $endpoint;
if (!empty($query)) {
$url .= '?' . http_build_query($query);
}
$headers = [
'Accept: application/json',
'Content-Type: application/json',
'Authorization: ApiKey ' . ($args['server']['variables']['plugin_tcadmin3_API_Key'] ?? '')
];
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_CONNECTTIMEOUT => 15,
// Terminate waits for TCAdmin to finish deleting the service
CURLOPT_TIMEOUT => 180
]);
if ($body !== null) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
} elseif (in_array($method, ['POST', 'PUT'], true)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, '');
}
if (($args['server']['variables']['plugin_tcadmin3_Verify_SSL_Certificate'] ?? '1') == '1') {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_CAINFO, CaBundle::getSystemCaRootBundlePath());
} else {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
}
CE_Lib::log(4, 'TCAdmin 3 ' . $method . ' ' . $url . ($body !== null ? ' ' . json_encode($this->maskSecrets($body)) : ''));
$response = curl_exec($ch);
if ($response === false) {
throw new CE_Exception($this->user->lang('Unable to connect to TCAdmin: %s', curl_error($ch)));
}
$status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
CE_Lib::log(4, 'TCAdmin 3 ' . $method . ' /api/' . $endpoint . ' returned HTTP ' . $status);
$decoded = json_decode((string) $response, true);
if ($status >= 200 && $status < 300) {
return is_array($decoded) ? $decoded : [];
}
throw new CE_Exception($this->buildErrorMessage($status, $decoded, (string) $response));
}
private function buildErrorMessage(int $status, mixed $decoded, string $body): string
{
if ($status >= 300 && $status < 400) {
return $this->user->lang('TCAdmin redirected the request (HTTP %s). Check the hostname and port.', $status);
}
if ($status === 401) {
return $this->user->lang('TCAdmin rejected the API key (HTTP 401).');
}
$message = '';
if (is_array($decoded)) {
// TCAdmin's 500 responses carry a generic message at the top level and the cause under errorDetails
if (!empty($decoded['errorDetails']['message']) && is_string($decoded['errorDetails']['message'])) {
$message = $decoded['errorDetails']['message'];
} elseif (!empty($decoded['errors']) && is_array($decoded['errors'])) {
$parts = [];
foreach ($decoded['errors'] as $field => $messages) {
$parts[] = (is_string($field) ? $field . ': ' : '') . implode(' ', array_map('strval', (array) $messages));
}
$message = implode(' | ', $parts);
} else {
foreach (['detail', 'title', 'message', 'error'] as $key) {
if (!empty($decoded[$key]) && is_string($decoded[$key])) {
$message = $decoded[$key];
break;
}
}
}
} elseif (is_string($decoded)) {
$message = $decoded;
} else {
$message = mb_substr(strip_tags($body), 0, 500);
}
$message = trim($message);
if ($message === '') {
return $this->user->lang('TCAdmin returned HTTP %s with no error message.', $status);
}
if ($status === 403) {
return $this->user->lang('The TCAdmin API key does not have permission for this action (HTTP 403): %s', $message);
}
return $this->user->lang('TCAdmin returned HTTP %s: %s', $status, $message);
}
private function maskSecrets(array $data): array
{
foreach ($data as $key => $value) {
if (is_array($value)) {
$data[$key] = $this->maskSecrets($value);
} elseif (in_array($key, self::MASKED_FIELDS, true)) {
$data[$key] = '********';
}
}
return $data;
}
}