-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathConfigController.php
More file actions
2252 lines (1984 loc) · 76.2 KB
/
Copy pathConfigController.php
File metadata and controls
2252 lines (1984 loc) · 76.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Nextcloud - iTop
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Integration Bot
* @copyright Integration Bot 2025
*/
namespace OCA\Itop\Controller;
use OCA\Itop\AppInfo\Application;
use OCA\Itop\Service\ItopAPIService;
use OCA\Itop\Service\CacheService;
use OCP\App\IAppManager;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\DataDisplayResponse;
use OCP\AppFramework\Http\DataResponse;
use OCP\Files\AppData\IAppDataFactory;
use OCP\Files\NotFoundException;
use OCP\Http\Client\IClientService;
use OCP\IConfig;
use OCP\IL10N;
use OCP\IRequest;
use OCP\IURLGenerator;
use OCP\PreConditionNotMetException;
use OCP\Security\ICrypto;
use Psr\Log\LoggerInterface;
class ConfigController extends Controller {
/**
* Request-local cache of parsed iTop class definitions, keyed by iTop base URL.
*
* @var array<string, array<string, array{parent:?string, icon:?string}>>
*/
private array $itopClassDefinitionsCache = [];
public function __construct(
string $appName,
IRequest $request,
private IConfig $config,
private ICrypto $crypto,
private IL10N $l10n,
private ItopAPIService $itopAPIService,
private CacheService $cacheService,
private LoggerInterface $logger,
private IAppManager $appManager,
private IClientService $clientService,
private IAppDataFactory $appDataFactory,
private IURLGenerator $urlGenerator,
private ?string $userId
) {
parent::__construct($appName, $request);
}
/**
* Set user configuration values (Phase 2: Personal Token Validation)
*
* WORKFLOW:
* 1. Receive personal token from user (NOT stored)
* 2. Validate token using :current_contact_id → extracts Person ID directly
* 3. Store ONLY person_id (NOT the token)
* 4. Discard personal token immediately (security enhancement)
*
* WHY DUAL-TOKEN ARCHITECTURE?
* ============================
* Portal users are HARD-BLOCKED from REST API access by iTop core:
* - webservices/rest.php line 103: $bIsAllowedToPortalUsers = false (hardcoded)
* - Even valid personal tokens fail with: {"code":1,"message":"Error: Portal user is not allowed"}
*
* SOLUTION:
* - Personal token: Identity verification ONLY (proves user is authorized)
* - Application token: All subsequent queries (admin-level, bypasses Portal user block)
* - Person ID filtering: Ensures data isolation between users
*
* @NoAdminRequired
*
* @return DataResponse
* @throws PreConditionNotMetException
*/
public function setConfig(): DataResponse {
if ($this->userId === null) {
return new DataResponse([], Http::STATUS_BAD_REQUEST);
}
// Get JSON data from request body
$input = json_decode(file_get_contents('php://input'), true);
if (!is_array($input)) {
return new DataResponse(['message' => $this->l10n->t('Invalid request data')], Http::STATUS_BAD_REQUEST);
}
$this->logger->info('iTop setConfig called for user: ' . $this->userId, ['app' => Application::APP_ID]);
$values = $input;
// Save non-token settings first
$allowedKeys = [
'navigation_enabled',
'notification_enabled',
'search_enabled',
'notify_ticket_status_changed',
'notify_agent_responded',
'notify_ticket_resolved',
'newsroom_mirroring_enabled',
];
foreach ($values as $key => $value) {
if (in_array($key, $allowedKeys)) {
// Boolean values should be '0' or '1'
$boolValue = $value ? '1' : '0';
$this->config->setUserValue($this->userId, Application::APP_ID, $key, $boolValue);
}
}
// Handle disabled CI classes (user preferences)
if (isset($values['disabled_ci_classes']) && is_array($values['disabled_ci_classes'])) {
$disabledClasses = array_values(array_unique($values['disabled_ci_classes']));
// Validate classes
$validDisabled = array_intersect($disabledClasses, Application::SUPPORTED_CI_CLASSES);
if (empty($validDisabled)) {
$this->config->deleteUserValue($this->userId, Application::APP_ID, 'disabled_ci_classes');
} else {
$this->config->setUserValue($this->userId, Application::APP_ID, 'disabled_ci_classes', json_encode($validDisabled));
}
}
// Handle disabled portal notifications (3-state system)
if (isset($values['disabled_portal_notifications'])) {
if ($values['disabled_portal_notifications'] === 'all') {
// Master toggle: disable all portal notifications
$this->config->setUserValue($this->userId, Application::APP_ID, 'disabled_portal_notifications', 'all');
} elseif (is_array($values['disabled_portal_notifications'])) {
$disabledPortal = array_values(array_unique($values['disabled_portal_notifications']));
// Validate against PORTAL_NOTIFICATION_TYPES
$validDisabledPortal = array_intersect($disabledPortal, Application::PORTAL_NOTIFICATION_TYPES);
if (empty($validDisabledPortal)) {
$this->config->deleteUserValue($this->userId, Application::APP_ID, 'disabled_portal_notifications');
} else {
$this->config->setUserValue($this->userId, Application::APP_ID, 'disabled_portal_notifications', json_encode($validDisabledPortal));
}
} else {
// Empty or invalid: clear disabled array (enable all)
$this->config->deleteUserValue($this->userId, Application::APP_ID, 'disabled_portal_notifications');
}
}
// Handle disabled agent notifications (3-state system)
if (isset($values['disabled_agent_notifications'])) {
if ($values['disabled_agent_notifications'] === 'all') {
// Master toggle: disable all agent notifications
$this->config->setUserValue($this->userId, Application::APP_ID, 'disabled_agent_notifications', 'all');
} elseif (is_array($values['disabled_agent_notifications'])) {
$disabledAgent = array_values(array_unique($values['disabled_agent_notifications']));
// Validate against AGENT_NOTIFICATION_TYPES
$validDisabledAgent = array_intersect($disabledAgent, Application::AGENT_NOTIFICATION_TYPES);
if (empty($validDisabledAgent)) {
$this->config->deleteUserValue($this->userId, Application::APP_ID, 'disabled_agent_notifications');
} else {
$this->config->setUserValue($this->userId, Application::APP_ID, 'disabled_agent_notifications', json_encode($validDisabledAgent));
}
} else {
// Empty or invalid: clear disabled array (enable all)
$this->config->deleteUserValue($this->userId, Application::APP_ID, 'disabled_agent_notifications');
}
}
// Handle notification check interval
if (isset($values['notification_check_interval'])) {
$interval = (int)$values['notification_check_interval'];
// Validate range: 5-1440 minutes
if ($interval >= 5 && $interval <= 1440) {
$this->config->setUserValue($this->userId, Application::APP_ID, 'notification_check_interval', (string)$interval);
}
}
// Phase 2: Handle personal token validation
$personalToken = $values['personal_token'] ?? $values['token'] ?? null;
// Handle token deletion
if ($personalToken !== null && $personalToken === '') {
// Remove person_id and user_id
$this->config->deleteUserValue($this->userId, Application::APP_ID, 'person_id');
$this->config->deleteUserValue($this->userId, Application::APP_ID, 'user_id');
// Also clean up any old token storage (Phase 1 leftover)
$this->config->deleteUserValue($this->userId, Application::APP_ID, 'token');
$this->logger->info('iTop: Person ID and User ID removed for user', ['app' => Application::APP_ID]);
return new DataResponse([
'message' => $this->l10n->t('Configuration removed successfully'),
'person_id_configured' => false
]);
}
// If no token provided, just return current status
if ($personalToken === null) {
$hasPersonId = $this->config->getUserValue($this->userId, Application::APP_ID, 'person_id', '') !== '';
return new DataResponse([
'message' => $this->l10n->t('Settings saved successfully'),
'person_id_configured' => $hasPersonId
]);
}
// Phase 2: Validate personal token and extract Person ID using :current_contact_id
$validation = $this->validatePersonalTokenAndExtractPersonId($personalToken);
if (!$validation['success']) {
return new DataResponse([
'message' => $this->l10n->t('Token validation failed'),
'error' => $validation['error'],
'person_id_configured' => false
], Http::STATUS_BAD_REQUEST);
}
// Success! Store Person ID and User ID (NOT the token)
$personId = $validation['person_id'];
$userId = $validation['user_id'];
$this->config->setUserValue($this->userId, Application::APP_ID, 'person_id', $personId);
$this->config->setUserValue($this->userId, Application::APP_ID, 'user_id', $userId);
// Clean up any old token storage (Phase 1 leftover)
$this->config->deleteUserValue($this->userId, Application::APP_ID, 'token');
$this->logger->info('iTop: Person ID ' . $personId . ' and User ID ' . $userId . ' configured for user ' . $this->userId, ['app' => Application::APP_ID]);
// Personal token is now discarded (never stored)
$userInfo = $validation['user_info'];
$userName = trim(($userInfo['first_name'] ?? '') . ' ' . ($userInfo['last_name'] ?? ''));
return new DataResponse([
'message' => $this->l10n->t('Configuration successful! You are now connected.'),
'person_id_configured' => true,
'user_info' => [
'name' => $userName ?: $userInfo['login'],
'email' => $userInfo['email'] ?? '',
'organization' => $userInfo['org_name'] ?? '',
'person_id' => $personId
]
]);
}
/**
* Get current user information from iTop
*
* @NoAdminRequired
*
* @return DataResponse
*/
public function getUserInfo(): DataResponse {
if ($this->userId === null) {
return new DataResponse(['error' => $this->l10n->t('User not authenticated')], Http::STATUS_UNAUTHORIZED);
}
$personId = $this->config->getUserValue($this->userId, Application::APP_ID, 'person_id', '');
if (empty($personId)) {
return new DataResponse(['error' => $this->l10n->t('User not configured')], Http::STATUS_NOT_FOUND);
}
// Fetch person details from iTop using application token
$encryptedAppToken = $this->config->getAppValue(Application::APP_ID, 'application_token', '');
if (empty($encryptedAppToken)) {
return new DataResponse(['error' => $this->l10n->t('Application token not configured')], Http::STATUS_SERVICE_UNAVAILABLE);
}
try {
$applicationToken = $this->crypto->decrypt($encryptedAppToken);
$adminInstanceUrl = $this->config->getAppValue(Application::APP_ID, 'admin_instance_url', '');
if (empty($adminInstanceUrl)) {
return new DataResponse(['error' => $this->l10n->t('Server URL not configured')], Http::STATUS_SERVICE_UNAVAILABLE);
}
$apiUrl = rtrim($adminInstanceUrl, '/') . '/webservices/rest.php?version=1.3';
$postData = [
'json_data' => json_encode([
'operation' => 'core/get',
'class' => 'Person',
'key' => $personId,
'output_fields' => 'id,first_name,name,email,org_id_friendlyname'
])
];
try {
$client = $this->clientService->newClient();
$response = $client->post($apiUrl, [
'body' => http_build_query($postData),
'headers' => [
'Content-Type' => 'application/x-www-form-urlencoded',
'Auth-Token' => $applicationToken,
'User-Agent' => 'Nextcloud-iTop-Integration/1.0'
],
'timeout' => 15,
]);
$result = $response->getBody();
} catch (\Exception $e) {
return new DataResponse(['error' => $this->l10n->t('Connection failed: %s', [$e->getMessage()])], Http::STATUS_SERVICE_UNAVAILABLE);
}
$responseData = json_decode($result, true);
if ($responseData === null || !isset($responseData['code']) || $responseData['code'] !== 0) {
$errorMsg = $responseData['message'] ?? $this->l10n->t('Failed to fetch user information');
return new DataResponse(['error' => $errorMsg], Http::STATUS_BAD_REQUEST);
}
if (!isset($responseData['objects']) || empty($responseData['objects'])) {
return new DataResponse(['error' => $this->l10n->t('Person not found')], Http::STATUS_NOT_FOUND);
}
$personObject = reset($responseData['objects']);
$personFields = $personObject['fields'] ?? [];
$userName = trim(($personFields['first_name'] ?? '') . ' ' . ($personFields['name'] ?? ''));
return new DataResponse([
'name' => $userName ?: $this->l10n->t('Unknown User'),
'email' => $personFields['email'] ?? '',
'organization' => $personFields['org_id_friendlyname'] ?? '',
'person_id' => $personId
]);
} catch (\Exception $e) {
$this->logger->error('Failed to fetch user info: ' . $e->getMessage(), ['app' => Application::APP_ID]);
return new DataResponse(['error' => $this->l10n->t('Failed to fetch user information')], Http::STATUS_INTERNAL_SERVER_ERROR);
}
}
/**
* Get admin configuration values
*
* @return DataResponse
*/
public function getAdminConfig(): DataResponse {
$adminInstanceUrl = $this->config->getAppValue(Application::APP_ID, 'admin_instance_url', '');
$userFacingName = $this->config->getAppValue(Application::APP_ID, 'user_facing_name', 'iTop');
$hasApplicationToken = $this->config->getAppValue(Application::APP_ID, 'application_token', '') !== '';
// Count users with configured tokens
$connectedUsers = $this->getConnectedUsersCount();
// Get cache TTL values (with defaults matching CacheService)
$cacheTtlCiPreview = (int)$this->config->getAppValue(Application::APP_ID, 'cache_ttl_ci_preview', '60');
$cacheTtlTicketInfo = (int)$this->config->getAppValue(Application::APP_ID, 'cache_ttl_ticket_info', '60');
$cacheTtlSearch = (int)$this->config->getAppValue(Application::APP_ID, 'cache_ttl_search', '30');
$cacheTtlPicker = (int)$this->config->getAppValue(Application::APP_ID, 'cache_ttl_picker', '60');
$cacheTtlProfile = (int)$this->config->getAppValue(Application::APP_ID, 'cache_ttl_profile', '1800');
// Get 3-state CI class configuration
$ciClassConfig = Application::getCIClassConfig($this->config);
$adminConfig = [
'admin_instance_url' => $adminInstanceUrl,
'user_facing_name' => $userFacingName,
'has_application_token' => $hasApplicationToken,
'connected_users' => $connectedUsers,
'last_updated' => date('Y-m-d H:i:s'),
'version' => Application::getVersion($this->appManager),
'cache_ttl_ci_preview' => $cacheTtlCiPreview,
'cache_ttl_ticket_info' => $cacheTtlTicketInfo,
'cache_ttl_search' => $cacheTtlSearch,
'cache_ttl_picker' => $cacheTtlPicker,
'cache_ttl_profile' => $cacheTtlProfile,
'ci_class_config' => $ciClassConfig,
'supported_ci_classes' => Application::SUPPORTED_CI_CLASSES,
];
return new DataResponse($adminConfig);
}
/**
* Test application token connection
*
* @param string $token Optional token to test (if not provided, uses saved token)
* @return DataResponse
*/
public function testApplicationToken(string $token = ''): DataResponse {
$adminInstanceUrl = $this->config->getAppValue(Application::APP_ID, 'admin_instance_url', '');
if (empty($adminInstanceUrl)) {
return new DataResponse([
'status' => 'error',
'message' => $this->l10n->t('Server URL not configured')
], Http::STATUS_BAD_REQUEST);
}
// If token not provided, try to get from saved config
if (empty($token)) {
$encryptedToken = $this->config->getAppValue(Application::APP_ID, 'application_token', '');
if (empty($encryptedToken)) {
return new DataResponse([
'status' => 'error',
'message' => $this->l10n->t('Application token not configured')
], Http::STATUS_BAD_REQUEST);
}
try {
// Decrypt the token
$token = $this->crypto->decrypt($encryptedToken);
} catch (\Exception $e) {
return new DataResponse([
'status' => 'error',
'message' => $this->l10n->t('Failed to decrypt saved token')
], Http::STATUS_BAD_REQUEST);
}
}
try {
// Test the token with a simple API call
$apiUrl = rtrim($adminInstanceUrl, '/') . '/webservices/rest.php?version=1.3';
// Use list_operations to validate the token (works for both Application and Personal tokens)
$postData = [
'json_data' => json_encode([
'operation' => 'list_operations'
])
];
try {
$client = $this->clientService->newClient();
$response = $client->post($apiUrl, [
'body' => http_build_query($postData),
'headers' => [
'Content-Type' => 'application/x-www-form-urlencoded',
'Auth-Token' => $token,
'User-Agent' => 'Nextcloud-iTop-Integration/1.0'
],
'timeout' => 15,
]);
$result = $response->getBody();
$this->logger->info('iTop application token test response: ' . $result, ['app' => Application::APP_ID]);
} catch (\Exception $e) {
return new DataResponse([
'status' => 'error',
'message' => $this->l10n->t('Connection failed: %s', [$e->getMessage()])
]);
}
$responseData = json_decode($result, true);
if ($responseData === null) {
return new DataResponse([
'status' => 'error',
'message' => $this->l10n->t('Invalid response from server')
]);
}
// Check response code
if (isset($responseData['code'])) {
if ($responseData['code'] == 0) {
// Success - token is valid
$operationCount = count($responseData['operations'] ?? []);
return new DataResponse([
'status' => 'success',
'message' => $this->l10n->t('Application token is valid and working'),
'details' => [
'api_version' => $responseData['version'] ?? 'Unknown',
'available_operations' => $operationCount,
'token_type' => 'Application Token'
]
]);
} elseif ($responseData['code'] == 1) {
// Unauthorized - provide detailed debugging info
$errorMsg = $responseData['message'] ?? 'Unauthorized';
return new DataResponse([
'status' => 'error',
'message' => $this->l10n->t('Application token authentication failed'),
'details' => [
'error' => $errorMsg,
'hint' => $this->l10n->t('Application tokens in iTop must have "Administrator" + "REST Services User" profiles. Token may be invalid or expired.'),
'token_length' => strlen($token),
'response_code' => $responseData['code']
]
]);
} else {
return new DataResponse([
'status' => 'error',
'message' => $this->l10n->t('API error: %s', [$responseData['message'] ?? $this->l10n->t('Unknown error')]),
'details' => [
'code' => $responseData['code'],
'full_response' => $responseData
]
]);
}
}
return new DataResponse([
'status' => 'error',
'message' => $this->l10n->t('Unexpected response format'),
'details' => [
'response' => $responseData
]
]);
} catch (\Exception $e) {
$this->logger->error('iTop application token test failed: ' . $e->getMessage(), ['app' => Application::APP_ID]);
return new DataResponse([
'status' => 'error',
'message' => $this->l10n->t('Test failed: %s', [$e->getMessage()])
]);
}
}
/**
* Test connection to iTop server
*
* @param string $url Optional URL to test (if not provided, uses saved config)
* @return DataResponse
*/
public function testAdminConnection(string $url = ''): DataResponse {
// Use provided URL or fall back to saved configuration
$testUrl = !empty($url) ? trim($url) : $this->config->getAppValue(Application::APP_ID, 'admin_instance_url', '');
if (empty($testUrl)) {
return new DataResponse(['status' => 'error', 'message' => $this->l10n->t('No server URL provided for testing')], Http::STATUS_BAD_REQUEST);
}
$this->logger->info('iTop testing connection to URL: ' . $testUrl, ['app' => Application::APP_ID]);
// Test iTop API endpoint specifically
try {
// Construct the iTop REST API URL
$apiUrl = rtrim($testUrl, '/') . '/webservices/rest.php?version=1.3';
$this->logger->info('iTop testing API endpoint: ' . $apiUrl, ['app' => Application::APP_ID]);
// Prepare a basic API request (without credentials to test for proper iTop error response)
$postData = [
'json_data' => json_encode([
'operation' => 'core/check_credentials'
])
];
try {
$client = $this->clientService->newClient();
$response = $client->post($apiUrl, [
'body' => http_build_query($postData),
'headers' => [
'Content-Type' => 'application/x-www-form-urlencoded',
'User-Agent' => 'Nextcloud-iTop-Integration/1.0'
],
'timeout' => 15,
]);
$result = $response->getBody();
} catch (\Exception $e) {
return new DataResponse([
'status' => 'error',
'message' => $this->l10n->t('Connection failed: %s', [$e->getMessage()]),
'details' => ['url' => $testUrl, 'api_url' => $apiUrl]
]);
}
// Parse the JSON response
$responseData = json_decode($result, true);
if ($responseData === null) {
return new DataResponse([
'status' => 'error',
'message' => $this->l10n->t('Server did not return valid JSON - not an iTop instance'),
'details' => ['url' => $testUrl, 'response' => substr($result, 0, 200)]
]);
}
$this->logger->info('iTop API response: ' . json_encode($responseData), ['app' => Application::APP_ID]);
// Check for proper iTop response structure
if (isset($responseData['code'])) {
// iTop returns status codes: 0 = OK, 1 = UNAUTHORIZED, 2 = MISSING_VERSION, etc.
if ($responseData['code'] == 1) {
// UNAUTHORIZED - this is expected and proves it's an iTop instance
return new DataResponse([
'status' => 'success',
'message' => $this->l10n->t('iTop instance detected (authentication required)'),
'details' => [
'url' => $testUrl,
'api_url' => $apiUrl,
'itop_code' => $responseData['code'],
'itop_message' => $responseData['message'] ?? 'Unauthorized'
]
]);
} elseif ($responseData['code'] == 0) {
// Successful response (shouldn't happen without credentials, but still valid iTop)
return new DataResponse([
'status' => 'success',
'message' => $this->l10n->t('iTop instance detected and accessible'),
'details' => [
'url' => $testUrl,
'api_url' => $apiUrl,
'itop_code' => $responseData['code']
]
]);
} else {
// Other iTop error codes
return new DataResponse([
'status' => 'warning',
'message' => $this->l10n->t('iTop instance detected with error: %s', [$responseData['message'] ?? $this->l10n->t('Unknown error')]),
'details' => [
'url' => $testUrl,
'api_url' => $apiUrl,
'itop_code' => $responseData['code'],
'itop_message' => $responseData['message'] ?? ''
]
]);
}
} else {
return new DataResponse([
'status' => 'error',
'message' => $this->l10n->t('Server response does not match iTop API format'),
'details' => ['url' => $testUrl, 'response' => $responseData]
]);
}
} catch (\Exception $e) {
$this->logger->error('iTop connection test failed: ' . $e->getMessage(), ['app' => Application::APP_ID]);
return new DataResponse([
'status' => 'error',
'message' => $this->l10n->t('Connection test failed: %s', [$e->getMessage()]),
'details' => ['url' => $testUrl]
]);
}
}
/**
* Set admin configuration values
*
* @param array $values key/value pairs to store in admin preferences
* @return DataResponse
*/
public function setAdminConfig(array $values): DataResponse {
// Debug logging
$this->logger->info('iTop setAdminConfig called with values: ' . json_encode(array_keys($values)), ['app' => Application::APP_ID]);
$result = [];
$allowedKeys = ['admin_instance_url', 'user_facing_name', 'application_token'];
foreach ($values as $key => $value) {
// Only process allowed configuration keys
if (!in_array($key, $allowedKeys)) {
continue;
}
$this->logger->info('iTop processing key: ' . $key, ['app' => Application::APP_ID]);
if ($key === 'admin_instance_url') {
// Validate URL format
if ($value !== '' && !filter_var($value, FILTER_VALIDATE_URL)) {
$this->logger->error('iTop Invalid URL format: ' . $value, ['app' => Application::APP_ID]);
return new DataResponse(['message' => $this->l10n->t('Invalid URL format')], Http::STATUS_BAD_REQUEST);
}
$this->config->setAppValue(Application::APP_ID, $key, $value);
$result[$key] = $value;
} elseif ($key === 'user_facing_name') {
// Validate user facing name
$value = trim($value);
if (strlen($value) > 100) {
return new DataResponse(['message' => $this->l10n->t('User facing name is too long (max 100 characters)')], Http::STATUS_BAD_REQUEST);
}
if ($value === '') {
$value = 'iTop'; // Default fallback
}
$this->config->setAppValue(Application::APP_ID, $key, $value);
$result[$key] = $value;
} elseif ($key === 'application_token') {
// Handle application token with encryption
if ($value === '') {
// Delete token if empty
$this->config->deleteAppValue(Application::APP_ID, 'application_token');
$this->logger->info('iTop application token deleted', ['app' => Application::APP_ID]);
$result['has_application_token'] = false;
} else {
// Encrypt and store the token
$encryptedToken = $this->crypto->encrypt($value);
$this->config->setAppValue(Application::APP_ID, 'application_token', $encryptedToken);
$this->logger->info('iTop application token saved (encrypted)', ['app' => Application::APP_ID]);
$result['has_application_token'] = true;
}
}
$this->logger->info('iTop saved config key: ' . $key, ['app' => Application::APP_ID]);
}
$this->logger->info('iTop Admin configuration saved successfully', ['app' => Application::APP_ID]);
$result['message'] = $this->l10n->t('Admin configuration saved');
return new DataResponse($result);
}
/**
* Save ticket system type configuration
*
* @param string $ticketSystemType 'itil', 'simple', or 'auto'
* @param string $simpleTypeField Optional enum field name (may be empty)
* @param string $simpleIncidentValue Enum value meaning "incident"
* @param string $simpleRequestValue Enum value meaning "service request"
* @return DataResponse
*/
public function saveTicketSystemType(
string $ticketSystemType,
string $simpleTypeField = '',
string $simpleIncidentValue = 'incident',
string $simpleRequestValue = 'service_request',
): DataResponse {
$validTypes = [
Application::TICKET_SYSTEM_TYPE_ITIL,
Application::TICKET_SYSTEM_TYPE_SIMPLE,
Application::TICKET_SYSTEM_TYPE_AUTO,
];
if (!in_array($ticketSystemType, $validTypes, true)) {
return new DataResponse([
'message' => $this->l10n->t('Invalid ticket system type'),
], Http::STATUS_BAD_REQUEST);
}
$this->config->setAppValue(Application::APP_ID, 'ticket_system_type', $ticketSystemType);
// Store optional simple-mode enum configuration
$this->config->setAppValue(Application::APP_ID, 'simple_ticket_type_field', trim($simpleTypeField));
$this->config->setAppValue(Application::APP_ID, 'simple_ticket_incident_value', trim($simpleIncidentValue) ?: 'incident');
$this->config->setAppValue(Application::APP_ID, 'simple_ticket_request_value', trim($simpleRequestValue) ?: 'service_request');
// Clear the cached auto-detection result so the next request re-probes if needed
$this->config->deleteAppValue(Application::APP_ID, 'ticket_system_type_detected');
$this->logger->info('Ticket system type configuration saved: ' . $ticketSystemType, [
'app' => Application::APP_ID,
]);
return new DataResponse([
'message' => $this->l10n->t('Ticket system type configuration saved'),
'ticket_system_type' => $ticketSystemType,
]);
}
/**
* Save notification interval settings with validation
*
* @param int $portalInterval Portal notification check interval in minutes (5-1440)
* @return DataResponse
*/
public function saveNotificationSettings(int $portalInterval): DataResponse {
// Validation: 5 minutes to 24 hours
$minInterval = 5;
$maxInterval = 1440;
if ($portalInterval < $minInterval || $portalInterval > $maxInterval) {
return new DataResponse([
'message' => $this->l10n->t('Portal notification interval must be between %d and %d minutes', [$minInterval, $maxInterval])
], Http::STATUS_BAD_REQUEST);
}
// Save validated value
$this->config->setAppValue(Application::APP_ID, 'portal_notification_interval', (string)$portalInterval);
$this->logger->info('Notification interval settings updated', [
'app' => Application::APP_ID,
'portal_interval' => $portalInterval
]);
return new DataResponse([
'message' => $this->l10n->t('Notification settings saved successfully'),
'portal_notification_interval' => $portalInterval
]);
}
/**
* Save 3-state notification configuration
*
* @param int $defaultInterval Default notification check interval in minutes (5-1440)
* @param string $portalConfig JSON-encoded portal notification configuration
* @param string $agentConfig JSON-encoded agent notification configuration
* @return DataResponse
*/
public function saveNotificationConfig(int $defaultInterval, string $portalConfig, string $agentConfig): DataResponse {
// Validate interval
$minInterval = 5;
$maxInterval = 1440;
if ($defaultInterval < $minInterval || $defaultInterval > $maxInterval) {
return new DataResponse([
'message' => $this->l10n->t('Default notification interval must be between %d and %d minutes', [$minInterval, $maxInterval])
], Http::STATUS_BAD_REQUEST);
}
// Decode and validate portal config
$portalConfigArray = json_decode($portalConfig, true);
if (!is_array($portalConfigArray)) {
return new DataResponse([
'message' => $this->l10n->t('Invalid portal notification configuration format')
], Http::STATUS_BAD_REQUEST);
}
// Decode and validate agent config
$agentConfigArray = json_decode($agentConfig, true);
if (!is_array($agentConfigArray)) {
return new DataResponse([
'message' => $this->l10n->t('Invalid agent notification configuration format')
], Http::STATUS_BAD_REQUEST);
}
// Validate portal notification types and states
$validStates = [
Application::NOTIFICATION_STATE_DISABLED,
Application::NOTIFICATION_STATE_FORCED,
Application::NOTIFICATION_STATE_USER_CHOICE
];
foreach (Application::PORTAL_NOTIFICATION_TYPES as $type) {
if (!isset($portalConfigArray[$type]) || !in_array($portalConfigArray[$type], $validStates)) {
return new DataResponse([
'message' => $this->l10n->t('Invalid portal notification state for type: %s', [$type])
], Http::STATUS_BAD_REQUEST);
}
}
// Validate agent notification types and states
foreach (Application::AGENT_NOTIFICATION_TYPES as $type) {
if (!isset($agentConfigArray[$type]) || !in_array($agentConfigArray[$type], $validStates)) {
return new DataResponse([
'message' => $this->l10n->t('Invalid agent notification state for type: %s', [$type])
], Http::STATUS_BAD_REQUEST);
}
}
// Save all validated values
$this->config->setAppValue(Application::APP_ID, 'default_notification_interval', (string)$defaultInterval);
$this->config->setAppValue(Application::APP_ID, 'portal_notification_config', $portalConfig);
$this->config->setAppValue(Application::APP_ID, 'agent_notification_config', $agentConfig);
$this->logger->info('Notification configuration updated', [
'app' => Application::APP_ID,
'default_interval' => $defaultInterval,
'portal_config_keys' => array_keys($portalConfigArray),
'agent_config_keys' => array_keys($agentConfigArray)
]);
return new DataResponse([
'message' => $this->l10n->t('Notification configuration saved successfully'),
'default_notification_interval' => $defaultInterval,
'portal_notification_config' => $portalConfigArray,
'agent_notification_config' => $agentConfigArray
]);
}
/**
* Save cache TTL settings with validation
*
* @param int $ciPreviewTTL CI preview cache TTL in seconds
* @param int $ticketInfoTTL Ticket info cache TTL in seconds
* @param int $searchTTL Search results cache TTL in seconds
* @param int $pickerTTL Picker suggestions cache TTL in seconds
* @param int $profileTTL Profile cache TTL in seconds
* @return DataResponse
*/
public function saveCacheSettings(int $ciPreviewTTL, int $ticketInfoTTL, int $searchTTL, int $pickerTTL, int $profileTTL): DataResponse {
// Validation ranges
$minTTL = 10; // 10 seconds minimum
$maxTTLPreview = 3600; // 1 hour maximum for previews
$maxTTLOther = 300; // 5 minutes maximum for search/picker
$maxTTLProfile = 3600; // 1 hour maximum for profile cache
// Validate CI Preview TTL
if ($ciPreviewTTL < $minTTL || $ciPreviewTTL > $maxTTLPreview) {
return new DataResponse([
'message' => $this->l10n->t('CI Preview cache TTL must be between %d and %d seconds', [$minTTL, $maxTTLPreview])
], Http::STATUS_BAD_REQUEST);
}
// Validate Ticket Info TTL
if ($ticketInfoTTL < $minTTL || $ticketInfoTTL > $maxTTLPreview) {
return new DataResponse([
'message' => $this->l10n->t('Ticket Info cache TTL must be between %d and %d seconds', [$minTTL, $maxTTLPreview])
], Http::STATUS_BAD_REQUEST);
}
// Validate Search TTL
if ($searchTTL < $minTTL || $searchTTL > $maxTTLOther) {
return new DataResponse([
'message' => $this->l10n->t('Search cache TTL must be between %d and %d seconds', [$minTTL, $maxTTLOther])
], Http::STATUS_BAD_REQUEST);
}
// Validate Picker TTL
if ($pickerTTL < $minTTL || $pickerTTL > $maxTTLOther) {
return new DataResponse([
'message' => $this->l10n->t('Picker cache TTL must be between %d and %d seconds', [$minTTL, $maxTTLOther])
], Http::STATUS_BAD_REQUEST);
}
// Validate Profile TTL
if ($profileTTL < $minTTL || $profileTTL > $maxTTLProfile) {
return new DataResponse([
'message' => $this->l10n->t('Profile cache TTL must be between %d and %d seconds', [$minTTL, $maxTTLProfile])
], Http::STATUS_BAD_REQUEST);
}
// Save validated values
$this->config->setAppValue(Application::APP_ID, 'cache_ttl_ci_preview', (string)$ciPreviewTTL);
$this->config->setAppValue(Application::APP_ID, 'cache_ttl_ticket_info', (string)$ticketInfoTTL);
$this->config->setAppValue(Application::APP_ID, 'cache_ttl_search', (string)$searchTTL);
$this->config->setAppValue(Application::APP_ID, 'cache_ttl_picker', (string)$pickerTTL);
$this->config->setAppValue(Application::APP_ID, 'cache_ttl_profile', (string)$profileTTL);
$this->logger->info('Cache TTL settings updated', [
'app' => Application::APP_ID,
'ci_preview' => $ciPreviewTTL,
'ticket_info' => $ticketInfoTTL,
'search' => $searchTTL,
'picker' => $pickerTTL,
'profile' => $profileTTL
]);
return new DataResponse([
'message' => $this->l10n->t('Cache settings saved successfully'),
'cache_ttl_ci_preview' => $ciPreviewTTL,
'cache_ttl_ticket_info' => $ticketInfoTTL,
'cache_ttl_search' => $searchTTL,
'cache_ttl_picker' => $pickerTTL,
'cache_ttl_profile' => $profileTTL
]);
}
/**
* Get enabled CI classes from configuration
*
* @return array List of enabled CI class names
*/
private function getEnabledCIClasses(): array {
$enabledClassesJson = $this->config->getAppValue(Application::APP_ID, 'enabled_ci_classes', '');
if ($enabledClassesJson === '') {
// Default: no classes enabled (opt-in model)
return [];
}
$enabledClasses = json_decode($enabledClassesJson, true);
if (!is_array($enabledClasses)) {
// Fallback on invalid JSON: no classes enabled
return [];
}
// Filter to only valid classes
return array_values(array_intersect($enabledClasses, Application::SUPPORTED_CI_CLASSES));
}
/**
* Get user's disabled CI classes
*
* @NoAdminRequired
* @return DataResponse
*/
public function getUserDisabledCIClasses(): DataResponse {
if ($this->userId === null) {
return new DataResponse(['error' => $this->l10n->t('User not authenticated')], Http::STATUS_UNAUTHORIZED);
}
$userDisabledJson = $this->config->getUserValue($this->userId, Application::APP_ID, 'disabled_ci_classes', '');
$userDisabled = [];
if ($userDisabledJson !== '') {
$userDisabled = json_decode($userDisabledJson, true);
if (!is_array($userDisabled)) {
$userDisabled = [];
}
}
// Also get admin-enabled classes for reference
$adminEnabled = Application::getEnabledCIClasses($this->config);
return new DataResponse([
'admin_enabled_classes' => $adminEnabled,
'user_disabled_classes' => $userDisabled,
'effective_enabled_classes' => Application::getEffectiveEnabledCIClasses($this->config, $this->userId),
'supported_ci_classes' => Application::SUPPORTED_CI_CLASSES
]);
}
/**
* Save user's disabled CI classes
*
* @NoAdminRequired
* @param array $disabledClasses Array of CI class names user wants to disable
* @return DataResponse
*/
public function saveUserDisabledCIClasses(array $disabledClasses): DataResponse {
if ($this->userId === null) {
return new DataResponse(['error' => $this->l10n->t('User not authenticated')], Http::STATUS_UNAUTHORIZED);
}
// Validate that all provided classes are supported
$validClasses = array_intersect($disabledClasses, Application::SUPPORTED_CI_CLASSES);
// Remove duplicates and re-index
$validClasses = array_values(array_unique($validClasses));
// Save to user config