-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhook.php
More file actions
677 lines (613 loc) · 27.6 KB
/
hook.php
File metadata and controls
677 lines (613 loc) · 27.6 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
<?php
/**
* Tasks Manager - Install/Uninstall hooks
*
* @license GPL-3.0-or-later
*/
/**
* Install hook - create database tables and initial config
*
* @return bool
*/
function plugin_tasksmanager_install(): bool
{
global $DB;
// -------------------------------------------------------
// Table: glpi_plugin_tasksmanager_taskstates
// -------------------------------------------------------
if (!$DB->tableExists('glpi_plugin_tasksmanager_taskstates')) {
$DB->doQuery("CREATE TABLE `glpi_plugin_tasksmanager_taskstates` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`tickets_id` INT UNSIGNED NOT NULL DEFAULT 0,
`tickettasks_id` INT UNSIGNED NOT NULL DEFAULT 0,
`plugin_status` VARCHAR(50) NOT NULL DEFAULT 'pending',
`priority` TINYINT NOT NULL DEFAULT 3,
`due_date` TIMESTAMP NULL DEFAULT NULL,
`assigned_users_id` INT UNSIGNED NOT NULL DEFAULT 0,
`assigned_groups_id` INT UNSIGNED NOT NULL DEFAULT 0,
`progress` TINYINT UNSIGNED NOT NULL DEFAULT 0,
`notes` TEXT NULL,
`ticket_workflows_id` INT UNSIGNED NULL DEFAULT NULL,
`workflow_step_order` INT UNSIGNED NULL DEFAULT NULL,
`date_creation` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`date_mod` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `tickets_id` (`tickets_id`),
KEY `tickettasks_id` (`tickettasks_id`),
KEY `plugin_status` (`plugin_status`),
KEY `assigned_users_id` (`assigned_users_id`),
KEY `assigned_groups_id` (`assigned_groups_id`),
KEY `due_date` (`due_date`),
KEY `ticket_workflows_id` (`ticket_workflows_id`),
KEY `date_mod` (`date_mod`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;");
} else {
// Upgrade: add workflow tracking columns if missing
if (!$DB->fieldExists('glpi_plugin_tasksmanager_taskstates', 'ticket_workflows_id')) {
$DB->doQuery("ALTER TABLE `glpi_plugin_tasksmanager_taskstates`
ADD `ticket_workflows_id` INT UNSIGNED NULL DEFAULT NULL AFTER `notes`,
ADD `workflow_step_order` INT UNSIGNED NULL DEFAULT NULL AFTER `ticket_workflows_id`,
ADD KEY `ticket_workflows_id` (`ticket_workflows_id`)");
}
}
// -------------------------------------------------------
// Table: glpi_plugin_tasksmanager_configs
// -------------------------------------------------------
if (!$DB->tableExists('glpi_plugin_tasksmanager_configs')) {
$DB->doQuery("CREATE TABLE `glpi_plugin_tasksmanager_configs` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`key` VARCHAR(255) NOT NULL,
`value` TEXT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `key` (`key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;");
$DB->insert('glpi_plugin_tasksmanager_configs', ['key' => 'default_priority', 'value' => '3']);
$DB->insert('glpi_plugin_tasksmanager_configs', ['key' => 'enable_notifications', 'value' => '1']);
$DB->insert('glpi_plugin_tasksmanager_configs', [
'key' => 'statuses',
'value' => json_encode(['pending', 'in_progress', 'blocked', 'review', 'done']),
]);
}
// -------------------------------------------------------
// Table: glpi_plugin_tasksmanager_workflows
// Named workflow definitions
// -------------------------------------------------------
if (!$DB->tableExists('glpi_plugin_tasksmanager_workflows')) {
$DB->doQuery("CREATE TABLE `glpi_plugin_tasksmanager_workflows` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL,
`description` TEXT NULL,
`is_active` TINYINT NOT NULL DEFAULT 1,
`assign_ticket_to_task` TINYINT NOT NULL DEFAULT 1,
`groups_id_completion` INT UNSIGNED NOT NULL DEFAULT 0,
`date_creation` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`date_mod` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `name` (`name`),
KEY `is_active` (`is_active`),
KEY `groups_id_completion` (`groups_id_completion`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;");
} else {
// Upgrade: add groups_id_completion if missing
if (!$DB->fieldExists('glpi_plugin_tasksmanager_workflows', 'groups_id_completion')) {
$DB->doQuery("ALTER TABLE `glpi_plugin_tasksmanager_workflows`
ADD `groups_id_completion` INT UNSIGNED NOT NULL DEFAULT 0 AFTER `is_active`,
ADD KEY `groups_id_completion` (`groups_id_completion`)");
}
// Upgrade: add assign_ticket_to_task if missing
if (!$DB->fieldExists('glpi_plugin_tasksmanager_workflows', 'assign_ticket_to_task')) {
$DB->doQuery("ALTER TABLE `glpi_plugin_tasksmanager_workflows`
ADD `assign_ticket_to_task` TINYINT NOT NULL DEFAULT 1 AFTER `is_active`");
}
}
// -------------------------------------------------------
// Table: glpi_plugin_tasksmanager_workflow_steps
// Ordered task-template steps belonging to a workflow
// -------------------------------------------------------
if (!$DB->tableExists('glpi_plugin_tasksmanager_workflow_steps')) {
$DB->doQuery("CREATE TABLE `glpi_plugin_tasksmanager_workflow_steps` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`workflows_id` INT UNSIGNED NOT NULL DEFAULT 0,
`tasktemplates_id` INT UNSIGNED NOT NULL DEFAULT 0,
`step_order` INT UNSIGNED NOT NULL DEFAULT 0,
`description` TEXT NULL,
`next_step_rules` TEXT NULL,
`default_goto_step_id` INT NOT NULL DEFAULT 0,
`date_creation` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `workflows_id` (`workflows_id`),
KEY `step_and_order` (`workflows_id`, `step_order`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;");
} else {
if (!$DB->fieldExists('glpi_plugin_tasksmanager_workflow_steps', 'description')) {
$DB->doQuery("ALTER TABLE `glpi_plugin_tasksmanager_workflow_steps`
ADD `description` TEXT NULL AFTER `step_order`");
}
// 1.5.0: conditional routing rules (JSON). Empty / null = fall through
// to the next step by step_order (legacy behaviour).
if (!$DB->fieldExists('glpi_plugin_tasksmanager_workflow_steps', 'next_step_rules')) {
$DB->doQuery("ALTER TABLE `glpi_plugin_tasksmanager_workflow_steps`
ADD `next_step_rules` TEXT NULL AFTER `description`");
}
// 1.5.0: else / default target when no rule matches.
// 0 = sequential next step (legacy)
// -1 = end the workflow
// >0 = jump to that step id (forward-only; invalid → fall through)
// Signed INT, because we need -1.
if (!$DB->fieldExists('glpi_plugin_tasksmanager_workflow_steps', 'default_goto_step_id')) {
$DB->doQuery("ALTER TABLE `glpi_plugin_tasksmanager_workflow_steps`
ADD `default_goto_step_id` INT NOT NULL DEFAULT 0 AFTER `next_step_rules`");
}
}
// -------------------------------------------------------
// Table: glpi_plugin_tasksmanager_ticket_workflows
// Active workflow instance linked to a specific ticket
// -------------------------------------------------------
if (!$DB->tableExists('glpi_plugin_tasksmanager_ticket_workflows')) {
$DB->doQuery("CREATE TABLE `glpi_plugin_tasksmanager_ticket_workflows` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`tickets_id` INT UNSIGNED NOT NULL DEFAULT 0,
`workflows_id` INT UNSIGNED NOT NULL DEFAULT 0,
`current_step` INT UNSIGNED NOT NULL DEFAULT 0,
`status` VARCHAR(20) NOT NULL DEFAULT 'active',
`date_creation` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`date_mod` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `tickets_id` (`tickets_id`),
KEY `workflows_id` (`workflows_id`),
KEY `status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;");
}
// -------------------------------------------------------
// Table: glpi_plugin_tasksmanager_pending_workflows
// Holds a desired workflow for a ticket that is awaiting approval.
// Consumed and deleted once the approval is granted.
// -------------------------------------------------------
// -------------------------------------------------------
// Table: glpi_plugin_tasksmanager_workflow_events
// Audit log: every advance / complete / apply / remove with who, when,
// and a JSON details payload (from/to step, group changes, etc.)
// -------------------------------------------------------
if (!$DB->tableExists('glpi_plugin_tasksmanager_workflow_events')) {
$DB->doQuery("CREATE TABLE `glpi_plugin_tasksmanager_workflow_events` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`tickets_id` INT UNSIGNED NOT NULL DEFAULT 0,
`workflows_id` INT UNSIGNED NOT NULL DEFAULT 0,
`ticket_workflows_id` INT UNSIGNED NOT NULL DEFAULT 0,
`step_order` INT UNSIGNED NULL DEFAULT NULL,
`event_type` VARCHAR(40) NOT NULL,
`users_id` INT UNSIGNED NOT NULL DEFAULT 0,
`details` TEXT NULL,
`date_creation` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `tickets_id` (`tickets_id`),
KEY `workflows_id` (`workflows_id`),
KEY `ticket_workflows_id` (`ticket_workflows_id`),
KEY `event_type` (`event_type`),
KEY `date_creation` (`date_creation`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;");
}
if (!$DB->tableExists('glpi_plugin_tasksmanager_pending_workflows')) {
$DB->doQuery("CREATE TABLE `glpi_plugin_tasksmanager_pending_workflows` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`tickets_id` INT UNSIGNED NOT NULL,
`workflows_id` INT UNSIGNED NOT NULL,
`date_creation` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `tickets_id` (`tickets_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;");
}
// Create plugin document directory
$plugin_doc_dir = GLPI_PLUGIN_DOC_DIR . '/tasksmanager';
if (!is_dir($plugin_doc_dir)) {
mkdir($plugin_doc_dir, 0755, true);
}
// Register plugin rights and grant them to super-admin
\GlpiPlugin\Tasksmanager\Profile::install();
return true;
}
/**
* Uninstall hook - remove database tables and files
*
* @return bool
*/
function plugin_tasksmanager_uninstall(): bool
{
global $DB;
$tables = [
'glpi_plugin_tasksmanager_workflow_events',
'glpi_plugin_tasksmanager_pending_workflows',
'glpi_plugin_tasksmanager_ticket_workflows',
'glpi_plugin_tasksmanager_workflow_steps',
'glpi_plugin_tasksmanager_workflows',
'glpi_plugin_tasksmanager_taskstates',
'glpi_plugin_tasksmanager_configs',
];
foreach ($tables as $table) {
if ($DB->tableExists($table)) {
$DB->doQuery("DROP TABLE `$table`");
}
}
$plugin_doc_dir = GLPI_PLUGIN_DOC_DIR . '/tasksmanager';
if (is_dir($plugin_doc_dir)) {
Toolbox::deleteDir($plugin_doc_dir);
}
// Drop plugin rights from every profile
\GlpiPlugin\Tasksmanager\Profile::uninstall();
return true;
}
// -------------------------------------------------------
// Hook callbacks for ticket task events
// -------------------------------------------------------
/**
* Callback when a Ticket is added.
* - No approval required → apply the workflow immediately.
* - Approval required → store in pending_workflows; applied when approval is granted.
*/
function plugin_tasksmanager_ticket_add(Ticket $item): void
{
$workflows_id = (int)($item->input['_plugin_tasksmanager_workflows_id'] ?? 0);
if (!$workflows_id) {
return;
}
global $DB;
$tickets_id = $item->getID();
// Store pending record (consumed by ticket_update when approval is granted)
$DB->insert('glpi_plugin_tasksmanager_pending_workflows', [
'tickets_id' => $tickets_id,
'workflows_id' => $workflows_id,
]);
// Decide: apply now vs. wait for approval.
//
// $item->fields['global_validation'] can be stale here — when the ticket
// is created via a Forms destination with ValidationField, the validation
// request is created in post_addItem and the parent ticket's
// global_validation may not yet reflect WAITING by the time our hook
// runs. Three checks to be safe:
// 1. Re-read global_validation directly from the DB.
// 2. Count waiting TicketValidation rows (the request itself).
// 3. Look at the prepared input for a `_validation` payload that
// Forms uses to schedule validations.
// Any one of them indicating "approval needed" defers the apply.
$validation_status = \CommonITILValidation::NONE;
$reread = $DB->request([
'SELECT' => ['global_validation'],
'FROM' => 'glpi_tickets',
'WHERE' => ['id' => $tickets_id],
'LIMIT' => 1,
]);
if (count($reread) > 0) {
$validation_status = (int)($reread->current()['global_validation'] ?? \CommonITILValidation::NONE);
}
$pending_validations = 0;
if ($DB->tableExists('glpi_ticketvalidations')) {
$pv = $DB->request([
'COUNT' => 'cnt',
'FROM' => 'glpi_ticketvalidations',
'WHERE' => ['tickets_id' => $tickets_id, 'status' => \CommonITILValidation::WAITING],
]);
if (count($pv) > 0) {
$pending_validations = (int)$pv->current()['cnt'];
}
}
// Permissive check: any input key whose name contains "validation" /
// "approval" is a strong hint that an approval request is being set up.
// This catches GLPI 11 Forms (`_validation_targets`), legacy
// (`_add_validation`), and any future / plugin-added keys we don't
// know about yet.
$validation_keys_seen = [];
foreach (array_keys((array)($item->input ?? [])) as $k) {
$lk = strtolower((string)$k);
if (str_contains($lk, 'validation') || str_contains($lk, 'approval')) {
// Only treat as a signal when the value is non-empty (Forms
// sets `_add_validation = 0` as an unconditional marker).
$val = $item->input[$k] ?? null;
if (!empty($val)) {
$validation_keys_seen[] = $k;
}
}
}
$input_has_validation = !empty($validation_keys_seen);
$needs_approval = $validation_status !== \CommonITILValidation::NONE
|| $pending_validations > 0
|| $input_has_validation;
// Audit: record the full diagnostic so we can see *exactly* which
// signals fired (or didn't) for this ticket. The `input_keys` snapshot
// is invaluable when a ticket created via a form path we didn't
// anticipate slips through the gate.
\GlpiPlugin\Tasksmanager\Workflow::logEvent(
$needs_approval ? 'workflow_pending' : 'workflow_applied_immediate',
$tickets_id,
$workflows_id,
0,
null,
[
'global_validation' => $validation_status,
'pending_validations' => $pending_validations,
'input_has_validation' => $input_has_validation,
'validation_keys_seen' => $validation_keys_seen,
'input_keys' => array_keys((array)($item->input ?? [])),
'decision' => $needs_approval ? 'defer' : 'apply',
]
);
if (!$needs_approval) {
plugin_tasksmanager_apply_pending_workflow($tickets_id);
}
// Otherwise leave the pending record — plugin_tasksmanager_ticket_update
// will consume it when global_validation transitions to ACCEPTED.
// Belt-and-suspenders: ALSO register a shutdown-time check. By the time
// PHP shuts down for this request, all Forms destination processing
// (including ValidationField → TicketValidation row inserts and the
// parent's global_validation update) has completed. If the synchronous
// checks above all returned "no approval needed" for a ticket that
// actually did get a validation set up later in post-add, the
// shutdown re-check will be authoritative.
//
// Safe to run alongside the synchronous apply because
// Workflow::applyToTicket() refuses to create a second active workflow.
register_shutdown_function('plugin_tasksmanager_recheck_pending_apply', $tickets_id);
}
/**
* End-of-request safety net. Runs after PHP shutdown, when all post-add
* processing is durable in the DB. Reads the live state and:
* - applies the pending workflow if no approval is pending and one isn't
* already active, or
* - leaves the pending record alone if an approval is now visible (the
* ticket_update hook will pick it up on ACCEPT)
*/
function plugin_tasksmanager_recheck_pending_apply(int $tickets_id): void
{
global $DB;
if (!$DB || !$tickets_id) {
return;
}
// Pending record still there?
$pending = $DB->request([
'FROM' => 'glpi_plugin_tasksmanager_pending_workflows',
'WHERE' => ['tickets_id' => $tickets_id],
'LIMIT' => 1,
]);
if (count($pending) === 0) {
return; // Already consumed (or never existed)
}
// Already has an active workflow?
$active = $DB->request([
'FROM' => 'glpi_plugin_tasksmanager_ticket_workflows',
'WHERE' => ['tickets_id' => $tickets_id, 'status' => 'active'],
'LIMIT' => 1,
]);
if (count($active) > 0) {
return; // Workflow already running — nothing to do
}
// Final authoritative read of validation state.
$gv = \CommonITILValidation::NONE;
$row = $DB->request([
'SELECT' => ['global_validation'],
'FROM' => 'glpi_tickets',
'WHERE' => ['id' => $tickets_id],
'LIMIT' => 1,
]);
if (count($row) > 0) {
$gv = (int)($row->current()['global_validation'] ?? \CommonITILValidation::NONE);
}
$waiting = 0;
if ($DB->tableExists('glpi_ticketvalidations')) {
$pv = $DB->request([
'COUNT' => 'cnt',
'FROM' => 'glpi_ticketvalidations',
'WHERE' => ['tickets_id' => $tickets_id, 'status' => \CommonITILValidation::WAITING],
]);
if (count($pv) > 0) {
$waiting = (int)$pv->current()['cnt'];
}
}
$needs_approval = $gv !== \CommonITILValidation::NONE || $waiting > 0;
// Audit the shutdown-time decision so a divergence from the
// synchronous check is visible in the History card.
$row_pending = $pending->current();
$workflows_id = (int)($row_pending['workflows_id'] ?? 0);
\GlpiPlugin\Tasksmanager\Workflow::logEvent(
$needs_approval ? 'workflow_pending_recheck' : 'workflow_applied_recheck',
$tickets_id,
$workflows_id,
0,
null,
[
'global_validation_at_shutdown' => $gv,
'waiting_validations_at_shutdown'=> $waiting,
'decision' => $needs_approval ? 'defer' : 'apply',
]
);
if (!$needs_approval) {
plugin_tasksmanager_apply_pending_workflow($tickets_id);
}
}
/**
* Callback when a Ticket is updated.
* Applies the pending workflow as soon as global_validation changes to ACCEPTED.
*/
function plugin_tasksmanager_ticket_update(Ticket $item): void
{
if (!array_key_exists('global_validation', $item->oldvalues ?? [])) {
return;
}
if ((int)$item->fields['global_validation'] !== \CommonITILValidation::ACCEPTED) {
return;
}
plugin_tasksmanager_apply_pending_workflow($item->getID());
}
/**
* Consume a pending workflow record and apply it to the ticket.
*/
function plugin_tasksmanager_apply_pending_workflow(int $tickets_id): void
{
global $DB;
$iter = $DB->request([
'FROM' => 'glpi_plugin_tasksmanager_pending_workflows',
'WHERE' => ['tickets_id' => $tickets_id],
'LIMIT' => 1,
]);
if (count($iter) === 0) {
return;
}
$row = $iter->current();
$DB->delete('glpi_plugin_tasksmanager_pending_workflows', ['tickets_id' => $tickets_id]);
\GlpiPlugin\Tasksmanager\Workflow::applyToTicket($tickets_id, (int)$row['workflows_id']);
}
/**
* Callback when a TicketTask is added — create a basic taskstate record.
*/
function plugin_tasksmanager_item_add(TicketTask $item): void
{
global $DB;
// Skip if a taskstate was already created by the workflow engine
$existing = $DB->request([
'FROM' => 'glpi_plugin_tasksmanager_taskstates',
'WHERE' => ['tickettasks_id' => $item->getID()],
'LIMIT' => 1,
]);
if (count($existing) > 0) {
return;
}
$DB->insert('glpi_plugin_tasksmanager_taskstates', [
'tickets_id' => $item->fields['tickets_id'],
'tickettasks_id' => $item->getID(),
'plugin_status' => 'pending',
'priority' => 3,
'date_creation' => date('Y-m-d H:i:s'),
]);
}
/**
* Callback when a TicketTask is updated.
* When a task is marked done (state=2) and it belongs to a workflow step,
* this automatically creates the next step's task on the ticket and replaces
* the ticket's ASSIGN actors with the new task's template tech/group.
* Paired with js/workflow-refresh.js which reloads the page after the inline
* checkbox XHR succeeds, so the user can't click Save with stale form data.
*/
function plugin_tasksmanager_item_update(TicketTask $item): void
{
global $DB;
// Skip auto-advance when an admin action (Skip / Restart) is in progress
// — that action marks the task Done itself and drives the advance, so
// letting this hook also advance produces a duplicate step.
if (\GlpiPlugin\Tasksmanager\Workflow::$suppressAutoAdvance) {
return;
}
// Only act when state is explicitly being set to 2 in this specific update.
// Do NOT fall back to $item->fields['state']: that would fire again on a
// ticket Save that re-submits the task when it is already done.
if (!isset($item->input['state']) || (int)$item->input['state'] !== 2) {
return;
}
// Sync our internal status tracking for the dashboard
$DB->update(
'glpi_plugin_tasksmanager_taskstates',
['plugin_status' => 'done', 'progress' => 100],
['tickettasks_id' => $item->getID()]
);
// Check whether this task belongs to an active workflow step
$taskstate_iter = $DB->request([
'FROM' => 'glpi_plugin_tasksmanager_taskstates',
'WHERE' => [
'tickettasks_id' => $item->getID(),
'ticket_workflows_id' => ['>', 0],
],
'LIMIT' => 1,
]);
if (count($taskstate_iter) === 0) {
return;
}
$taskstate = $taskstate_iter->current();
$ticket_workflows_id = (int)$taskstate['ticket_workflows_id'];
$current_step_order = (int)$taskstate['workflow_step_order'];
// Load the ticket workflow record and verify it is still active
$tw_iter = $DB->request([
'FROM' => 'glpi_plugin_tasksmanager_ticket_workflows',
'WHERE' => ['id' => $ticket_workflows_id, 'status' => 'active'],
'LIMIT' => 1,
]);
if (count($tw_iter) === 0) {
return;
}
$ticket_workflow = $tw_iter->current();
$workflows_id = (int)$ticket_workflow['workflows_id'];
$tickets_id = (int)$ticket_workflow['tickets_id'];
// Double-advance guard: if current_step is already past this task's step,
// a prior update has already advanced (e.g. checkbox XHR before a Save).
if ((int)$ticket_workflow['current_step'] > $current_step_order) {
return;
}
// Find the next step — honour conditional routing rules on the current
// step (1.5.0+). Falls back to the sequentially next step when no rule
// matches or no rules are configured. The trace captures the decision
// path for audit logging so you can see *why* a particular step ran.
$routing_trace = [];
$next_step = \GlpiPlugin\Tasksmanager\Workflow::resolveNextStep(
$workflows_id,
$current_step_order,
$tickets_id,
$routing_trace
);
\GlpiPlugin\Tasksmanager\Workflow::logEvent(
'step_routed',
$tickets_id,
$workflows_id,
$ticket_workflows_id,
$current_step_order,
$routing_trace
);
if ($next_step === null) {
// All steps done — mark workflow complete and, if the workflow has a
// groups_id_completion configured, reassign the ticket to that group.
$DB->update(
'glpi_plugin_tasksmanager_ticket_workflows',
['status' => 'completed'],
['id' => $ticket_workflows_id]
);
$completion_group = 0;
$wf_iter = $DB->request([
'FROM' => 'glpi_plugin_tasksmanager_workflows',
'WHERE' => ['id' => $workflows_id],
'LIMIT' => 1,
]);
if (count($wf_iter) > 0) {
$wf = $wf_iter->current();
$completion_group = (int)($wf['groups_id_completion'] ?? 0);
if ($completion_group > 0) {
\GlpiPlugin\Tasksmanager\Workflow::swapAssignActors(
$tickets_id,
0,
$completion_group
);
if (!headers_sent()) {
header('X-TM-Workflow-Advanced: 1');
}
}
}
\GlpiPlugin\Tasksmanager\Workflow::logEvent(
'workflow_completed',
$tickets_id,
$workflows_id,
$ticket_workflows_id,
$current_step_order,
['completion_group' => $completion_group]
);
return;
}
// Only advance current_step if the task was actually created
if (plugin_tasksmanager_apply_workflow_step($tickets_id, $next_step, $ticket_workflows_id)) {
$DB->update(
'glpi_plugin_tasksmanager_ticket_workflows',
['current_step' => $next_step['step_order']],
['id' => $ticket_workflows_id]
);
}
}
/**
* Thin wrapper so legacy callers and the AJAX endpoint can use the class method.
*/
function plugin_tasksmanager_apply_workflow_step(int $tickets_id, array $step, int $ticket_workflows_id): bool
{
return \GlpiPlugin\Tasksmanager\Workflow::applyStep($tickets_id, $step, $ticket_workflows_id);
}