forked from osTicket/osTicket
-
Notifications
You must be signed in to change notification settings - Fork 0
/
class.dynamic_forms.php
1945 lines (1689 loc) · 62 KB
/
class.dynamic_forms.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
/*********************************************************************
class.dynamic_forms.php
Forms models built on the VerySimpleModel paradigm. Allows for arbitrary
data to be associated with tickets. Eventually this model can be
extended to associate arbitrary data with registered clients and thread
entries.
Jared Hancock <[email protected]>
Copyright (c) 2006-2013 osTicket
http://www.osticket.com
Released under the GNU General Public License WITHOUT ANY WARRANTY.
See LICENSE.TXT for details.
vim: expandtab sw=4 ts=4 sts=4:
**********************************************************************/
require_once(INCLUDE_DIR . 'class.orm.php');
require_once(INCLUDE_DIR . 'class.forms.php');
require_once(INCLUDE_DIR . 'class.list.php');
require_once(INCLUDE_DIR . 'class.filter.php');
require_once(INCLUDE_DIR . 'class.signal.php');
/**
* Form template, used for designing the custom form and for entering custom
* data for a ticket
*/
class DynamicForm extends VerySimpleModel {
static $meta = array(
'table' => FORM_SEC_TABLE,
'ordering' => array('title'),
'pk' => array('id'),
'joins' => array(
'fields' => array(
'reverse' => 'DynamicFormField.form',
),
),
);
// Registered form types
static $types = array(
'T' => 'Ticket Information',
'U' => 'User Information',
'O' => 'Organization Information',
);
const FLAG_DELETABLE = 0x0001;
const FLAG_DELETED = 0x0002;
var $_form;
var $_fields;
var $_has_data = false;
var $_dfields;
function getInfo() {
$base = $this->ht;
unset($base['fields']);
return $base;
}
function getId() {
return $this->id;
}
/**
* Fetch a list of field implementations for the fields defined in this
* form. This method should *always* be preferred over
* ::getDynamicFields() to avoid caching confusion
*/
function getFields() {
if (!$this->_fields) {
$this->_fields = new ListObject();
foreach ($this->getDynamicFields() as $f)
$this->_fields->append($f->getImpl($f));
}
return $this->_fields;
}
/**
* Fetch the dynamic fields associated with this dynamic form. Do not
* use this list for data processing or validation. Use ::getFields()
* for that.
*/
function getDynamicFields() {
return $this->fields;
}
// Multiple inheritance -- delegate methods not defined to a forms API
// Form
function __call($what, $args) {
$delegate = array($this->getForm(), $what);
if (!is_callable($delegate))
throw new Exception(sprintf(__('%s: Call to non-existing function'), $what));
return call_user_func_array($delegate, $args);
}
function getTitle() {
return $this->getLocal('title');
}
function getInstructions() {
return $this->getLocal('instructions');
}
/**
* Drop field errors clean info etc. Useful when replacing the source
* content of the form. This is necessary because the field listing is
* cached under some circumstances.
*/
function reset() {
foreach ($this->getFields() as $f)
$f->reset();
return $this;
}
function getForm($source=false) {
if ($source)
$this->reset();
$fields = $this->getFields();
$form = new SimpleForm($fields, $source, array(
'title' => $this->getLocal('title'),
'instructions' => $this->getLocal('instructions'),
'id' => $this->getId(),
));
return $form;
}
function isDeletable() {
return $this->flags & self::FLAG_DELETABLE;
}
function setFlag($flag) {
$this->flags |= $flag;
}
function hasAnyVisibleFields($user=false) {
global $thisstaff, $thisclient;
$user = $user ?: $thisstaff ?: $thisclient;
$visible = 0;
$isstaff = $user instanceof Staff;
foreach ($this->getFields() as $F) {
if ($isstaff) {
if ($F->isVisibleToStaff())
$visible++;
}
elseif ($F->isVisibleToUsers()) {
$visible++;
}
}
return $visible > 0;
}
function instanciate($sort=1, $data=null) {
$inst = DynamicFormEntry::create(
array('form_id'=>$this->get('id'), 'sort'=>$sort)
);
if ($data)
$inst->setSource($data);
$inst->_fields = $this->_fields ?: null;
return $inst;
}
function disableFields(array $ids) {
foreach ($this->getFields() as $F) {
if (in_array($F->get('id'), $ids)) {
$F->disable();
}
}
}
function getTranslateTag($subtag) {
return _H(sprintf('form.%s.%s', $subtag, $this->id));
}
function getLocal($subtag) {
$tag = $this->getTranslateTag($subtag);
$T = CustomDataTranslation::translate($tag);
return $T != $tag ? $T : $this->get($subtag);
}
function save($refetch=false) {
if (count($this->dirty))
$this->set('updated', new SqlFunction('NOW'));
if ($rv = parent::save($refetch | $this->dirty))
return $this->saveTranslations();
return $rv;
}
function delete() {
if (!$this->isDeletable())
return false;
// Soft Delete: Mark the form as deleted.
$this->setFlag(self::FLAG_DELETED);
return $this->save();
}
function getExportableFields($exclude=array(), $prefix='__') {
$fields = array();
foreach ($this->getFields() as $f) {
// Ignore core fields
if ($exclude && in_array($f->get('name'), $exclude))
continue;
// Ignore non-data fields
// FIXME: Consider ::isStorable() too
elseif (!$f->hasData() || $f->isPresentationOnly())
continue;
$name = $f->get('name') ?: ('field_'.$f->get('id'));
$fields[$prefix.$name] = $f;
}
return $fields;
}
static function create($ht=false) {
$inst = new static($ht);
$inst->set('created', new SqlFunction('NOW'));
if (isset($ht['fields'])) {
$inst->save();
foreach ($ht['fields'] as $f) {
$field = DynamicFormField::create(array('form' => $inst) + $f);
$field->save();
}
}
return $inst;
}
function saveTranslations($vars=false) {
global $thisstaff;
$vars = $vars ?: $_POST;
$tags = array(
'title' => $this->getTranslateTag('title'),
'instructions' => $this->getTranslateTag('instructions'),
);
$rtags = array_flip($tags);
$translations = CustomDataTranslation::allTranslations($tags, 'phrase');
foreach ($translations as $t) {
$T = $rtags[$t->object_hash];
$content = @$vars['trans'][$t->lang][$T];
if (!isset($content))
continue;
// Content is not new and shouldn't be added below
unset($vars['trans'][$t->lang][$T]);
$t->text = $content;
$t->agent_id = $thisstaff->getId();
$t->updated = SqlFunction::NOW();
if (!$t->save())
return false;
}
// New translations (?)
if ($vars['trans'] && is_array($vars['trans'])) {
foreach ($vars['trans'] as $lang=>$parts) {
if (!Internationalization::isLanguageEnabled($lang))
continue;
foreach ($parts as $T => $content) {
$content = trim($content);
if (!$content)
continue;
$t = CustomDataTranslation::create(array(
'type' => 'phrase',
'object_hash' => $tags[$T],
'lang' => $lang,
'text' => $content,
'agent_id' => $thisstaff->getId(),
'updated' => SqlFunction::NOW(),
));
if (!$t->save())
return false;
}
}
}
return true;
}
static function ensureDynamicDataView() {
if (!($cdata=static::$cdata) || !$cdata['table'])
return false;
$sql = 'SHOW TABLES LIKE \''.$cdata['table'].'\'';
if (!db_num_rows(db_query($sql)))
return static::buildDynamicDataView($cdata);
}
static function buildDynamicDataView($cdata) {
$sql = 'CREATE TABLE IF NOT EXISTS `'.$cdata['table'].'` (PRIMARY KEY
('.$cdata['object_id'].')) DEFAULT CHARSET=utf8 AS '
. static::getCrossTabQuery( $cdata['object_type'], $cdata['object_id']);
db_query($sql);
}
static function dropDynamicDataView($table) {
db_query('DROP TABLE IF EXISTS `'.$table.'`');
}
static function updateDynamicDataView($answer, $data) {
// TODO: Detect $data['dirty'] for value and value_id
// We're chiefly concerned with Ticket form answers
$cdata = static::$cdata;
if (!$cdata
|| !$cdata['table']
|| !($e = $answer->getEntry())
|| $e->form->get('type') != $cdata['object_type'])
return;
// $record = array();
// $record[$f] = $answer->value'
// TicketFormData::objects()->filter(array('ticket_id'=>$a))
// ->merge($record);
$sql = 'SHOW TABLES LIKE \''.$cdata['table'].'\'';
if (!db_num_rows(db_query($sql)))
return;
$f = $answer->getField();
$name = $f->get('name') ? $f->get('name')
: 'field_'.$f->get('id');
$fields = sprintf('`%s`=', $name) . db_input($answer->getSearchKeys());
$sql = 'INSERT INTO `'.$cdata['table'].'` SET '.$fields
. sprintf(', `%s`= %s',
$cdata['object_id'],
db_input($answer->getEntry()->get('object_id')))
.' ON DUPLICATE KEY UPDATE '.$fields;
if (!db_query($sql))
return self::dropDynamicDataView($cdata['table']);
}
static function updateDynamicFormEntryAnswer($answer, $data) {
if (!$answer
|| !($e = $answer->getEntry())
|| !$e->form)
return;
switch ($e->form->get('type')) {
case 'T':
return TicketForm::updateDynamicDataView($answer, $data);
case 'A':
return TaskForm::updateDynamicDataView($answer, $data);
case 'U':
return UserForm::updateDynamicDataView($answer, $data);
case 'O':
return OrganizationForm::updateDynamicDataView($answer, $data);
}
}
static function updateDynamicFormField($field, $data) {
if (!$field || !$field->form)
return;
switch ($field->form->get('type')) {
case 'T':
return TicketForm::dropDynamicDataView(TicketForm::$cdata['table']);
case 'A':
return TaskForm::dropDynamicDataView(TaskForm::$cdata['table']);
case 'U':
return UserForm::dropDynamicDataView(UserForm::$cdata['table']);
case 'O':
return OrganizationForm::dropDynamicDataView(OrganizationForm::$cdata['table']);
}
}
static function getCrossTabQuery($object_type, $object_id='object_id', $exclude=array()) {
$fields = static::getDynamicDataViewFields($exclude);
return "SELECT entry.`object_id` as `$object_id`, ".implode(',', $fields)
.' FROM '.FORM_ENTRY_TABLE.' entry
JOIN '.FORM_ANSWER_TABLE.' ans ON ans.entry_id = entry.id
JOIN '.FORM_FIELD_TABLE." field ON field.id=ans.field_id
WHERE entry.object_type='$object_type' GROUP BY entry.object_id";
}
// Materialized View for custom data (MySQL FlexViews would be nice)
//
// @see http://code.google.com/p/flexviews/
static function getDynamicDataViewFields($exclude) {
$fields = array();
foreach (static::getInstance()->getFields() as $f) {
if ($exclude && in_array($f->get('name'), $exclude))
continue;
$impl = $f->getImpl($f);
if (!$impl->hasData() || $impl->isPresentationOnly())
continue;
$id = $f->get('id');
$name = ($f->get('name')) ? $f->get('name')
: 'field_'.$id;
if ($impl instanceof ChoiceField || $impl instanceof SelectionField) {
$fields[] = sprintf(
'MAX(CASE WHEN field.id=\'%1$s\' THEN REPLACE(REPLACE(REPLACE(REPLACE(coalesce(ans.value_id, ans.value), \'{\', \'\'), \'}\', \'\'), \'"\', \'\'), \':\', \',\') ELSE NULL END) as `%2$s`',
$id, $name);
}
else {
$fields[] = sprintf(
'MAX(IF(field.id=\'%1$s\',coalesce(ans.value_id, ans.value),NULL)) as `%2$s`',
$id, $name);
}
}
return $fields;
}
}
class UserForm extends DynamicForm {
static $instance;
static $form;
static $cdata = array(
'table' => USER_CDATA_TABLE,
'object_id' => 'user_id',
'object_type' => ObjectModel::OBJECT_TYPE_USER,
);
static function objects() {
$os = parent::objects();
return $os->filter(array('type'=>'U'));
}
static function getUserForm() {
if (!isset(static::$form)) {
static::$form = static::objects()->one();
}
return static::$form;
}
static function getInstance() {
if (!isset(static::$instance))
static::$instance = static::getUserForm()->instanciate();
return static::$instance;
}
static function getNewInstance() {
$o = static::objects()->one();
static::$instance = $o->instanciate();
return static::$instance;
}
}
Filter::addSupportedMatches(/* @trans */ 'User Data', function() {
$matches = array();
foreach (UserForm::getInstance()->getFields() as $f) {
if (!$f->hasData())
continue;
$matches['field.'.$f->get('id')] = __('User').' / '.$f->getLabel();
if (($fi = $f->getImpl()) && $fi->hasSubFields()) {
foreach ($fi->getSubFields() as $p) {
$matches['field.'.$f->get('id').'.'.$p->get('id')]
= __('User').' / '.$f->getLabel().' / '.$p->getLabel();
}
}
}
return $matches;
}, 20);
class TicketForm extends DynamicForm {
static $instance;
static $cdata = array(
'table' => TICKET_CDATA_TABLE,
'object_id' => 'ticket_id',
'object_type' => 'T',
);
static function objects() {
$os = parent::objects();
return $os->filter(array('type'=>'T'));
}
static function getInstance() {
if (!isset(static::$instance))
self::getNewInstance();
return static::$instance;
}
static function getNewInstance() {
$o = static::objects()->one();
static::$instance = $o->instanciate();
return static::$instance;
}
}
// Add fields from the standard ticket form to the ticket filterable fields
Filter::addSupportedMatches(/* @trans */ 'Ticket Data', function() {
$matches = array();
foreach (TicketForm::getInstance()->getFields() as $f) {
if (!$f->hasData())
continue;
$matches['field.'.$f->get('id')] = __('Ticket').' / '.$f->getLabel();
if (($fi = $f->getImpl()) && $fi->hasSubFields()) {
foreach ($fi->getSubFields() as $p) {
$matches['field.'.$f->get('id').'.'.$p->get('id')]
= __('Ticket').' / '.$f->getLabel().' / '.$p->getLabel();
}
}
}
return $matches;
}, 30);
// Manage materialized view on custom data updates
Signal::connect('model.created',
array('DynamicForm', 'updateDynamicFormEntryAnswer'),
'DynamicFormEntryAnswer');
Signal::connect('model.updated',
array('DynamicForm', 'updateDynamicFormEntryAnswer'),
'DynamicFormEntryAnswer');
// Recreate the dynamic view after new or removed fields to the ticket
// details form
Signal::connect('model.created',
array('DynamicForm', 'updateDynamicFormField'),
'DynamicFormField');
Signal::connect('model.deleted',
array('DynamicForm', 'updateDynamicFormField'),
'DynamicFormField');
// If the `name` column is in the dirty list, we would be renaming a
// column. Delete the view instead.
Signal::connect('model.updated',
array('DynamicForm', 'updateDynamicFormField'),
'DynamicFormField',
function($o, $d) { return isset($d['dirty'])
&& (isset($d['dirty']['name']) || isset($d['dirty']['type'])); });
Filter::addSupportedMatches(/* trans */ 'Custom Forms', function() {
$matches = array();
foreach (DynamicForm::objects()->filter(array('type'=>'G')) as $form) {
foreach ($form->getFields() as $f) {
if (!$f->hasData())
continue;
$matches['field.'.$f->get('id')] = $form->getTitle().' / '.$f->getLabel();
if (($fi = $f->getImpl()) && $fi->hasSubFields()) {
foreach ($fi->getSubFields() as $p) {
$matches['field.'.$f->get('id').'.'.$p->get('id')]
= $form->getTitle().' / '.$f->getLabel().' / '.$p->getLabel();
}
}
}
}
return $matches;
}, 9900);
require_once(INCLUDE_DIR . "class.json.php");
class DynamicFormField extends VerySimpleModel {
static $meta = array(
'table' => FORM_FIELD_TABLE,
'ordering' => array('sort'),
'pk' => array('id'),
'select_related' => array('form'),
'joins' => array(
'form' => array(
'null' => true,
'constraint' => array('form_id' => 'DynamicForm.id'),
),
'answers' => array(
'reverse' => 'DynamicFormEntryAnswer.field',
),
),
);
var $_field;
var $_disabled = false;
const FLAG_ENABLED = 0x00001;
const FLAG_EXT_STORED = 0x00002; // Value stored outside of form_entry_value
const FLAG_CLOSE_REQUIRED = 0x00004;
const FLAG_MASK_CHANGE = 0x00010;
const FLAG_MASK_DELETE = 0x00020;
const FLAG_MASK_EDIT = 0x00040;
const FLAG_MASK_DISABLE = 0x00080;
const FLAG_MASK_REQUIRE = 0x10000;
const FLAG_MASK_VIEW = 0x20000;
const FLAG_MASK_NAME = 0x40000;
const MASK_MASK_INTERNAL = 0x400B2; # !change, !delete, !disable, !edit-name
const MASK_MASK_ALL = 0x700F2;
const FLAG_CLIENT_VIEW = 0x00100;
const FLAG_CLIENT_EDIT = 0x00200;
const FLAG_CLIENT_REQUIRED = 0x00400;
const MASK_CLIENT_FULL = 0x00700;
const FLAG_AGENT_VIEW = 0x01000;
const FLAG_AGENT_EDIT = 0x02000;
const FLAG_AGENT_REQUIRED = 0x04000;
const MASK_AGENT_FULL = 0x7000;
// Multiple inheritance -- delegate methods not defined here to the
// forms API FormField instance
function __call($what, $args) {
return call_user_func_array(
array($this->getField(), $what), $args);
}
/**
* Fetch a forms API FormField instance which represents this designable
* DynamicFormField.
*/
function getField() {
global $thisstaff;
// Finagle the `required` flag for the FormField instance
$ht = $this->ht;
$ht['required'] = ($thisstaff) ? $this->isRequiredForStaff()
: $this->isRequiredForUsers();
if (!isset($this->_field))
$this->_field = new FormField($ht);
return $this->_field;
}
function getForm() { return $this->form; }
function getFormId() { return $this->form_id; }
/**
* setConfiguration
*
* Used in the POST request of the configuration process. The
* ::getConfigurationForm() method should be used to retrieve a
* configuration form for this field. That form should be submitted via
* a POST request, and this method should be called in that request. The
* data from the POST request will be interpreted and will adjust the
* configuration of this field
*
* Parameters:
* vars - POST request / data
* errors - (OUT array) receives validation errors of the parsed
* configuration form
*
* Returns:
* (bool) true if the configuration was updated, false if there were
* errors. If false, the errors were written into the received errors
* array.
*/
function setConfiguration($vars, &$errors=array()) {
$config = array();
foreach ($this->getConfigurationForm($vars)->getFields() as $name=>$field) {
$config[$name] = $field->to_php($field->getClean());
$errors = array_merge($errors, $field->errors());
}
if (count($errors))
return false;
// See if field impl. need to save or override anything
$config = $this->getImpl()->to_config($config);
$this->set('configuration', JsonDataEncoder::encode($config));
$this->set('hint', Format::sanitize($vars['hint']));
return true;
}
function isDeletable() {
return !$this->hasFlag(self::FLAG_MASK_DELETE);
}
function isNameForced() {
return $this->hasFlag(self::FLAG_MASK_NAME);
}
function isPrivacyForced() {
return $this->hasFlag(self::FLAG_MASK_VIEW);
}
function isRequirementForced() {
return $this->hasFlag(self::FLAG_MASK_REQUIRE);
}
function isChangeable() {
return !$this->hasFlag(self::FLAG_MASK_CHANGE);
}
function isEditable() {
return $this->hasFlag(self::FLAG_MASK_EDIT);
}
function disable() {
$this->_disabled = true;
}
function isEnabled() {
return !$this->_disabled && $this->hasFlag(self::FLAG_ENABLED);
}
function hasFlag($flag) {
return (isset($this->flags) && ($this->flags & $flag) != 0);
}
/**
* Describes the current visibility settings for this field. Returns a
* comma-separated, localized list of flag descriptions.
*/
function getVisibilityDescription() {
$F = $this->flags;
if (!$this->hasFlag(self::FLAG_ENABLED))
return __('Disabled');
$impl = $this->getImpl();
$hints = array();
$VIEW = self::FLAG_CLIENT_VIEW | self::FLAG_AGENT_VIEW;
if (($F & $VIEW) == 0) {
$hints[] = __('Hidden');
}
elseif (~$F & self::FLAG_CLIENT_VIEW) {
$hints[] = __('Internal');
}
elseif (~$F & self::FLAG_AGENT_VIEW) {
$hints[] = __('For EndUsers Only');
}
if ($impl->hasData()) {
if ($F & (self::FLAG_CLIENT_REQUIRED | self::FLAG_AGENT_REQUIRED)) {
$hints[] = __('Required');
}
else {
$hints[] = __('Optional');
}
if (!($F & (self::FLAG_CLIENT_EDIT | self::FLAG_AGENT_EDIT))) {
$hints[] = __('Immutable');
}
}
return implode(', ', $hints);
}
function getTranslateTag($subtag) {
return _H(sprintf('field.%s.%s', $subtag, $this->id));
}
function getLocal($subtag, $default=false) {
$tag = $this->getTranslateTag($subtag);
$T = CustomDataTranslation::translate($tag);
return $T != $tag ? $T : ($default ?: $this->get($subtag));
}
/**
* Fetch a list of names to flag settings to make configuring new fields
* a bit easier.
*
* Returns:
* <Array['desc', 'flags']>, where the 'desc' key is a localized
* description of the flag set, and the 'flags' key is a bit mask of
* flags which should be set on the new field to implement the
* requirement / visibility mode.
*/
function allRequirementModes() {
return array(
'a' => array('desc' => __('Optional'),
'flags' => self::FLAG_CLIENT_VIEW | self::FLAG_AGENT_VIEW
| self::FLAG_CLIENT_EDIT | self::FLAG_AGENT_EDIT),
'b' => array('desc' => __('Required'),
'flags' => self::FLAG_CLIENT_VIEW | self::FLAG_AGENT_VIEW
| self::FLAG_CLIENT_EDIT | self::FLAG_AGENT_EDIT
| self::FLAG_CLIENT_REQUIRED | self::FLAG_AGENT_REQUIRED),
'c' => array('desc' => __('Required for EndUsers'),
'flags' => self::FLAG_CLIENT_VIEW | self::FLAG_AGENT_VIEW
| self::FLAG_CLIENT_EDIT | self::FLAG_AGENT_EDIT
| self::FLAG_CLIENT_REQUIRED),
'd' => array('desc' => __('Required for Agents'),
'flags' => self::FLAG_CLIENT_VIEW | self::FLAG_AGENT_VIEW
| self::FLAG_CLIENT_EDIT | self::FLAG_AGENT_EDIT
| self::FLAG_AGENT_REQUIRED),
'e' => array('desc' => __('Internal, Optional'),
'flags' => self::FLAG_AGENT_VIEW | self::FLAG_AGENT_EDIT),
'f' => array('desc' => __('Internal, Required'),
'flags' => self::FLAG_AGENT_VIEW | self::FLAG_AGENT_EDIT
| self::FLAG_AGENT_REQUIRED),
'g' => array('desc' => __('For EndUsers Only'),
'flags' => self::FLAG_CLIENT_VIEW | self::FLAG_CLIENT_EDIT
| self::FLAG_CLIENT_REQUIRED),
);
}
/**
* Fetch a list of valid requirement modes for this field. This list
* will be filtered based on flags which are not supported or not
* allowed for this field.
*
* Deprecated:
* This was used in previous versions when a drop-down list was
* presented for editing a field's visibility. The current software
* version presents the drop-down list for new fields only.
*
* Returns:
* <Array['desc', 'flags']> Filtered list from ::allRequirementModes
*/
function getAllRequirementModes() {
$modes = static::allRequirementModes();
if ($this->isPrivacyForced()) {
// Required to be internal
foreach ($modes as $m=>$info) {
if ($info['flags'] & (self::FLAG_CLIENT_VIEW | self::FLAG_AGENT_VIEW))
unset($modes[$m]);
}
}
if ($this->isRequirementForced()) {
// Required to be required
foreach ($modes as $m=>$info) {
if ($info['flags'] & (self::FLAG_CLIENT_REQUIRED | self::FLAG_AGENT_REQUIRED))
unset($modes[$m]);
}
}
return $modes;
}
function setRequirementMode($mode) {
$modes = $this->getAllRequirementModes();
if (!isset($modes[$mode]))
return false;
$info = $modes[$mode];
$this->set('flags', $info['flags'] | self::FLAG_ENABLED);
}
function isRequiredForStaff() {
return $this->hasFlag(self::FLAG_AGENT_REQUIRED);
}
function isRequiredForUsers() {
return $this->hasFlag(self::FLAG_CLIENT_REQUIRED);
}
function isRequiredForClose() {
return $this->hasFlag(self::FLAG_CLOSE_REQUIRED);
}
function isEditableToStaff() {
return $this->isEnabled()
&& $this->hasFlag(self::FLAG_AGENT_EDIT);
}
function isVisibleToStaff() {
return $this->isEnabled()
&& $this->hasFlag(self::FLAG_AGENT_VIEW);
}
function isEditableToUsers() {
return $this->isEnabled()
&& $this->hasFlag(self::FLAG_CLIENT_EDIT);
}
function isVisibleToUsers() {
return $this->isEnabled()
&& $this->hasFlag(self::FLAG_CLIENT_VIEW);
}
function addToQuery($query, $name=false) {
return $query->values($name ?: $this->get('name'));
}
/**
* Used when updating the form via the admin panel. This represents
* validation on the form field template, not data entered into a form
* field of a custom form. The latter would be isValidEntry()
*/
function isValid() {
if (count($this->errors()))
return false;
if (!$this->get('label'))
$this->addError(
__("Label is required for custom form fields"), "label");
if (($this->isRequiredForStaff() || $this->isRequiredForUsers())
&& !$this->get('name')
) {
$this->addError(
__("Variable name is required for required fields"
/* `required` is a visibility setting fields */
/* `variable` is used for automation. Internally it's called `name` */
), "name");
}
if (preg_match('/[.{}\'"`; ]/u', $this->get('name')))
$this->addError(__(
'Invalid character in variable name. Please use letters and numbers only.'
), 'name');
return count($this->errors()) == 0;
}
function delete() {
$values = $this->answers->count();
// Don't really delete form fields with data as that will screw up the data
// model. Instead, just drop the association with the form which
// will give the appearance of deletion. Not deleting means that
// the field will continue to exist on form entries it may already
// have answers on, but since it isn't associated with the form, it
// won't be available for new form submittals.
$this->set('form_id', 0);
$impl = $this->getImpl();
// Trigger db_clean so the field can do house cleaning
$impl->db_cleanup(true);
// Short-circuit deletion if the field has data.
if ($impl->hasData() && $values)
return $this->save();
// Delete the field for realz
parent::delete();
}
function save($refetch=false) {
if (count($this->dirty))
$this->set('updated', new SqlFunction('NOW'));
return parent::save($this->dirty || $refetch);
}
static function create($ht=false) {
$inst = new static($ht);
$inst->set('created', new SqlFunction('NOW'));
if (isset($ht['configuration']))
$inst->configuration = JsonDataEncoder::encode($ht['configuration']);
return $inst;
}
}
/**
* Represents an entry to a dynamic form. Used to render the completed form
* in reference to the attached ticket, etc. A form is used to represent the
* template of enterable data. This represents the data entered into an
* instance of that template.
*
* The data of the entry is called 'answers' in this model. This model
* represents an instance of a form entry. The data / answers to that entry
* are represented individually in the DynamicFormEntryAnswer model.
*/
class DynamicFormEntry extends VerySimpleModel {
static $meta = array(
'table' => FORM_ENTRY_TABLE,
'ordering' => array('sort'),
'pk' => array('id'),
'select_related' => array('form'),
'joins' => array(
'form' => array(
'null' => true,
'constraint' => array('form_id' => 'DynamicForm.id'),
),
'answers' => array(
'reverse' => 'DynamicFormEntryAnswer.entry',
),
),
);
var $_fields;
var $_form;
var $_errors = false;
var $_clean = false;
var $_source = null;
function getId() {
return $this->get('id');
}
function getFormId() {
return $this->form_id;
}
function getAnswers() {
return $this->answers;
}
function getAnswer($name) {
foreach ($this->getAnswers() as $ans)
if ($ans->getField()->get('name') == $name)
return $ans;
return null;
}
function setAnswer($name, $value, $id=false) {
if ($ans=$this->getAnswer($name)) {
$f = $ans->getField();
if ($f->isStorable())
$ans->setValue($value, $id);
}
}
function errors() {
return $this->_errors;
}
function getTitle() {
return $this->form->getTitle();
}
function getInstructions() {
return $this->form->getInstructions();
}
function getDynamicForm() {
return $this->form;
}
function getForm($source=false, $options=array()) {
if (!isset($this->_form)) {
$fields = $this->getFields();
if (isset($this->extra)) {
$x = JsonDataParser::decode($this->extra) ?: array();