-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathItopAPIService.php
More file actions
2523 lines (2225 loc) · 87.7 KB
/
Copy pathItopAPIService.php
File metadata and controls
2523 lines (2225 loc) · 87.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
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\Service;
use DateTime;
use Exception;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\ServerException;
use OCA\Itop\AppInfo\Application;
use OCP\AppFramework\Http;
use OCP\Http\Client\IClient;
use OCP\Http\Client\IClientService;
use OCP\ICache;
use OCP\ICacheFactory;
use OCP\IConfig;
use OCP\IL10N;
use OCP\IUser;
use OCP\IUserManager;
use OCP\Notification\IManager as INotificationManager;
use OCP\PreConditionNotMetException;
use OCP\Security\ICrypto;
use Psr\Log\LoggerInterface;
class ItopAPIService {
private ICache $cache;
private IClient $client;
/**
* Service to make requests to iTop REST/JSON API
*
* Architecture:
* - Uses dual-token approach for security and Portal user compatibility
* - Application token (admin-level) for all API queries
* - Personal token (user-provided) for one-time identity verification only
* - Person ID stored per user to filter all queries and ensure data isolation
*/
public function __construct(
private IUserManager $userManager,
private LoggerInterface $logger,
private IL10N $l10n,
private IConfig $config,
private INotificationManager $notificationManager,
private ICrypto $crypto,
ICacheFactory $cacheFactory,
IClientService $clientService,
) {
$this->client = $clientService->newClient();
$this->cache = $cacheFactory->createDistributed(Application::APP_ID . '_global_info');
}
public function getItopUrl(string $userId): string {
$adminItopUrl = $this->config->getAppValue(Application::APP_ID, 'admin_instance_url');
return $this->config->getUserValue($userId, Application::APP_ID, 'url') ?: $adminItopUrl;
}
/**
* Build ticket URL based on user's portal access level
*
* Portal-only users get portal URLs (/pages/exec.php/object/edit/...)
* Power users (agents/admins) get admin UI URLs (/pages/UI.php?operation=details...)
*
* @param string $userId Nextcloud user ID
* @param string $class iTop class (UserRequest, Incident, etc.)
* @param string $id Ticket ID
* @return string Full ticket URL
*/
private function buildTicketUrl(string $userId, string $class, string $id): string {
$itopUrl = $this->getItopUrl($userId);
// Check if user is portal-only (cached by ProfileService)
$isPortalOnly = $this->config->getUserValue($userId, Application::APP_ID, 'is_portal_only', '0') === '1';
if ($isPortalOnly) {
// Portal user - use portal URL format
return $itopUrl . '/pages/exec.php/object/edit/' . $class . '/' . $id . '?exec_module=itop-portal-base&exec_page=index.php&portal_id=itop-portal';
} else {
// Power user - use admin UI URL format
return $itopUrl . '/pages/UI.php?operation=details&class=' . $class . '&id=' . $id;
}
}
/**
* Get application token for API requests
*
* @return string|null Decrypted application token or null if not configured
*/
private function getApplicationToken(): ?string {
$encryptedToken = $this->config->getAppValue(Application::APP_ID, 'application_token', '');
if (empty($encryptedToken)) {
return null;
}
try {
return $this->crypto->decrypt($encryptedToken);
} catch (\Exception $e) {
$this->logger->error('Failed to decrypt application token: ' . $e->getMessage(), ['app' => Application::APP_ID]);
return null;
}
}
/**
* Get person ID for a user
*
* @param string $userId
* @return string|null Person ID or null if not configured
*/
private function getPersonId(string $userId): ?string {
$personId = $this->config->getUserValue($userId, Application::APP_ID, 'person_id', '');
return $personId !== '' ? $personId : null;
}
/**
* Escape a string value for use in OQL queries
* Protects against OQL injection by properly escaping special characters
*
* @param string $value Value to escape
* @return string Escaped value safe for OQL
*/
private function escapeOQLString(string $value): string {
// Escape backslashes first to prevent double-escaping
$value = str_replace('\\', '\\\\', $value);
// Escape single quotes
$value = str_replace("'", "\\'", $value);
// Escape double quotes
$value = str_replace('"', '\\"', $value);
return $value;
}
/**
* Validate and sanitize a numeric ID for use in OQL queries
* Throws exception if ID is not numeric to prevent injection
*
* @param mixed $id ID to validate
* @return int Validated numeric ID
* @throws \InvalidArgumentException If ID is not numeric
*/
private function validateNumericId($id): int {
if (!is_numeric($id) || $id < 0) {
throw new \InvalidArgumentException('Invalid ID: must be a positive integer');
}
return (int)$id;
}
/**
* Validate class name against whitelist to prevent injection
*
* @param string $class Class name to validate
* @return string Validated class name
* @throws \InvalidArgumentException If class is not in whitelist
*/
private function validateClassName(string $class): string {
$allowedClasses = ['UserRequest', 'Incident', 'Person', 'User', 'Team', 'lnkContactToTicket',
'lnkPersonToTeam', 'Change', 'PC', 'Phone', 'IPPhone', 'MobilePhone', 'Tablet',
'Printer', 'Peripheral', 'PCSoftware', 'OtherSoftware', 'WebApplication', 'Software',
'SoftwareInstance', 'lnkContactToFunctionalCI'];
if (!in_array($class, $allowedClasses, true)) {
throw new \InvalidArgumentException('Invalid class name: ' . $class);
}
return $class;
}
/**
* Get tickets created by the current user (UserRequest + Incident)
*
* @param string $userId
* @param ?string $since
* @param ?int $limit
* @return array
* @throws PreConditionNotMetException|Exception
*/
public function getUserCreatedTickets(string $userId, ?string $since = null, ?int $limit = null): array {
// Get current user's details first
$userInfo = $this->getCurrentUser($userId);
if (isset($userInfo['error'])) {
return $userInfo;
}
// Extract user info - use full name for matching
$firstName = $userInfo['user']['first_name'] ?? '';
$lastName = $userInfo['user']['last_name'] ?? '';
$fullName = trim($firstName . ' ' . $lastName);
if (empty($fullName)) {
return [];
}
$allTickets = [];
$itopUrl = $this->getItopUrl($userId);
// Get person_id for more precise queries
$personId = $this->config->getUserValue($userId, Application::APP_ID, 'person_id', '');
// Query UserRequest tickets where user is caller OR contact
// Note: ORDER BY in complex queries with subqueries may not work, so we sort in PHP
if ($personId) {
$personId = $this->validateNumericId($personId);
$userRequestQuery = "SELECT UserRequest WHERE (caller_id = $personId OR id IN (SELECT UserRequest JOIN lnkContactToTicket ON lnkContactToTicket.ticket_id = UserRequest.id WHERE lnkContactToTicket.contact_id = $personId)) AND status != 'closed'";
} else {
// Fallback to name-based query if no person_id
$escapedFullName = $this->escapeOQLString($fullName);
$userRequestQuery = "SELECT UserRequest WHERE caller_id_friendlyname = '$escapedFullName' AND status != 'closed'";
}
$userRequestParams = [
'operation' => 'core/get',
'class' => 'UserRequest',
'key' => $userRequestQuery,
'output_fields' => '*'
];
if ($limit) {
$userRequestParams['limit'] = $limit;
}
$userRequestResult = $this->request($userId, $userRequestParams);
// Debug: log raw API response structure
if (isset($userRequestResult['objects']) && count($userRequestResult['objects']) > 0) {
$firstTicket = array_values($userRequestResult['objects'])[0];
\OC::$server->get(\Psr\Log\LoggerInterface::class)->debug(
'First UserRequest full structure: ' . json_encode($firstTicket),
['app' => Application::APP_ID]
);
}
if (isset($userRequestResult['objects'])) {
foreach ($userRequestResult['objects'] as $objectKey => $ticket) {
// The ticket ID is in the 'key' field of the ticket object
$ticketId = $ticket['key'] ?? null;
if (!$ticketId) {
// Fallback: extract from object key like "UserRequest::2"
$ticketId = strpos($objectKey, '::') !== false ? explode('::', $objectKey)[1] : $objectKey;
}
$allTickets[] = [
'type' => 'UserRequest',
'id' => $ticketId,
'ref' => $ticket['fields']['ref'] ?? '',
'title' => $ticket['fields']['title'] ?? '',
'description' => $ticket['fields']['description'] ?? '',
'status' => $ticket['fields']['status'] ?? 'unknown',
'operational_status' => $ticket['fields']['operational_status'] ?? '',
'priority' => $ticket['fields']['priority'] ?? '',
'agent' => $ticket['fields']['agent_id_friendlyname'] ?? '',
'start_date' => $ticket['fields']['start_date'] ?? '',
'last_update' => $ticket['fields']['last_update'] ?? '',
'close_date' => $ticket['fields']['close_date'] ?? '',
'url' => $this->buildTicketUrl($userId, 'UserRequest', $ticketId)
];
}
}
// Query Incident tickets where user is caller OR contact
if ($personId) {
$incidentQuery = "SELECT Incident WHERE (caller_id = $personId OR id IN (SELECT Incident JOIN lnkContactToTicket ON lnkContactToTicket.ticket_id = Incident.id WHERE lnkContactToTicket.contact_id = $personId)) AND status != 'closed'";
} else {
// Fallback to name-based query if no person_id
$escapedFullName = $this->escapeOQLString($fullName);
$incidentQuery = "SELECT Incident WHERE caller_id_friendlyname = '$escapedFullName' AND status != 'closed'";
}
$incidentParams = [
'operation' => 'core/get',
'class' => 'Incident',
'key' => $incidentQuery,
'output_fields' => '*'
];
if ($limit) {
$incidentParams['limit'] = $limit;
}
$incidentResult = $this->request($userId, $incidentParams);
if (isset($incidentResult['objects'])) {
foreach ($incidentResult['objects'] as $objectKey => $ticket) {
// The ticket ID is in the 'key' field of the ticket object
$ticketId = $ticket['key'] ?? null;
if (!$ticketId) {
// Fallback: extract from object key like "Incident::4"
$ticketId = strpos($objectKey, '::') !== false ? explode('::', $objectKey)[1] : $objectKey;
}
$allTickets[] = [
'type' => 'Incident',
'id' => $ticketId,
'ref' => $ticket['fields']['ref'] ?? '',
'title' => $ticket['fields']['title'] ?? '',
'description' => $ticket['fields']['description'] ?? '',
'status' => $ticket['fields']['status'] ?? 'unknown',
'operational_status' => $ticket['fields']['operational_status'] ?? '',
'priority' => $ticket['fields']['priority'] ?? '',
'agent' => $ticket['fields']['agent_id_friendlyname'] ?? '',
'start_date' => $ticket['fields']['start_date'] ?? '',
'last_update' => $ticket['fields']['last_update'] ?? '',
'close_date' => $ticket['fields']['close_date'] ?? '',
'url' => $this->buildTicketUrl($userId, 'Incident', $ticketId)
];
}
}
return $allTickets;
}
/**
* Get tickets created by the current user grouped by status with counts
*
* @param string $userId
* @return array { by_status: {status=>count}, tickets: {status=>tickets[]} }
*/
public function getUserTicketsByStatus(string $userId): array {
$tickets = $this->getUserCreatedTickets($userId, null, 100);
$groups = [
'open' => [],
'escalated' => [],
'pending' => [],
'resolved' => [],
'closed' => [],
'unknown' => [],
];
$rawStatuses = []; // Debug: collect all raw statuses
foreach (is_array($tickets) ? $tickets : [] as $ticket) {
$statusRaw = strtolower($ticket['status'] ?? '');
$rawStatuses[] = $statusRaw; // Debug
// Map iTop statuses to dashboard categories
$status = match (true) {
// Open statuses
$statusRaw === 'new' || $statusRaw === 'assigned' || $statusRaw === 'dispatched' || $statusRaw === 'open' => 'open',
// Escalated statuses
$statusRaw === 'escalated_tto' || $statusRaw === 'escalated_ttr' || str_contains($statusRaw, 'escalated') => 'escalated',
// Pending statuses
$statusRaw === 'pending' || $statusRaw === 'waiting_for_approval' || $statusRaw === 'paused' => 'pending',
// Resolved statuses
$statusRaw === 'resolved' || $statusRaw === 'solution_approved' => 'resolved',
// Closed statuses
$statusRaw === 'closed' => 'closed',
// Default: treat as open if not recognized
default => 'open',
};
$groups[$status][] = $ticket;
}
$counts = [];
foreach ($groups as $key => $list) {
$counts[$key] = count($list);
}
// Debug: log raw statuses
\OC::$server->get(\Psr\Log\LoggerInterface::class)->debug(
'getUserTicketsByStatus: Raw statuses found: ' . json_encode($rawStatuses),
['app' => Application::APP_ID]
);
return [
'by_status' => $counts,
'tickets' => $groups,
];
}
/**
* Get count of tickets created by the current user (separate counts for UserRequest and Incident)
*
* @param string $userId
* @return array
* @throws Exception
*/
public function getUserCreatedTicketsCount(string $userId): array {
// Get current user's details first
$userInfo = $this->getCurrentUser($userId);
if (isset($userInfo['error'])) {
return ['error' => $userInfo['error']];
}
// Extract user info - use full name for matching
$firstName = $userInfo['user']['first_name'] ?? '';
$lastName = $userInfo['user']['last_name'] ?? '';
$fullName = trim($firstName . ' ' . $lastName);
if (empty($fullName)) {
return ['incidents' => 0, 'requests' => 0, 'status' => 'no_user'];
}
$incidentCount = 0;
$requestCount = 0;
// Query UserRequest tickets
$escapedFullName = $this->escapeOQLString($fullName);
$userRequestQuery = "SELECT UserRequest WHERE caller_id_friendlyname = '$escapedFullName' AND status != 'closed'";
$userRequestParams = [
'operation' => 'core/get',
'class' => 'UserRequest',
'key' => $userRequestQuery,
'output_fields' => 'id'
];
$userRequestResult = $this->request($userId, $userRequestParams);
if (isset($userRequestResult['objects'])) {
$requestCount = count($userRequestResult['objects']);
}
// Query Incident tickets
$incidentQuery = "SELECT Incident WHERE caller_id_friendlyname = '$escapedFullName' AND status != 'closed'";
$incidentParams = [
'operation' => 'core/get',
'class' => 'Incident',
'key' => $incidentQuery,
'output_fields' => 'id'
];
$incidentResult = $this->request($userId, $incidentParams);
if (isset($incidentResult['objects'])) {
$incidentCount = count($incidentResult['objects']);
}
// Return separate counts
return [
'incidents' => $incidentCount,
'requests' => $requestCount,
'total' => $incidentCount + $requestCount,
'status' => 'success'
];
}
/**
* Get current user information
*
* Portal users can access their own Person record but not the User class.
* Strategy: Get a UserRequest to find caller_id (Person ID), then query Person directly.
*
* @param string $userId
* @return array
* @throws Exception
*/
public function getCurrentUser(string $userId): array {
// Check if user has configured their Person ID manually
$personId = $this->config->getUserValue($userId, Application::APP_ID, 'person_id', '');
// If no Person ID configured, try to get it from a UserRequest
if (!$personId) {
$ticketParams = [
'operation' => 'core/get',
'class' => 'UserRequest',
'key' => 'SELECT UserRequest LIMIT 1',
'output_fields' => 'caller_id,caller_id_friendlyname'
];
$ticketResult = $this->request($userId, $ticketParams);
// Extract Person ID from the ticket's caller_id
if (isset($ticketResult['objects']) && !empty($ticketResult['objects'])) {
$ticketKey = array_keys($ticketResult['objects'])[0];
$personId = $ticketResult['objects'][$ticketKey]['fields']['caller_id'] ?? null;
}
}
// If still no Person ID, return helpful error with instructions
if (!$personId) {
return [
'code' => 1,
'message' => 'Portal user detected: Please configure your Person ID in the settings below, or ensure you have created at least one ticket in iTop.',
'user' => null
];
}
// Step 2: Query the Person record directly by ID
// Portal users have permission to read their own Person record
$personParams = [
'operation' => 'core/get',
'class' => 'Person',
'key' => $personId,
'output_fields' => 'friendlyname,first_name,name,email,phone,org_id_friendlyname'
];
$personResult = $this->request($userId, $personParams);
// If we got the person record, transform to expected format
if (isset($personResult['objects']) && !empty($personResult['objects'])) {
$personKey = array_keys($personResult['objects'])[0];
$person = $personResult['objects'][$personKey];
return [
'code' => 0,
'message' => 'User authenticated successfully',
'version' => '1.3',
'user' => [
'login' => $person['fields']['email'] ?? 'Unknown', // Portal users don't have login field in Person
'first_name' => $person['fields']['first_name'] ?? '',
'last_name' => $person['fields']['name'] ?? '',
'email' => $person['fields']['email'] ?? '',
'org_name' => $person['fields']['org_id_friendlyname'] ?? '',
'phone' => $person['fields']['phone'] ?? '',
'status' => 'active' // Person records don't have status, assume active
],
'privileges' => [] // Portal users - privileges not available from Person class
];
}
// If no person found or error, return the result
return $personResult;
}
/**
* Search for tickets and CIs
*
* @param string $userId
* @param string $query Search term
* @param int $offset
* @param int $limit
* @return array
* @throws Exception
*/
public function search(string $userId, string $query, int $offset = 0, int $limit = 10): array {
// Get current user's details first
$userInfo = $this->getCurrentUser($userId);
if (isset($userInfo['error'])) {
return $userInfo;
}
// Extract user info - use full name for matching
$firstName = $userInfo['user']['first_name'] ?? '';
$lastName = $userInfo['user']['last_name'] ?? '';
$fullName = trim($firstName . ' ' . $lastName);
if (empty($fullName)) {
return [];
}
// Escape single quotes in search query for OQL
$escapedQuery = str_replace("'", "\\'", $query);
$searchResults = [];
$itopUrl = $this->getItopUrl($userId);
// Search UserRequests - tickets where user is creator OR assigned agent
// Also search by ref (ticket ID like R-000001)
// Note: Contact relationship search added separately below
$userRequestQuery = "SELECT UserRequest WHERE "
. "(caller_id_friendlyname = '$fullName' OR agent_id_friendlyname = '$fullName') "
. "AND (title LIKE '%$escapedQuery%' OR description LIKE '%$escapedQuery%' OR ref LIKE '%$escapedQuery%')";
$userRequestParams = [
'operation' => 'core/get',
'class' => 'UserRequest',
'key' => $userRequestQuery,
'output_fields' => 'id,ref,title,description,status,priority,caller_id_friendlyname,agent_id_friendlyname,start_date,last_update,close_date'
];
if ($limit) {
$userRequestParams['limit'] = $limit + 5; // Get extra to compensate for Incidents
}
$userRequests = $this->request($userId, $userRequestParams);
if (isset($userRequests['objects'])) {
foreach ($userRequests['objects'] as $key => $ticket) {
$searchResults[] = [
'type' => 'UserRequest',
'id' => $ticket['fields']['id'],
'ref' => $ticket['fields']['ref'] ?? '',
'title' => $ticket['fields']['title'],
'description' => strip_tags($ticket['fields']['description'] ?? ''),
'status' => $ticket['fields']['status'],
'priority' => $ticket['fields']['priority'] ?? '',
'caller' => $ticket['fields']['caller_id_friendlyname'] ?? '',
'agent' => $ticket['fields']['agent_id_friendlyname'] ?? '',
'start_date' => $ticket['fields']['start_date'] ?? '',
'last_update' => $ticket['fields']['last_update'] ?? '',
'close_date' => $ticket['fields']['close_date'] ?? '',
'url' => $this->buildTicketUrl($userId, 'UserRequest', $ticket['fields']['id'])
];
}
}
// Search Incidents - tickets where user is creator OR assigned agent
// Also search by ref (ticket ID like I-000006)
// Note: Contact relationship search added separately below
$incidentQuery = "SELECT Incident WHERE "
. "(caller_id_friendlyname = '$fullName' OR agent_id_friendlyname = '$fullName') "
. "AND (title LIKE '%$escapedQuery%' OR description LIKE '%$escapedQuery%' OR ref LIKE '%$escapedQuery%')";
$incidentParams = [
'operation' => 'core/get',
'class' => 'Incident',
'key' => $incidentQuery,
'output_fields' => 'id,ref,title,description,status,priority,caller_id_friendlyname,agent_id_friendlyname,start_date,last_update,close_date'
];
if ($limit) {
$incidentParams['limit'] = $limit + 5;
}
$incidents = $this->request($userId, $incidentParams);
if (isset($incidents['objects'])) {
foreach ($incidents['objects'] as $key => $ticket) {
$searchResults[] = [
'type' => 'Incident',
'id' => $ticket['fields']['id'],
'ref' => $ticket['fields']['ref'] ?? '',
'title' => $ticket['fields']['title'],
'description' => strip_tags($ticket['fields']['description'] ?? ''),
'status' => $ticket['fields']['status'],
'priority' => $ticket['fields']['priority'] ?? '',
'caller' => $ticket['fields']['caller_id_friendlyname'] ?? '',
'agent' => $ticket['fields']['agent_id_friendlyname'] ?? '',
'start_date' => $ticket['fields']['start_date'] ?? '',
'last_update' => $ticket['fields']['last_update'] ?? '',
'close_date' => $ticket['fields']['close_date'] ?? '',
'url' => $this->buildTicketUrl($userId, 'Incident', $ticket['fields']['id'])
];
}
}
// Additional search: Find tickets where user is listed as a contact (lnkContactToTicket)
// This handles cases where user is added to the Contacts tab of a ticket
$personId = $this->getPersonId($userId);
if ($personId) {
// Search for UserRequest contacts
$contactLinksUR = $this->request($userId, [
'operation' => 'core/get',
'class' => 'lnkContactToTicket',
'key' => "SELECT lnkContactToTicket WHERE contact_id = $personId",
'output_fields' => 'ticket_id,ticket_ref'
]);
if (isset($contactLinksUR['objects']) && !empty($contactLinksUR['objects'])) {
foreach ($contactLinksUR['objects'] as $link) {
$ticketId = $link['fields']['ticket_id'] ?? null;
$ticketRef = $link['fields']['ticket_ref'] ?? '';
// Only fetch if ref matches search query
if ($ticketId && (empty($escapedQuery) || stripos($ticketRef, $query) !== false)) {
// Determine ticket class from ref (R- = UserRequest, I- = Incident)
$ticketClass = (strpos($ticketRef, 'R-') === 0) ? 'UserRequest' :
((strpos($ticketRef, 'I-') === 0) ? 'Incident' : null);
if ($ticketClass) {
$ticketData = $this->request($userId, [
'operation' => 'core/get',
'class' => $ticketClass,
'key' => $ticketId,
'output_fields' => 'id,ref,title,description,status,priority,caller_id_friendlyname,agent_id_friendlyname,start_date,last_update,close_date'
]);
if (isset($ticketData['objects']) && !empty($ticketData['objects'])) {
$ticket = reset($ticketData['objects']);
// Check if title/description matches search
$titleMatch = empty($escapedQuery) || stripos($ticket['fields']['title'] ?? '', $query) !== false;
$descMatch = empty($escapedQuery) || stripos($ticket['fields']['description'] ?? '', $query) !== false;
if ($titleMatch || $descMatch || stripos($ticketRef, $query) !== false) {
$searchResults[] = [
'type' => $ticketClass,
'id' => $ticket['fields']['id'],
'ref' => $ticket['fields']['ref'] ?? '',
'title' => $ticket['fields']['title'],
'description' => strip_tags($ticket['fields']['description'] ?? ''),
'status' => $ticket['fields']['status'],
'priority' => $ticket['fields']['priority'] ?? '',
'caller' => $ticket['fields']['caller_id_friendlyname'] ?? '',
'agent' => $ticket['fields']['agent_id_friendlyname'] ?? '',
'start_date' => $ticket['fields']['start_date'] ?? '',
'last_update' => $ticket['fields']['last_update'] ?? '',
'close_date' => $ticket['fields']['close_date'] ?? '',
'url' => $this->buildTicketUrl($userId, $ticketClass, $ticket['fields']['id'])
];
}
}
}
}
}
}
}
// Remove duplicates (ticket might be in both searches)
$seen = [];
$searchResults = array_filter($searchResults, function($ticket) use (&$seen) {
$key = $ticket['type'] . '-' . $ticket['id'];
if (isset($seen[$key])) {
return false;
}
$seen[$key] = true;
return true;
});
// Sort by last_update descending (most recent first)
usort($searchResults, function($a, $b) {
return strcmp($b['last_update'] ?? '', $a['last_update'] ?? '');
});
return array_slice($searchResults, $offset, $limit);
}
/**
* Get detailed information about a ticket
*
* @param string $userId
* @param int $ticketId
* @return array
* @throws PreConditionNotMetException|Exception
*/
public function getTicketInfo(string $userId, int $ticketId, string $class = 'UserRequest'): array {
$params = [
'operation' => 'core/get',
'class' => $class,
'key' => $ticketId,
'output_fields' => '*'
];
return $this->request($userId, $params);
}
/**
* Get CI preview data for a single CI
*
* Fetches only the fields needed for preview rendering (defined in docs/class-mapping.md).
* Uses profile-aware filtering: Portal-only users get CIs from contacts_list,
* power users get full CMDB access within ACL.
*
* @param string $userId Nextcloud user ID
* @param string $class iTop CI class (PC, Phone, Tablet, etc.)
* @param int $id CI ID
* @param bool $isPortalOnly Whether user has only Portal user profile
* @return array CI data with preview fields or error
* @throws Exception
*/
public function getCIPreview(string $userId, string $class, int $id, bool $isPortalOnly = false): array {
// Define preview fields per class (from docs/class-mapping.md)
$outputFields = $this->getCIPreviewFields($class);
// Build query with profile-aware filtering
if ($isPortalOnly) {
// Portal-only users: Only CIs where they are listed as contact
$personId = $this->getPersonId($userId);
if (!$personId) {
return ['error' => $this->l10n->t('User not configured')];
}
// Query via lnkContactToFunctionalCI to get allowed CIs
$query = "SELECT $class AS ci JOIN lnkContactToFunctionalCI AS lnk ON lnk.functionalci_id = ci.id WHERE lnk.contact_id = $personId AND ci.id = $id";
$params = [
'operation' => 'core/get',
'class' => $class,
'key' => $query,
'output_fields' => $outputFields
];
} else {
// Power users: Full CMDB access within ACL
// For core/get with simple ID lookup, just pass the ID directly
$params = [
'operation' => 'core/get',
'class' => $class,
'key' => $id,
'output_fields' => $outputFields
];
}
return $this->request($userId, $params);
}
/**
* Search CIs with profile-aware filtering
*
* Portal-only users: Only CIs where they are listed as contact (contacts_list)
* Power users: Full CMDB access within ACL
*
* @param string $userId Nextcloud user ID
* @param string $term Search term (searches name, serialnumber, asset_number)
* @param array $classes CI classes to search (default: all supported classes)
* @param bool $isPortalOnly Whether user has only Portal user profile
* @param int $limit Maximum results per class
* @return array Search results with preview data
* @throws Exception
*/
public function searchCIs(string $userId, string $term, array $classes = [], bool $isPortalOnly = false, int $limit = 10): array {
// Default to effective enabled CI classes (admin-enabled minus user-disabled)
if (empty($classes)) {
$classes = Application::getEffectiveEnabledCIClasses($this->config, $userId);
}
$searchResults = [];
$itopUrl = $this->getItopUrl($userId);
$escapedTerm = str_replace("'", "\\'", $term);
// Get person ID for portal-only filtering
$personId = null;
if ($isPortalOnly) {
$personId = $this->getPersonId($userId);
if (!$personId) {
return ['error' => $this->l10n->t('User not configured')];
}
}
foreach ($classes as $class) {
// Skip Software search for Portal-only users
if ($class === 'Software' && $isPortalOnly) {
continue;
}
$outputFields = $this->getCIPreviewFields($class);
// Class-aware joins and term clause
$joins = '';
$termClause = '';
if (in_array($class, ['PCSoftware', 'OtherSoftware'], true)) {
// Software instances: match without joins using friendlyname fields
$termClause = "(ci.system_name LIKE '%$escapedTerm%' OR ci.software_id_friendlyname LIKE '%$escapedTerm%' OR ci.path LIKE '%$escapedTerm%' OR ci.friendlyname LIKE '%$escapedTerm%')";
} elseif ($class === 'WebApplication') {
// Web applications: match name and URL
$termClause = "(ci.name LIKE '%$escapedTerm%' OR ci.url LIKE '%$escapedTerm%')";
} elseif ($class === 'Software') {
// Software catalog entries: try exact-like on name/vendor first
$termClause = "(ci.name LIKE '$escapedTerm' OR ci.vendor LIKE '$escapedTerm')";
} elseif (in_array($class, Application::SUPPORTED_CI_CLASSES, true)) {
// Known hardware-like CIs (FunctionalCI subclasses): include brand/model; add phone specifics
$termParts = [
"ci.name LIKE '%$escapedTerm%'",
"ci.serialnumber LIKE '%$escapedTerm%'",
"ci.asset_number LIKE '%$escapedTerm%'",
"ci.brand_id_friendlyname LIKE '%$escapedTerm%'",
"ci.model_id_friendlyname LIKE '%$escapedTerm%'",
];
if (in_array($class, ['Phone','IPPhone','MobilePhone'], true)) {
$termParts[] = "ci.phonenumber LIKE '%$escapedTerm%'";
}
if ($class === 'MobilePhone') {
$termParts[] = "ci.imei LIKE '%$escapedTerm%'";
}
$termClause = '(' . implode(' OR ', $termParts) . ')';
} else {
// Custom / unknown CI classes: use a safe minimal search on name only
// to avoid OQL failures with fields that may not exist in this class.
$termClause = "ci.name LIKE '%$escapedTerm%'";
}
// Build OQL query with profile-aware filtering
if ($isPortalOnly) {
if ($class === 'Software') {
// Software is not a FunctionalCI; do not filter via lnkContactToFunctionalCI
$query = "SELECT $class AS ci WHERE $termClause";
} else {
// Portal-only: Only CIs where user is contact (FunctionalCI and subclasses)
$query = "SELECT $class AS ci JOIN lnkContactToFunctionalCI AS lnk ON lnk.functionalci_id = ci.id"
. $joins
. " WHERE lnk.contact_id = $personId AND $termClause";
}
} else {
// Power users: Full CMDB search within ACL
$query = "SELECT $class AS ci"
. $joins
. " WHERE $termClause";
}
$params = [
'operation' => 'core/get',
'class' => $class,
'key' => $query,
'output_fields' => $outputFields,
'limit' => $limit
];
// no debug logging
$result = $this->request($userId, $params, 'POST', $class !== 'Software');
// If Software exact-like returns empty, retry with wildcards
if ($class === 'Software') {
$empty = !isset($result['objects']) || empty($result['objects']);
if ($empty && $escapedTerm !== '') {
$termClauseWildcard = "(ci.name LIKE '%$escapedTerm%' OR ci.vendor LIKE '%$escapedTerm%')";
$queryWildcard = "SELECT $class AS ci WHERE $termClauseWildcard";
$result = $this->request($userId, [
'operation' => 'core/get',
'class' => $class,
'key' => $queryWildcard,
'output_fields' => $outputFields,
'limit' => $limit
], 'POST', false);
}
}
if ($class === 'Software') {
// no debug logging
}
// Fallback for Software: if empty, derive from SoftwareInstance matches
if (($class === 'Software') && (!isset($result['objects']) || empty($result['objects'])) && $escapedTerm !== '') {
$si = $this->request($userId, [
'operation' => 'core/get',
'class' => 'SoftwareInstance',
'key' => "SELECT SoftwareInstance AS si WHERE (si.system_name LIKE '%$escapedTerm%' OR si.software_id_friendlyname LIKE '%$escapedTerm%')",
'output_fields' => 'software_id',
'limit' => $limit * 2,
], 'POST', false);
$ids = [];
if (isset($si['objects'])) {
foreach ($si['objects'] as $obj) {
$ids[] = (int)($obj['fields']['software_id'] ?? 0);
}
$ids = array_values(array_unique(array_filter($ids)));
}
if (!empty($ids)) {
$idsCsv = implode(',', $ids);
$result = $this->request($userId, [
'operation' => 'core/get',
'class' => 'Software',
'key' => "SELECT Software WHERE id IN ($idsCsv)",
'output_fields' => $outputFields,
'limit' => $limit
]);
}
}
if (isset($result['objects'])) {
$this->logger->debug('SearchCIs: Found ' . count($result['objects']) . ' results for class ' . $class, ['app' => Application::APP_ID]);
foreach ($result['objects'] as $key => $ci) {
$fields = $ci['fields'] ?? [];
// Robust title fallback across CI families
$name = $fields['name']
?? $fields['friendlyname']
?? $fields['system_name']
?? $fields['software_id_friendlyname']
?? '';
$entry = [
'class' => $class,
'id' => $fields['id'] ?? null,
'name' => $name,
'status' => $fields['status'] ?? '',
'business_criticity' => $fields['business_criticity'] ?? '',
'org_name' => $fields['org_id_friendlyname'] ?? '',
'location' => $fields['location_id_friendlyname'] ?? '',
'serialnumber' => $fields['serialnumber'] ?? '',
'asset_number' => $fields['asset_number'] ?? '',
'brand_model' => trim(($fields['brand_id_friendlyname'] ?? '') . ' ' . ($fields['model_id_friendlyname'] ?? '')),
'description' => strip_tags($fields['description'] ?? ''),
'url' => $itopUrl . '/pages/UI.php?operation=details&class=' . urlencode($class) . '&id=' . ($fields['id'] ?? '')
];
// Class-specific enrichments for subline rendering
if ($class === 'WebApplication') {
$entry['web_url'] = $fields['url'] ?? '';
$entry['webserver_name'] = $fields['webserver_id_friendlyname'] ?? '';
} elseif ($class === 'PCSoftware' || $class === 'OtherSoftware') {
$entry['system_name'] = $fields['system_name'] ?? '';
$entry['software'] = $fields['software_id_friendlyname'] ?? '';
$entry['license'] = $fields['softwarelicence_id_friendlyname'] ?? '';
$entry['path'] = $fields['path'] ?? '';
} elseif ($class === 'Software') {
$entry['vendor'] = $fields['vendor'] ?? '';
$entry['version'] = $fields['version'] ?? '';
$entry['counts'] = [
'documents' => $this->countFromLinkedSet($fields['documents_list'] ?? null),
'instances' => $this->countFromLinkedSet($fields['softwareinstance_list'] ?? null),
'patches' => $this->countFromLinkedSet($fields['softwarepatch_list'] ?? null),
'licenses' => $this->countFromLinkedSet($fields['softwarelicence_list'] ?? null),
];
}
$searchResults[] = $entry;
}
} else {
$this->logger->debug('SearchCIs: No objects found for class ' . $class, ['app' => Application::APP_ID]);
}
}
// Sort by name
usort($searchResults, function($a, $b) {
return strcasecmp($a['name'], $b['name']);
});
return $searchResults;
}
/**
* Helper to count linked objects for Software summaries from AttributeLinkedSet
*/
private function countFromLinkedSet($linkedSet): int {
if (!is_array($linkedSet)) {
return 0;
}
// iTop may return ['items' => [id => fields, ...]] or a plain array
if (isset($linkedSet['items']) && is_array($linkedSet['items'])) {
return count($linkedSet['items']);
}
return count($linkedSet);
}
/**
* Get preview fields for a CI class
*
* Returns comma-separated field list for output_fields parameter.
* Based on docs/class-mapping.md specifications.