/
formanswer.class.php
2124 lines (1894 loc) · 73 KB
/
formanswer.class.php
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
/**
* ---------------------------------------------------------------------
* Formcreator is a plugin which allows creation of custom forms of
* easy access.
* ---------------------------------------------------------------------
* LICENSE
*
* This file is part of Formcreator.
*
* Formcreator 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.
*
* Formcreator 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 Formcreator. If not, see <http://www.gnu.org/licenses/>.
* ---------------------------------------------------------------------
* @copyright Copyright © 2011 - 2021 Teclib'
* @license http://www.gnu.org/licenses/gpl.txt GPLv3+
* @link https://github.com/pluginsGLPI/formcreator/
* @link https://pluginsglpi.github.io/formcreator/
* @link http://plugins.glpi-project.org/#/plugin/formcreatorp@
* ---------------------------------------------------------------------
*/
use Glpi\Application\View\TemplateRenderer;
use Glpi\Toolbox\Sanitizer;
use GlpiPlugin\Formcreator\Field\DropdownField;
use Glpi\Application\ErrorHandler;
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access this file directly");
}
class PluginFormcreatorFormAnswer extends CommonDBTM
{
public $dohistory = true;
public $usenotepad = true;
public $usenotepadrights = true;
protected static $showTitleInNavigationHeader = true;
/**
* Generated targets after creation of a form answer
* Populated only after creation of a FormAnswer in DB with add() method
*
* @var array
*/
public $targetList = [];
const SOPTION_ANSWER = 900000;
// Values choosen to not conflict with status of ticket constants
// @see PluginFormcreatorIssue::getNewStatusArray
const STATUS_WAITING = 101;
const STATUS_REFUSED = 102;
const STATUS_ACCEPTED = 103;
/** @var null|PluginFormcreatorAbstractField[] fields of the form answers */
private $questionFields = null;
/** @var boolean True if the answers are loaded and are valid */
private $isAnswersValid = false;
/** @var PluginFormcreatorForm $form The form attached to the object */
private $form = null;
/** @var array $answers set of answers */
private array $answers = [];
public static function getStatuses() {
return [
self::STATUS_WAITING => __('Waiting', 'formcreator'),
self::STATUS_REFUSED => __('Refused', 'formcreator'),
self::STATUS_ACCEPTED => __('Accepted', 'formcreator'),
];
}
/**
* Check if current user have the right to create and modify requests
*
* @return boolean True if he can create and modify requests
*/
public static function canCreate() {
return true;
}
/**
* Check if current user have the right to read requests
*
* @return boolean True if he can read requests
*/
public static function canView() {
return true;
}
public function canViewItem() {
global $DB;
if (Plugin::isPluginActive(PLUGIN_FORMCREATOR_ADVANCED_VALIDATION)) {
$advFormAnswer = new PluginAdvformFormanswer();
$advFormAnswer->getFromDB($this->getID());
return $advFormAnswer->canViewItem();
}
$currentUser = Session::getLoginUserID();
if ($currentUser === false) {
return false;
}
if (Session::haveRight('entity', UPDATE)) {
return true;
}
if ($currentUser == $this->fields['requester_id']) {
return true;
}
if ($currentUser == $this->fields['users_id_validator']) {
return true;
}
$groupUser = new Group_User();
$groups = $groupUser->getUserGroups($currentUser);
foreach ($groups as $group) {
if ($this->fields['groups_id_validator'] == $group['id']) {
return true;
}
}
$request = [
'SELECT' => PluginFormcreatorForm_Validator::getTable() . '.*',
'FROM' => $this::getTable(),
'INNER JOIN' => [
PluginFormcreatorForm::getTable() => [
'FKEY' => [
PluginFormcreatorForm::getTable() => PluginFormcreatorForm::getIndexName(),
$this::getTable() => PluginFormcreatorForm::getForeignKeyField(),
],
],
PluginFormcreatorForm_Validator::getTable() => [
'FKEY' => [
PluginFormcreatorForm::getTable() => PluginFormcreatorForm::getIndexName(),
PluginFormcreatorForm_Validator::getTable() => PluginFormcreatorForm::getForeignKeyField()
]
]
],
'WHERE' => [$this::getTable() . '.id' => $this->getID()],
];
foreach ($DB->request($request) as $row) {
if ($row['itemtype'] == User::class) {
if ($currentUser == $row['items_id']) {
return true;
}
} else {
foreach ($groups as $group) {
if ($group['id'] == $row['items_id']) {
return true;
}
}
}
}
// Check if the current user is a requester of a ticket linked to a form answer typed
// Matches search option 42, 43 and 44 of PluginFormcreatorIssue (requester, watcher, assigned)
$ticket_table = Ticket::getTable();
$ticket_user_table = Ticket_User::getTable();
$item_ticket_table = Item_Ticket::getTable();
$request = [
'SELECT' => [
Ticket_User::getTableField(User::getForeignKeyField()),
Ticket::getTableField('id'),
],
'FROM' => $ticket_user_table,
'INNER JOIN' => [
$ticket_table => [
'FKEY' => [
$ticket_table => 'id',
$ticket_user_table => 'tickets_id',
['AND' => [
Ticket_User::getTableField(User::getForeignKeyField()) => $currentUser,
]],
],
],
$item_ticket_table => [
'FKEY' => [
$item_ticket_table => 'tickets_id',
$ticket_table => 'id',
['AND' => [
Item_Ticket::getTableField('itemtype') => self::getType(),
Item_Ticket::getTableField('items_id') => $this->getID(),
]],
],
],
]
];
if ($DB->request($request)->count() > 0) {
return true;
}
return false;
}
public static function canPurge() {
return true;
}
public function canPurgeItem() {
return Session::haveRight('entity', UPDATE);
}
/**
* Returns the type name with consideration of plural
*
* @param number $nb Number of item(s)
* @return string Itemtype name
*/
public static function getTypeName($nb = 0) {
return _n('Form answer', 'Form answers', $nb, 'formcreator');
}
public function rawSearchOptions() {
global $DB;
$tab = parent::rawSearchOptions();
$display_for_form = isset($_SESSION['formcreator']['form_search_answers'])
&& $_SESSION['formcreator']['form_search_answers'];
$tab[] = [
'id' => '2',
'table' => $this::getTable(),
'field' => 'id',
'name' => __('ID'),
'searchtype' => 'contains',
'datatype' => 'itemlink',
'massiveaction' => false
];
$tab[] = [
'id' => '3',
'table' => 'glpi_plugin_formcreator_forms',
'field' => 'name',
'name' => PluginFormcreatorForm::getTypeName(1),
'datatype' => 'dropdown',
'massiveaction' => false
];
$tab[] = [
'id' => '4',
'table' => 'glpi_users',
'field' => 'name',
'name' => _n('Requester', 'Requesters', 1),
'datatype' => 'itemlink',
'massiveaction' => false,
'linkfield' => 'requester_id'
];
$tab[] = [
'id' => '5',
'table' => User::getTable(),
'field' => 'name',
'name' => __('Form approver', 'formcreator'),
'datatype' => 'itemlink',
'forcegroupby' => true,
'massiveaction' => false,
'linkfield' => 'users_id_validator',
];
$tab[] = [
'id' => '6',
'table' => $this::getTable(),
'field' => 'request_date',
'name' => __('Creation date'),
'datatype' => 'datetime',
'massiveaction' => false
];
$tab[] = [
'id' => '7',
'table' => Group::getTable(),
'field' => 'completename',
'name' => __('Form approver group', 'formcreator'),
'datatype' => 'itemlink',
'forcegroupby' => true,
'massiveaction' => false,
'linkfield' => 'groups_id_validator',
];
$tab[] = [
'id' => '8',
'table' => $this::getTable(),
'field' => 'status',
'name' => __('Status'),
'searchtype' => [
'0' => 'equals',
'1' => 'notequals'
],
'datatype' => 'specific',
'massiveaction' => false
];
$tab[] = [
'id' => '9',
'table' => PluginFormcreatorForm::getTable(),
'field' => 'id',
'name' => __('ID'),
'searchtype' => 'contains',
'datatype' => 'integer',
'massiveaction' => false,
];
if ($display_for_form) {
$optindex = self::SOPTION_ANSWER;
$question = new PluginFormcreatorQuestion;
$questions = $question->getQuestionsFromForm($_SESSION['formcreator']['form_search_answers']);
foreach ($questions as $current_question) {
$questions_id = $current_question->getID();
$tab[] = [
'id' => $optindex,
'table' => PluginFormcreatorAnswer::getTable(),
'field' => 'answer',
'name' => $current_question->fields['name'],
'datatype' => 'string',
'massiveaction' => false,
'nosearch' => false,
'joinparams' => [
'jointype' => 'child',
'condition' => "AND NEWTABLE.`plugin_formcreator_questions_id` = $questions_id",
]
];
$optindex++;
}
}
return $tab;
}
/**
* Define how to display a specific value in search result table
*
* @param String $field Name of the field as define in $this->getSearchOptions()
* @param Mixed $values The value as it is stored in DB
* @param Array $options Options (optional)
* @return Mixed Value to be displayed
*/
public static function getSpecificValueToDisplay($field, $values, array $options = []) {
if (!is_array($values)) {
$values = [$field => $values];
}
switch ($field) {
case 'status' :
if (!isAPI()) {
switch ($values[$field]) {
case PluginFormcreatorFormAnswer::STATUS_WAITING:
$status = CommonITILObject::WAITING;
break;
case PluginFormcreatorFormAnswer::STATUS_REFUSED:
$status = Change::REFUSED;
break;
case PluginFormcreatorFormAnswer::STATUS_ACCEPTED:
$status = CommonITILObject::ACCEPTED;
break;
default:
$status = $values[$field];
}
$status = CommonITILObject::getStatusClass($status);
return '<i class="'.$status.'"></i>';
}
break;
}
return parent::getSpecificValueToDisplay($field, $values, $options);
}
/**
* Define how to display search field for a specific type
*
* @since version 0.84
*
* @param String $field Name of the field as define in $this->getSearchOptions()
* @param String $name Name attribute for the field to be posted (default '')
* @param Array $values Array of all values to display in search engine (default '')
* @param Array $options Options (optional)
*
* @return String Html string to be displayed for the form field
*/
public static function getSpecificValueToSelect($field, $name = '', $values = '', array $options = []) {
if (!is_array($values)) {
$values = [$field => $values];
}
$options['display'] = false;
switch ($field) {
case 'status' :
$elements = self::getStatuses();
$output = Dropdown::showFromArray($name, $elements, ['display' => false, 'value' => $values[$field]]);
return $output;
break;
}
return parent::getSpecificValueToSelect($field, $name, $values, $options);
}
/**
* Display a list of all forms on the configuration page
*
* @param CommonGLPI $item Instance of a CommonGLPI Item (The Config Item)
* @param integer $tabnum Number of the current tab
* @param integer $withtemplate
*
* @see CommonDBTM::displayTabContentForItem
*
* @return null Nothing, just display the list
*/
public static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0) {
if ($item instanceof PluginFormcreatorForm) {
self::showForForm($item);
} else {
$item->showForm($item->fields['id']);
}
}
public function defineTabs($options = []) {
$ong = [];
$this->addDefaultFormTab($ong);
if ($this->fields['id'] > 0) {
$this->addStandardTab(Ticket::class, $ong, $options);
$this->addStandardTab(Document_Item::class, $ong, $options);
$this->addStandardTab(Notepad::class, $ong, $options);
$this->addStandardTab(Log::class, $ong, $options);
}
return $ong;
}
/**
* Return the name of the tab for item including forms like the config page
*
* @param CommonGLPI $item Instance of a CommonGLPI Item (The Config Item)
* @param integer $withtemplate
*
* @return String Name to be displayed
*/
public function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) {
if ($item instanceof PluginFormcreatorForm) {
$dbUtils = new DbUtils();
$formFk = PluginFormcreatorForm::getForeignKeyField();
$number = $dbUtils->countElementsInTableForMyEntities(
static::getTable(),
[
$formFk => $item->getID(),
]
);
return self::createTabEntry(self::getTypeName($number), $number);
} else {
return $this->getTypeName();
}
}
static function showForForm(PluginFormcreatorForm $form, $params = []) {
global $DB;
$table = self::getTable();
$form_table = PluginFormcreatorForm::getTable();
$form_fk = PluginFormcreatorForm::getForeignKeyField();
$user_table = User::getTable();
if (version_compare(GLPI_VERSION, '10.0.5') >= 0) {
$userQueryExpression = User::getFriendlyNameFields('requester_name');
} else {
// Drop this alternative when the plugin requires GLPI 10.0.5+
$alias = 'requester_name';
$config = Config::getConfigurationValues('core');
if ($config['names_format'] == User::FIRSTNAME_BEFORE) {
$first = "firstname";
$second = "realname";
} else {
$first = "realname";
$second = "firstname";
}
$first = DBmysql::quoteName("$user_table.$first");
$second = DBmysql::quoteName("$user_table.$second");
$alias = DBmysql::quoteName($alias);
$name = DBmysql::quoteName($user_table . '.' . self::getNameField());
$userQueryExpression = new QueryExpression("IF(
$first <> '' && $second <> '',
CONCAT($first, ' ', $second),
$name
) AS $alias");
}
$result = $DB->request([
'SELECT' => [
$table => [
'id',
'name',
'requester_id',
'users_id_validator',
'request_date'
],
$form_table => [
'name as form_name'
],
$userQueryExpression
],
'FROM' => self::getTable(),
'INNER JOIN' => [
$form_table => [
'FKEY' => [
$form_table => 'id',
$table => $form_fk,
],
],
],
'LEFT JOIN' => [
$user_table => [
'FKEY' => [
$user_table => 'id',
$table => 'requester_id',
],
],
],
'WHERE' => [
$table . '.' . $form_fk => $form->getID(),
],
'LIMIT' => 20,
'ORDER' => [
'request_date DESC',
],
]);
$total_count = count($result);
TemplateRenderer::getInstance()->display('@formcreator/pages/form.formanswer.html.twig', [
'form' => $form,
'form_answers' => $result,
'total_count' => $total_count,
]);
}
/**
* Can the current user validate the form ?
*/
public function canValidate(): bool {
if (Plugin::isPluginActive(PLUGIN_FORMCREATOR_ADVANCED_VALIDATION)) {
$formAnswer = new PluginAdvformFormAnswer();
$formAnswer->getFromDB($this->getID());
return $formAnswer->canValidate($this);
}
if (!PluginFormcreatorCommon::canValidate()) {
return false;
}
$form = $this->getForm();
switch ($form->fields['validation_required']) {
case PluginFormcreatorForm_Validator::VALIDATION_USER:
return (Session::getLoginUserID() == $this->fields['users_id_validator']);
break;
case PluginFormcreatorForm_Validator::VALIDATION_GROUP:
$groupList = Group_User::getUserGroups(
Session::getLoginUserID(),
['glpi_groups.id' => $this->fields['groups_id_validator']]
);
return (count($groupList) > 0);
break;
}
return false;
}
public function showForm($ID, $options = []) {
if (!isset($ID) || !$this->getFromDB($ID)) {
Html::displayNotFoundError();
}
$options['canedit'] = false;
// Print css media
echo Html::css(FORMCREATOR_ROOTDOC . "/css/print_form.css", ['media' => 'print']);
$style = "<style>";
// force colums width
$width_percent = 100 / PluginFormcreatorSection::COLUMNS;
for ($i = 0; $i < PluginFormcreatorSection::COLUMNS; $i++) {
$width = ($i+1) * $width_percent;
$style.= '
#plugin_formcreator_form.plugin_formcreator_form [data-itemtype = "PluginFormcreatorQuestion"][gs-w="' . ($i+1) . '"],
#plugin_formcreator_form.plugin_formcreator_form .plugin_formcreator_gap[gs-w="' . ($i+1) . '"]
{
min-width: ' . $width_percent . '%;
width: ' . $width . '%;
}
';
}
$style.= "</style>";
echo $style;
$formUrl = static::getFormURL(); // May be called from iinherited classes
$formName = 'plugin_formcreator_form';
echo '<form name="' . $formName . '" method="post" role="form" enctype="multipart/form-data"'
. ' class="plugin_formcreator_form"'
. ' action="' . $formUrl . '"'
. ' id="plugin_formcreator_form"'
. '>';
$form = $this->getForm();
// Edit mode for validator
$editMode = !isset($options['edit']) ? false : ($options['edit'] != '0');
// form title
if (version_compare(GLPI_VERSION, '10.0.3') < 0) {
echo "<h1 class='form-title'>";
echo $this->fields['name'] . " ";
echo '<i class="pointer print_button fas fa-print" title="' . __("Print this form", 'formcreator') . '" onclick="window.print();"></i>';
echo '</h1>';
}
// Form Header
if (!empty($form->fields['content']) || !empty($form->getExtraHeader())) {
echo '<div class="form_header">';
echo html_entity_decode($form->fields['content']);
echo html_entity_decode($form->getExtraHeader());
echo '</div>';
}
// Validation status and comment
if ($this->fields['status'] == self::STATUS_REFUSED) {
echo '<div class="refused_header">';
echo '<strong>' . __('Comment', 'formcreator') . '</strong>';
echo '<div>' . nl2br($this->fields['comment']) .'</div>';
echo '</div>';
} else if ($this->fields['status'] == self::STATUS_ACCEPTED) {
echo '<div class="accepted_header">';
echo '<div>';
if (!empty($this->fields['comment'])) {
echo '<strong>' . __('Comment', 'formcreator') . '</strong>';
echo nl2br($this->fields['comment']);
} else if ($form->validationRequired()) {
echo __('Form accepted by validator.', 'formcreator');
} else {
echo __('Form successfully saved.', 'formcreator');
}
echo '</div>';
echo '</div>';
}
echo '<ol>';
$domain = PluginFormcreatorForm::getTranslationDomain($form->getID());
// Get fields populated with answers
$this->loadAnswers();
$this->answers['plugin_formcreator_forms_id'] = $form->getID();
$visibility = PluginFormcreatorFields::updateVisibility($this->answers);
$sections = (new PluginFormcreatorSection)->getSectionsFromForm($form->getID());
foreach ($sections as $section) {
$sectionId = $section->getID();
// Section header
$hiddenAttribute = $visibility[$section->getType()][$sectionId] ? '' : 'hidden=""';
echo '<li'
. ' class="plugin_formcreator_section"'
. ' data-itemtype="' . PluginFormcreatorSection::class . '"'
. ' data-id="' . $sectionId . '"'
. " $hiddenAttribute"
. '">';
// section name
echo '<h2>';
echo empty($section->fields['name']) ? '(' . $sectionId . ')' : $section->fields['name'];
echo '</h2>';
// Section content
echo '<div>';
// Display all fields of the section
$lastQuestion = null;
$questions = (new PluginFormcreatorQuestion)->getQuestionsFromSection($sectionId);
foreach ($questions as $question) {
if ($lastQuestion !== null) {
if ($lastQuestion->fields['row'] < $question->fields['row']) {
// the question begins a new line
echo '<div class="plugin_formcreator_newRow"></div>';
} else {
$x = $lastQuestion->fields['col'] + $lastQuestion->fields['width'];
$width = $question->fields['col'] - $x;
if ($x < $question->fields['col']) {
// there is an horizontal gap between previous question and current one
echo '<div class="plugin_formcreator_gap" gs-x="' . $x . '" gs-w="' . $width . '"></div>';
}
}
}
echo $question->getRenderedHtml($domain, $editMode, $this, $visibility[$question->getType()][$question->getID()]);
$lastQuestion = $question;
}
echo '</div>';
echo '</li>';
}
//add requester info
echo '<div class="form-group">';
echo '<label for="requester">' . _n('Requester', 'Requesters', 1) . '</label>';
echo Dropdown::getDropdownName('glpi_users', $this->fields['requester_id']);
echo '</div>';
// Display submit button
if (($this->fields['status'] == self::STATUS_REFUSED) && (Session::getLoginUserID() == $this->fields['requester_id'])) {
echo '<div class="form-group">';
echo '<div class="center">';
echo Html::submit(__('Save'), ['name' => 'save_formanswer']);
echo '</div>';
echo '</div>';
} else if (($this->fields['status'] == self::STATUS_WAITING) && $this->canValidate()) {
// Display validation form
echo '<div class="form-group required line1">';
echo '<label for="comment">' . __('Comment', 'formcreator') . ' <span class="red">*</span></label>';
Html::textarea([
'name' => 'comment',
'value' => $this->fields['comment']
]);
echo '<div class="help-block">' . __('Required if refused', 'formcreator') . '</div>';
echo '</div>';
echo '<div class="form-group line1">';
echo '<div class="center" style="float: left; width: 30%;">';
echo Html::submit(
__('Refuse', 'formcreator'), [
'name' => 'refuse_formanswer',
'onclick' => 'return plugin_formcreator_checkComment(this)',
]);
echo '</div>';
echo '<div class="center" style="float: left; width: 40%;">';
if (!$editMode) {
echo Html::submit(
__('Edit answers', 'formcreator'), [
'name' => 'edit_answers',
'onclick' => 'reloadTab("edit=1"); return false;',
]);
} else {
echo Html::submit(
__('Cancel edition', 'formcreator'), [
'name' => 'edit_answers',
'onclick' => 'reloadTab("edit=0"); return false;',
]);
}
echo '</div>'; echo '<div class="center">';
echo Html::submit(
__('Accept', 'formcreator'), [
'name' => 'accept_formanswer',
]);
echo '</div>';
echo '</div>';
}
if (Plugin::isPluginActive(PLUGIN_FORMCREATOR_ADVANCED_VALIDATION)) {
$formAnswer = PluginFormcreatorCommon::getFormAnswer();
$formAnswer->getFromDB($this->getID());
PluginAdvformFormanswerValidation::showValidationStatuses($formAnswer);
}
$options['canedit'] = true;
$options['candel'] = false;
echo Html::hidden('plugin_formcreator_forms_id', ['value' => $form->getID()]);
echo Html::hidden('id', ['value' => $this->getID()]);
echo Html::hidden('_glpi_csrf_token', ['value' => Session::getNewCSRFToken()]);
echo '</div>';
echo '<script type="text/javascript">
function plugin_formcreator_checkComment(field) {
if ($("textarea[name=comment]").val() == "") {
alert("' . __('Refused comment is required!', 'formcreator') . '");
return false;
}
}
</script>';
echo '</td></tr>';
$this->showFormButtons($options);
echo "</div>"; // .form_answer
return true;
}
/**
* Prepare input data for adding the question
* Check fields values and get the order for the new question
*
* @param array $input data used to add the item
*
* @return array the modified $input array
*/
public function prepareInputForAdd($input) {
global $GLPI;
// A requester submits his answers to a form
if (!isset($input['plugin_formcreator_forms_id'])) {
return false;
}
$form = $this->getForm($input['plugin_formcreator_forms_id']);
if ($form->validationRequired()) {
if (($validator = $this->getUniqueValidator($form)) !== null) {
$input['formcreator_validator'] = $validator->getType() . '_' . $validator->getID();
}
}
try {
if (!$this->validateFormAnswer($input)) {
// Validation of answers failed
return false;
}
} catch (Exception $e) {
// A fatal error caught during validation of answers
$GLPI->getErrorHandler()->handleException($e, false);
Session::addMessageAfterRedirect(__('An internal error occured when verifying your answers. Please report it to your administrator.', 'formcreator'), false, ERROR);
return false;
}
if (!$this->validateCaptcha($input)) {
// Captcha verification failed
return false;
}
if (!$this->validateValidator($input)) {
// Validator requirement failed
return false;
}
try {
$input['name'] = $this->parseTags($form->fields['formanswer_name']);
} catch (Exception $e) {
// A fatal error caught during parsing of tags
$GLPI->getErrorHandler()->handleException($e, false);
Session::addMessageAfterRedirect(__('An internal error occured when verifying your answers. Please report it to your administrator.', 'formcreator'), false, ERROR);
return false;
}
$input = $this->setValidator($input, $form);
$input['entities_id'] = $_SESSION['glpiactive_entity'] ?? $form->fields['entities_id'];
$input['is_recursive'] = $form->fields['is_recursive'];
$input['plugin_formcreator_forms_id'] = $form->getID();
// requester_id is actually the author
// TODO : rename this column
$input['requester_id'] = $_SESSION['glpiID'] ?? 0;
$input['request_date'] = $_SESSION['glpi_currenttime'];
$input['comment'] = '';
return $input;
}
public function prepareInputForUpdate($input) {
// A requester submits his answers to a form
if (!isset($input['plugin_formcreator_forms_id'])) {
return false;
}
$skipValidation = false;
$input['status'] = self::STATUS_WAITING;
if (isset($input['refuse_formanswer']) || isset($input['accept_formanswer'])) {
// The formanswer is being acepted or refused
// Check the user haas right to validate the form answer
if (!$this->canValidate()) {
Session::addMessageAfterRedirect(__('You are not the validator of these answers', 'formcreator'), true, ERROR);
return false;
}
$newStatus = isset($input['refuse_formanswer'])
? PluginFormcreatorForm_Validator::VALIDATION_STATUS_REFUSED
: PluginFormcreatorForm_Validator::VALIDATION_STATUS_ACCEPTED;
if (Plugin::isPluginActive(PLUGIN_FORMCREATOR_ADVANCED_VALIDATION)) {
PluginAdvformFormanswerValidation::updateValidationStatus($this, $newStatus);
}
$computedStatus = self::getValidationStatus($this);
switch ($computedStatus) {
case PluginFormcreatorForm_Validator::VALIDATION_STATUS_REFUSED:
$input = $this->refuse($input);
$skipValidation = true;
break;
case PluginFormcreatorForm_Validator::VALIDATION_STATUS_ACCEPTED:
$input = $this->accept($input);
break;
}
if ($input['status'] != self::STATUS_REFUSED) {
// The requester may edit his answers
// or the validator accepts the answers and may edit the requester's answers
// check if the input contains answers to validate
$fieldPresence = [];
$this->getQuestionFields($input['plugin_formcreator_forms_id']);
foreach ($this->questionFields as $id => $field) {
$fieldPresence[$id] = $field->hasInput($input);
}
$skipValidation = !in_array(true, $fieldPresence, true);
if ($skipValidation) {
$this->questionFields = null;
}
}
}
if (!$skipValidation) {
if (!$this->validateFormAnswer($input)) {
// Validation of answers failed
return false;
}
if (!$this->validateCaptcha($input)) {
// Captcha verification failed
return false;
}
}
return $input;
}
/**
* Actions done before deleting an item. In case of failure, prevents
* actual deletion of the item
*
* @return boolean true if pre_delete actions succeeded, false if not
*/
public function pre_deleteItem() {
$issue = new PluginFormcreatorIssue();
$issue->deleteByCriteria([
'items_id' => $this->getID(),
'itemtype' => self::getType(),
]);
return true;
}
/**
* return the validator user or group if it is the ony choice for the requester
*
* @param PluginFormcreatorForm $form Form to search the unique validator
* @return null|User|Group
*/
protected function getUniqueValidator(PluginFormcreatorForm $form): ?CommonDBTM {
$validValidators = PluginFormcreatorForm_Validator::getValidatorsForForm(
$form
);
if (count($validValidators) != 1) {
return null;
}
return array_pop($validValidators);
}
/**
* Generates all targets for the answers
* @return bool true if targets were successfully generated
*/
public function generateTarget(): bool {
global $CFG_GLPI;
$success = true;
// Get all targets
$form = $this->getForm();
$all_targets = $form->getTargetsFromForm();
$CFG_GLPI['plugin_formcreator_disable_hook_create_ticket'] = '1';
// get all fields to compute visibility of targets
$this->questionFields = $form->getFields();
$this->deserializeAnswers();
// Generate targets
$generatedTargets = new PluginFormcreatorComposite(new PluginFormcreatorItem_TargetTicket(), new Ticket_Ticket(), $this);
foreach ($all_targets as $targets) {
foreach ($targets as $targetObject) {
// Check the condition of the target
if (!PluginFormcreatorFields::isVisible($targetObject, $this->questionFields)) {
// The target shall not be generated
continue;
}
// Generate the target
$generatedTarget = $targetObject->save($this);
if ($targetObject->getTargetType() == PluginFormcreatorAbstractItilTarget::TARGET_TYPE_OBJECT) {
if ($generatedTarget === null) {
// If the target generates an object but none generated
$success = false;
} else {
$this->targetList[] = $generatedTarget;