-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathquestiontype.class.php
More file actions
446 lines (381 loc) · 15 KB
/
questiontype.class.php
File metadata and controls
446 lines (381 loc) · 15 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
<?php
/**
* -------------------------------------------------------------------------
* Fields plugin for GLPI
* -------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of Fields.
*
* Fields is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Fields is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Fields. If not, see <http://www.gnu.org/licenses/>.
* -------------------------------------------------------------------------
* @copyright Copyright (C) 2013-2023 by Fields plugin team.
* @license GPLv2 https://www.gnu.org/licenses/gpl-2.0.html
* @link https://github.com/pluginsGLPI/fields
* -------------------------------------------------------------------------
*/
use Glpi\Application\View\TemplateRenderer;
use Glpi\DBAL\JsonFieldInterface;
use Glpi\Form\Condition\ConditionHandler\ItemAsTextConditionHandler;
use Glpi\Form\Condition\ConditionHandler\ItemConditionHandler;
use Glpi\Form\Form;
use Glpi\Form\Migration\FormQuestionDataConverterInterface;
use Glpi\Form\Question;
use Glpi\Form\QuestionType\AbstractQuestionType;
use Glpi\Form\QuestionType\QuestionTypeCategoryInterface;
use function Safe\json_decode;
use function Safe\json_encode;
final class PluginFieldsQuestionType extends AbstractQuestionType implements FormQuestionDataConverterInterface
{
#[Override]
public function getCategory(): QuestionTypeCategoryInterface
{
return new PluginFieldsQuestionTypeCategory();
}
#[Override]
public function getExtraDataConfigClass(): string
{
return PluginFieldsQuestionTypeExtraDataConfig::class;
}
#[Override]
public function getSubTypes(): array
{
return $this->getAvailableBlocks();
}
#[Override]
public function getSubTypeFieldName(): string
{
return 'block_id';
}
#[Override]
public function getSubTypeFieldAriaLabel(): string
{
return __('Select a block');
}
#[Override]
public function getSubTypeDefaultValue(?Question $question): string
{
return (string) $this->getDefaultValueBlockId($question);
}
#[Override]
public function formatDefaultValueForDB(mixed $value): string
{
return json_encode($value);
}
#[Override]
public function validateExtraDataInput(array $input): bool
{
// Check if the block_id is set and is numeric
if (!isset($input['block_id']) || !is_numeric($input['block_id'])) {
return false;
}
// Check if the block_id exists
$available_blocks = $this->getAvailableBlocks();
if (!isset($available_blocks[$input['block_id']])) {
return false;
}
// Check if the field_id is set and is numeric
if (!isset($input['field_id']) || !is_numeric($input['field_id'])) {
return false;
}
// Check if the field_id exists in the selected block
$available_fields = self::getFieldsFromBlock($input['block_id']);
return isset($available_fields[$input['field_id']]);
}
#[Override]
public function renderAdministrationTemplate(?Question $question): string
{
// Get the block_id from the question's extra data or use the first available block
$block_id = $this->getDefaultValueBlockId($question);
if ($block_id === null) {
$block_id = current(array_keys($this->getAvailableBlocks()));
}
$available_fields = self::getFieldsFromBlock($block_id);
// Retrieve current field
$current_field_id = $this->getDefaultValueFieldId($question);
if ($current_field_id === null) {
$current_field_id = current(array_keys($available_fields));
}
$current_field = PluginFieldsField::getById($current_field_id);
// Compute default value for the field
$default_value = null;
if ($question instanceof Question && !empty($question->fields['default_value'])) {
$default_value = json_decode($question->fields['default_value'], true);
}
$twig = TemplateRenderer::getInstance();
return $twig->render('@fields/question_type_administration.html.twig', [
'question' => $question,
'default_value' => $default_value,
'selected_field_id' => $current_field_id,
'available_fields' => $available_fields,
'item' => new Form(),
'field' => $current_field->fields,
]);
}
#[Override]
public function renderEndUserTemplate(Question $question): string
{
// Get the block_id from the question's extra data or use the first available block
$block_id = $this->getDefaultValueBlockId($question);
if ($block_id === null) {
$block_id = current(array_keys($this->getAvailableBlocks()));
}
$available_fields = self::getFieldsFromBlock($block_id);
// Retrieve current field
$current_field_id = $this->getDefaultValueFieldId($question);
if ($current_field_id === null) {
$current_field_id = current(array_keys($available_fields));
}
$current_field = PluginFieldsField::getById($current_field_id);
// Compute default value for the field
$default_value = null;
if (!empty($question->fields['default_value'])) {
$default_value = json_decode($question->fields['default_value'], true);
}
$itemtype = null;
if (str_starts_with((string) $current_field->fields['type'], 'dropdown')) {
if ($current_field->fields['type'] == 'dropdown') {
$itemtype = PluginFieldsDropdown::getClassname($current_field->fields['name']);
} else {
$dropdown_matches = [];
preg_match('/^dropdown-(?<class>.+)$/', (string) $current_field->fields['type'], $dropdown_matches);
$itemtype = $dropdown_matches['class'];
}
}
$twig = TemplateRenderer::getInstance();
return $twig->render('@fields/question_type_end_user.html.twig', [
'question' => $question,
'field' => $current_field->fields,
'default_value' => $default_value,
'item' => new Form(),
'itemtype' => $itemtype,
]);
}
#[Override]
public function formatRawAnswer(mixed $answer, Question $question): string
{
$current_field_id = $this->getDefaultValueFieldId($question);
if ($current_field_id === null) {
throw new LogicException('No field configured for this question');
}
$current_field = PluginFieldsField::getById($current_field_id);
switch ($current_field->fields['type']) {
case 'header':
case 'text':
case 'textarea':
case 'richtext':
case 'number':
case 'url':
case 'date':
return (string) $answer;
case 'dropdown':
$answer = $answer['items_id'];
if (is_string($answer) || is_numeric($answer)) {
$answer = [$answer];
}
$itemtype = PluginFieldsDropdown::getClassname($current_field->fields['name']);
return implode(', ', array_map(fn($opt_id) => $itemtype::getById($opt_id)?->fields['name'] ?? '', $answer));
case 'yesno':
return $answer ? __('Yes') : __('No');
case 'datetime':
return (new DateTime($answer))->format('Y-m-d H:i');
case 'glpi_item':
$itemtype = $answer['itemtype'];
if (!is_a($itemtype, CommonDBTM::class, true)) {
return '';
}
$item = $answer['itemtype']::getById($answer['items_id']);
if (!$item) {
return '';
}
return $item->fields['name'];
}
if (str_starts_with((string) $current_field->fields['type'], 'dropdown-')) {
$itemtype = substr((string) $current_field->fields['type'], strlen('dropdown-'));
if (!getItemForItemtype($itemtype)) {
return '';
}
if (!is_array($answer)) {
$answer = [$answer];
}
$names = [];
foreach ($answer as $items_id) {
$item = $itemtype::getById($items_id);
if ($item) {
$names[] = $item->fields['name'];
}
}
return implode(', ', $names);
}
return (string) $answer;
}
#[Override]
public function beforeConversion(array $rawData): void {}
#[Override]
public function convertDefaultValue(array $rawData): null
{
return null;
}
#[Override]
public function convertExtraData(array $rawData): ?array
{
$values = json_decode($rawData['values'], true);
if (!isset($values['dropdown_fields_field']) || !isset($values['blocks_field'])) {
return null;
}
$block = new PluginFieldsContainer();
if (!$block->getFromDB($values['blocks_field'])) {
return null;
}
$field = new PluginFieldsField();
if (!$field->getFromDBByCrit(['name' => $values['dropdown_fields_field']])) {
return null;
}
return [
'block_id' => $block->getID(),
'field_id' => $field->getID(),
];
}
#[Override]
public function getTargetQuestionType(array $rawData): string
{
return self::class;
}
#[Override]
public function getConditionHandlers(
?JsonFieldInterface $question_config,
): array {
$condition_handlers = parent::getConditionHandlers($question_config);
if (!$question_config instanceof PluginFieldsQuestionTypeExtraDataConfig) {
throw new InvalidArgumentException();
}
if (!$question_config->getFieldId()) {
return parent::getConditionHandlers($question_config);
}
// If the question is configured with a dropdown field, we add condition handlers to handle item and item as text conditions on the dropdown options
$field = PluginFieldsField::getById($question_config->getFieldId());
if ($field && str_starts_with((string) $field->fields['type'], 'dropdown')) {
if ($field->fields['type'] == 'dropdown') {
$itemtype = PluginFieldsDropdown::getClassname($field->fields['name']);
} else {
$dropdown_matches = [];
preg_match('/^dropdown-(?<class>.+)$/', (string) $field->fields['type'], $dropdown_matches);
$itemtype = $dropdown_matches['class'];
}
$condition_handlers = array_merge(
$condition_handlers,
[
new ItemConditionHandler($itemtype),
new ItemAsTextConditionHandler($itemtype),
],
);
}
return $condition_handlers;
}
/**
* Retrieve the default value block from the question's extra data
*
* @param Question|null $question The question to retrieve the default value from
*/
public function getDefaultValueBlockId(?Question $question): ?int
{
if (!$question instanceof Question) {
return null;
}
/** @var ?PluginFieldsQuestionTypeExtraDataConfig $config */
$config = $this->getExtraDataConfig(json_decode($question->fields['extra_data'], true) ?? []);
if ($config === null) {
return null;
}
return $config->getBlockId();
}
/**
* Retrieve the default value field from the question's extra data
*
* @param Question|null $question The question to retrieve the default value from
*/
public function getDefaultValueFieldId(?Question $question): ?int
{
if (!$question instanceof Question) {
return null;
}
/** @var ?PluginFieldsQuestionTypeExtraDataConfig $config */
$config = $this->getExtraDataConfig(json_decode($question->fields['extra_data'], true) ?? []);
if ($config === null) {
return null;
}
return $config->getFieldId();
}
private function getAvailableBlocks(): array
{
$field_container = new PluginFieldsContainer();
$available_blocks = [];
$entity_restrict = isCommandLine() ? [] : getEntitiesRestrictCriteria(PluginFieldsContainer::getTable(), '', '', true);
// If entity restriction contains an empty string value, it means no valid session
// is active. Running the query would produce a MySQL
// warning (1292: Truncated incorrect DECIMAL value)
foreach ($entity_restrict as $criterion) {
if (is_array($criterion) && in_array('', $criterion, true)) {
return $available_blocks;
}
}
$result = $field_container->find([
'is_active' => 1,
'type' => 'dom',
'OR' => [
['itemtypes' => ['LIKE', '%\"Ticket\"%']],
['itemtypes' => ['LIKE', '%\"Change\"%']],
['itemtypes' => ['LIKE', '%\"Problem\"%']],
],
] + $entity_restrict, 'name');
foreach ($result as $id => $data) {
$available_blocks[$id] = $data['label'];
}
return $available_blocks;
}
public static function getFieldsFromBlock(?int $block_id): array
{
$fields = [];
$field_container = PluginFieldsContainer::getById($block_id);
if ($field_container) {
$field = new PluginFieldsField();
$result = $field->find([
'is_active' => 1,
'plugin_fields_containers_id' => $block_id,
'NOT' => [
['type' => 'header'], // Exclude headers
],
]);
foreach ($result as $id => $data) {
$fields[$id] = $data['label'];
}
}
return $fields;
}
/**
* Check if there is at least one available field in the available blocks
*/
public static function hasAvailableFields(): bool
{
$blocks = (new self())->getAvailableBlocks();
foreach (array_keys($blocks) as $block_id) {
$fields = (new self())->getFieldsFromBlock($block_id);
if ($fields !== []) {
return true;
}
}
return false;
}
}