-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdata_entry_helper.php
10130 lines (9851 loc) · 474 KB
/
data_entry_helper.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
/**
* Indicia, the OPAL Online Recording Toolkit.
*
* This program 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 3 of the License, or
* any later version.
* This program 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 this program. If not, see http://www.gnu.org/licenses/gpl.html.
*
* @license http://www.gnu.org/licenses/gpl.html GPL 3.0
* @link https://github.com/indicia-team/client_helpers
*/
/**
* Link in other required php files.
*/
require_once 'helper_base.php';
require_once 'submission_builder.php';
/**
* Static helper class that provides automatic HTML and JavaScript generation Indicia data entry.
*
* Provides a set of controls that can be used to construct data entry forms. Examples include auto-complete text boxes
* that are populated by Indicia species lists, maps for spatial reference selection and date pickers. All controls in
* this class support the following entries in their $options array parameter:
*
* * label- Optional. If specified, then an HTML label containing this value is prefixed to the control HTML.
* * labelTemplate - If you need to change the label for this control only, set this to refer to the name of an
* alternate template you have added to the global $indicia_templates array. To change the label for all controls, you
* can update the value of $indicia_templates['label'] before building the form.
* * helpText- Optional. Defines help text to be displayed alongside the control. The position of the text is defined by
* helper_base::$helpTextPos, which can be set to before or after (default). The template is defined by global
* $indicia_templates['helpText'] and can be replaced on an instance by instance basis by specifying an option
* 'helpTextTemplate' for the control.
* * helpTextTemplate - If helpText is supplied but you need to change the template for this control only, set this to
* refer to the name of an alternate template you have added to the $indicia_templates array. The template should
* contain a {helpText} replacement string.
* * helpTextClass - Specify helpTextClass to override the class normally applied to control help texts, which defaults
* to helpText.
* * tooltip - Optional. Defines help text to be displayed as a title for the input control. Display of the control's
* title is browser dependent so you might need to enhance this functionality by adding jQuery UI tooltip to the page
* and calling tooltip() on the $(document) object.
* * prefixTemplate - If you need to change the prefix for this control only, set this to refer to the name of an
* alternate template you have added to the global $indicia_templates array. To change the prefix for all controls,
* you can update the value of $indicia_templates['prefix'] before building the form.
* * suffixTemplate - If you need to change the suffix for this control only, set this to refer to the name of an
* alternate template you have added to the global $indicia_templates array. To change the suffix for all controls,
* you can update the value of $indicia_templates['suffix'] before building the form.
* * afterControl- Allows a piece of HTML to be specified which is inserted immediately after the control, before the
* suffix and helpText. Ideal for inserting buttons that are to be displayed alongside a control such as a Go button
* for a search box. Also ideal for inserting units after value input boxes (e.g. degrees, m, cm etc).
* * lockable - Adds a padlock icon after the control which can be used to lock the control's value. The value will then
* be remembered and redisplayed in the control each time the form is shown until the control is unlocked or the end
* of the browser session. This option will not work for password controls.
*/
class data_entry_helper extends helper_base {
/**
* Data to load when reloading a form.
*
* When reloading a form, this can be populated with the list of values to load into the controls. E.g. set it to the
* content of $_POST after submitting a form that needs to reload.
*
* @var array
*/
public static $entity_to_load = NULL;
/**
* Field values remembered between form reloads using a cookie.
*
* List of fields that are to be stored in a cookie and reloaded the next
* time a form is accessed. These are populated by implementing a hook
* function called indicia_define_remembered_fields which calls
* setRememberedFields.
*
* @var array
*/
private static $rememberedFields = NULL;
/**
* IDs for attributes that have already been output on the current form.
*
* List of attribute ids that should be ignored when automatically drawing attributes to the page because they
* are already output, e.g. if they are output by a radio group which shows a textbox when "other" is selected.
*
* @var array
*/
public static $handled_attributes = [];
/**
* Track need to warn user if on a form that has checked records.
*
* @var int
*/
public static $checkedRecordsCount = 0;
/**
* Also track unchecked records to help make a sensible warning message.
*
* @var int
*/
public static $uncheckedRecordsCount = 0;
/**
* Track need to warn user if on a form that has unpublished records.
*
* @var int
*/
public static $unreleasedRecordsCount = 0;
/**********************************/
/* Start of main controls section */
/**********************************/
/**
* Autocomplete control.
*
* Helper function to generate an autocomplete box from an Indicia core service query.
* Because this generates a hidden ID control as well as a text input control, if you are outputting your own HTML label
* then the label you associate with this control should be of the form "$id:$caption" rather than just the $id which
* is normal for other controls. For example:
* <code>
* <label for='occurrence:taxa_taxon_list_id:taxon'>Taxon:</label>
* <?php echo data_entry_helper::autocomplete(array(
* 'fieldname' => 'occurrence:taxa_taxon_list_id',
* 'table' => 'taxa_taxon_list',
* 'captionField' => 'taxon',
* 'valueField' => 'id',
* 'extraParams' => $readAuth
* )); ?>
* </code>
* Of course if you use the built in label option in the options array then this is handled for you.
* The output of this control can be configured using the following templates:
* * autocomplete - Defines a hidden input and a visible input, to hold the underlying database ID and to
* allow input and display of the text search string respectively.
* * autocomplete_javascript - Defines the JavaScript which will be inserted onto the page in order to activate the
* autocomplete control.
*
* @param array $options
* Options array with the following possibilities:
* * attributes - JSON object where the properties will be output as HTML
* attribute names on the input and the values will be the HTML escaped
* attribute values.
* * fieldname - Required. The name of the database field this control is
* bound to.
* * inputId - The ID and name given to the visible input (as opposed to
* the hidden input which receives the looked up ID. Defaults to
* fieldname:captionFieldInEntity.
* * id - Optional. The id to assign to the HTML control. This should be
* left to its default value for integration with other mapping controls
* to work correctly.
* * default - Optional. The default value to assign to the control. This
* is overridden when reloading a record with existing data for this
* control.
* * defaultCaption - Optional. The default caption to assign to the
* control. This is overridden when reloading a record with existing data
* for this control.
* * class - Optional. CSS class names to add to the control.
* * table - Optional. Table name to get data from for the autocomplete
* options.
* * report - Optional. Report name to get data from for the autocomplete
* options. If specified then the table option is ignored.
* * captionField - Required. Field to draw values to show in the control
* from.
* * captionFieldInEntity - Optional. Field to use in the loaded entity to
* display the caption, when reloading an existing record. Defaults to
* the captionField.
* * valueField - Optional. Field to draw values to return from the control
* from. Defaults to the value of captionField.
* * extraParams - Optional. Associative array of items to pass via the
* query string to the service. This should at least contain the read
* authorisation array.
* * template - Optional. Name of the template entry used to build the HTML
* for the control. Defaults to autocomplete.
* * numValues - Optional. Number of returned values in the drop down list.
* Defaults to 20.
* * duplicateCheckFields - Optional. Provide an array of field names from
* the dataset returned from the warehouse. Any duplicate values from
* this list of fields will not be added to the output.
* * simplify - Set to true to simplify the search term by removing
* punctuation and spaces. Use when the field being searched against is
* also simplified. Deprecated, use taxa_search service instead.
* * warnIfNoMatch - Should the autocomplete control warn the user if they
* leave the control whilst searching and then nothing is matched?
* Default true.
* * continueOnBlur - Should the autocomplete control continue trying to
* load values when the user blurs out of the control? If true then
* tabbing out of the control will select the first match. Set to false
* if you intend to allow the user to enter free text which is not
* matched to a term in the database. Default true.
* * selectMode - Should the autocomplete simulate a select drop down
* control by adding a drop down arrow after the input box which, when
* clicked, populates the drop down list with all search results to a
* maximum of numValues. This is similar to typing * into the box.
* Default false.
* * matchContains - If true, then the search looks for matches which
* contain the search characters. Otherwise, the search looks for matches
* which start with the search characters. Default false.
*
* @return string
* HTML to insert into the page for the autocomplete control.
*
* @link https://github.com/Indicia-Team/client_helperswiki/DataModel
*/
public static function autocomplete($options) {
global $indicia_templates;
$options = self::check_options($options);
if (!array_key_exists('id', $options)) {
$options['id'] = $options['fieldname'];
}
if (!array_key_exists('captionFieldInEntity', $options)) {
$options['captionFieldInEntity'] = $options['captionField'];
}
// The inputId is the id given to the text field, e.g. occurrence:taxa_taxon_list_id:taxon.
if (empty($options['inputId'])) {
$options['inputId'] = $options['id'] . ':' . $options['captionFieldInEntity'];
}
$defaultCaption = self::check_default_value($options['inputId']);
if (!is_null($defaultCaption)) {
// This computed value overrides a value passed in to the function.
$options['defaultCaption'] = $defaultCaption;
}
elseif (!isset($options['defaultCaption'])) {
$options['defaultCaption'] = '';
}
$options = array_merge([
'attributes' => [],
'template' => 'autocomplete',
'url' => parent::getProxiedBaseUrl() . 'index.php/services/' .
(isset($options['report']) ? 'report/requestReport' : "data/$options[table]"),
// Escape the ids for jQuery selectors.
'escaped_input_id' => self::jq_esc($options['inputId']),
'escaped_id' => self::jq_esc($options['id']),
'max' => array_key_exists('numValues', $options) ? ', max : ' . $options['numValues'] : '',
'formatFunction' => "function(item) { return item.$options[captionField]; }",
'simplify' => (isset($options['simplify']) && $options['simplify']) ? 'true' : 'false',
'warnIfNoMatch' => TRUE,
'continueOnBlur' => TRUE,
'selectMode' => FALSE,
'default' => '',
'matchContains' => FALSE,
'isFormControl' => TRUE
], $options);
if (isset($options['report'])) {
$options['extraParams']['report'] = $options['report'] . '.xml';
$options['extraParams']['reportSource'] = 'local';
}
$options['warnIfNoMatch'] = $options['warnIfNoMatch'] ? 'true' : 'false';
$options['continueOnBlur'] = $options['continueOnBlur'] ? 'true' : 'false';
$options['selectMode'] = $options['selectMode'] ? 'true' : 'false';
$options['matchContains'] = $options['matchContains'] ? 'true' : 'false';
self::add_resource('autocomplete');
// Do stuff with extraParams.
$sParams = '';
foreach ($options['extraParams'] as $a => $b) {
// Escape single quotes.
$b = str_replace("'", "\'", $b);
$sParams .= "$a : '$b',";
}
// Lop the comma off the end.
$options['sParams'] = substr($sParams, 0, -1);
$options['extraParams'] = NULL;
if (!empty($options['duplicateCheckFields'])) {
$duplicateCheckFields = 'item.' . implode(" + '#' + item.", $options['duplicateCheckFields']);
$options['duplicateCheck'] = "$.inArray($duplicateCheckFields, done)===-1";
$options['storeDuplicates'] = "done.push($duplicateCheckFields);";
unset($options['duplicateCheckFields']);
}
else {
// Disable duplicate checking.
$options['duplicateCheck'] = 'true';
$options['storeDuplicates'] = '';
}
// Handle any custom HTML attributes.
$attrArray = [];
foreach ($options['attributes'] as $attrName => $attrValue) {
$escaped = htmlspecialchars($attrValue);
$attrArray[] = "$attrName=\"$escaped\"";
}
$options['attribute_list'] = implode(' ', $attrArray);
self::$javascript .= self::apply_replacements_to_template($indicia_templates['autocomplete_javascript'], $options);
$r = self::apply_template($options['template'], $options);
return $r;
}
/**
* Complex custom attribute grid control.
*
* A control that can be used to output a multi-value text attribute where the text value holds a json record
* structure. The control is a simple grid with each row representing a single attribute value and each column representing
* a field in the JSON stored in the value.
*
* @param array $options
* Options array with the following possibilities:
* * **fieldname** - The fieldname of the attribute, e.g. smpAttr:10.
* * **defaultRows** - Number of rows to show in the grid by default. An Add Another button is available to add more.
* Defaults to 3.
* * **columns** - An array defining the columns available in the grid which map to fields in the JSON stored for each
* value. The array key is the column name and the value is a sub-array with a column definition. The column
* definition can contain the following:
* * label - The column label. Will be automatically translated.
* * class - A class given to the column label.
* * datatype - The column's data type. Currently only text and lookup is supported.
* * control - If datatype=lookup and control=checkbox_group then the
* options are presented as checkboxes. If omitted then options are
* presented as a select.
* * termlist_id - If datatype=lookup, then provide the termlist_id of the list to load terms for as options in the
* control.
* * hierarchical - set to true if the termlist is hierarchical. In this case terms shown in the drop down will
* include all the ancestors, e.g. coastal->coastal lagoon, rather than just the child term.
* * minDepth - if hierarchical, set the min and max depth to limit the range of levels returned.
* * maxDepth - if hierarchical, set the min and max depth to limit the range of levels returned.
* * orderby - if datatype=lookup and termlist_id is provided then allows
* the order of terms to be controlled. If hierarchical, the default is
* 'path' (the concatenated terms) but you may prefer 'sort_order'. If
* not hierarchical, the default is 'sort_order' but you may prefer
* 'term'
* * lookupValues - Instead of a termlist_id you can supply the values for
* a lookup column in an associative array of terms, keyed by a value.
* * unit - An optional unit label to display after the control (e.g. 'cm', 'kg').
* * regex - A regular expression which validates the controls input value.
* * default - default value for this control used for new rows
* * **default** - An array of default values loaded for existing data, as obtained by a call to getAttributes.
* * **rowCountControl** - Pass the ID of an input control that will contain an integer value to define the number of
* rows in the grid. If not set, then a button is shown allowing additional rows to be added.
* * **encoding** - encoding used when saving the array for a row to the database. Default is json. If not json then
* the provided character acts as a separator used to join the value list together.
*/
public static function complex_attr_grid($options) {
self::add_resource('complexAttrGrid');
self::add_resource('font_awesome');
global $indicia_templates;
$options = array_merge([
'defaultRows' => 3,
'columns' => [
'x' => [
'label' => 'x',
'datatype' => 'text',
'unit' => 'cm',
'regex' => '/^[0-9]+$/'
],
'y' => [
'label' => 'y',
'datatype' => 'lookup',
'termlist_id' => '5'
],
],
'default' => [],
'deleteRows' => FALSE,
'rowCountControl' => '',
'encoding' => 'json',
], $options);
list($attrTypeTag, $attrId) = explode(':', $options['fieldname']);
if (preg_match('/\[\]$/', $attrId)) {
$attrId = str_replace('[]', '', $attrId);
}
else {
return 'The complex attribute grid control must be used with a mult-value attribute.';
}
// Start building table head.
$r = '<thead><tr>';
$lookupData = [];
$thRow2 = '';
foreach ($options['columns'] as $idx => &$def) {
// Whilst we are iterating the columns, may as well do some setup.
// Apply i18n to unit now, as it will be used in JS later.
if (!empty($def['unit'])) {
$def['unit'] = lang::get($def['unit']);
}
if ($def['datatype'] === 'lookup') {
$listData = [];
// No matter if the lookup comes from the db, or from a local array,
// we want it in the same minimal format.
if (!empty($def['termlist_id'])) {
if (empty($def['hierarchical'])) {
$termlistData = self::get_population_data([
'table' => 'termlists_term',
'extraParams' => $options['extraParams'] + [
'termlist_id' => $def['termlist_id'],
'view' => 'cache',
'orderby' => isset($def['orderby']) ? $def['orderby'] : 'sort_order,term',
'allow_data_entry' => 't',
],
]);
}
else {
iform_load_helpers(['report_helper']);
$termlistData = report_helper::get_report_data([
'dataSource' => '/library/terms/terms_list_with_hierarchy',
'extraParams' => [
'termlist_id' => $def['termlist_id'],
'min_depth' => empty($def['minDepth']) ? 0 : $def['minDepth'],
'max_depth' => empty($def['maxDepth']) ? 0 : $def['maxDepth'],
'orderby' => isset($def['orderby']) ? $def['orderby'] : 'path',
],
'readAuth' => [
'auth_token' => $options['extraParams']['auth_token'],
'nonce' => $options['extraParams']['nonce'],
],
'caching' => TRUE,
'cachePerUser' => FALSE,
]);
}
foreach ($termlistData as $term) {
$listData[] = [$term['id'], $term['term']];
}
self::$javascript .= "indiciaData.tl$def[termlist_id]=" . json_encode($listData) . ";\n";
}
elseif (isset($def['lookupValues'])) {
foreach ($def['lookupValues'] as $id => $term) {
$listData[] = [$id, $term];
}
}
if (isset($def['control']) && $def['control'] === 'checkbox_group') {
// Add checkbox text to table header.
foreach ($listData as $listItem) {
$thRow2 .= "<th>$listItem[1]</th>";
}
}
$lookupData["tl$idx"] = $listData;
}
// Checkbox groups output a second row of cells for each checkbox label.
$rowspan = isset($def['control']) && $def['control'] === 'checkbox_group' ? 1 : 2;
$colspan = isset($def['control']) && $def['control'] === 'checkbox_group' ? count($listData) : 1;
// Add default class if none provided.
$class = isset($def['class']) ? $def['class'] : 'complex-attr-grid-col' . $idx;
$r .= "<th rowspan=\"$rowspan\" colspan=\"$colspan\" class=\"$class\">" . lang::get($def['label']) . '</th>';
}
// Need to unset the variable used in &$def, otherwise it doesn't work in the next iterator.
unset($def);
// Add delete column and end tr.
$r .= '<th rowspan="2" class="complex-attr-grid-col-del"></th></tr>';
// Add second header row then end thead.
$r .= "<tr>$thRow2</tr></thead>";
// Start building table body.
$r .= '<tbody>';
$rowCount = $options['defaultRows'] > count($options['default']) ? $options['defaultRows'] : count($options['default']);
$extraCols = 0;
$controlClass = 'complex-attr-grid-control';
$controlClass .= " $indicia_templates[formControlClass]";
// For each row in table body.
for ($i = 0; $i <= $rowCount - 1; $i++) {
$class = ($i % 2 === 1) ? '' : ' class="odd"';
$r .= "<tr$class>";
if (isset($options['default'][$i])) {
$defaults = $options['encoding'] === 'json'
? json_decode($options['default'][$i]['default'], TRUE)
: explode($options['encoding'], $options['default'][$i]['default']);
}
else {
$defaults = [];
}
// For each cell in row.
foreach ($options['columns'] as $idx => $def) {
if (isset($options['default'][$i])) {
$fieldnamePrefix = str_replace('Attr:', 'AttrComplex:', $options['default'][$i]['fieldname']);
}
else {
$fieldnamePrefix = "$attrTypeTag" . "Complex:" . $attrId . ":";
}
$fieldname = "$fieldnamePrefix:$i:$idx";
$default = isset(self::$entity_to_load[$fieldname]) ? self::$entity_to_load[$fieldname] :
(array_key_exists($idx, $defaults) ? $defaults[$idx] :
(isset($def['default']) ? $def['default'] : ''));
$r .= "<td>";
if ($def['datatype'] === 'lookup' && isset($def['control']) && $def['control'] === 'checkbox_group') {
// Add lookup as checkboxes.
$checkboxes = [];
// Array field.
$fieldname .= '[]';
foreach ($lookupData["tl$idx"] as $term) {
$checked = is_array($default) && in_array($term[0], $default) ? ' checked="checked"' : '';
$checkboxes[] = "<input title=\"$term[1]\" type=\"checkbox\" class=\"$controlClass\" name=\"$fieldname\" value=\"$term[0]:$term[1]\"$checked>";
}
$r .= implode('</td><td>', $checkboxes);
$extraCols .= count($checkboxes) - 1;
}
elseif ($def['datatype'] === 'lookup') {
// Add lookup as select.
$r .= "<select name=\"$fieldname\" class=\"$controlClass\"><option value=''><" . lang::get('Please select') . "></option>";
foreach ($lookupData["tl$idx"] as $term) {
$selected = $default == "$term[0]" ? ' selected="selected"' : '';
$r .= "<option value=\"$term[0]:$term[1]\"$selected>$term[1]</option>";
}
$r .= "</select>";
}
else {
// Add text input.
$class = empty($def['regex']) ? $controlClass : "$controlClass {pattern:$def[regex]}";
$default = htmlspecialchars($default);
$r .= "<input type=\"text\" name=\"$fieldname\" value=\"$default\" class=\"$class\"/>";
}
if (!empty($def['unit'])) {
// Add unit after input.
$r .= '<span class="unit">' . lang::get($def['unit']) . '</span>';
}
$r .= '</td>';
}
$r .= "<td><input type=\"hidden\" name=\"$fieldnamePrefix:$i:deleted\" value=\"f\" class=\"delete-flag\"/>";
if (empty($options['rowCountControl'])) {
$r .= "<span class=\"fas fa-trash-alt action-delete\"/>";
}
$r .= "</td></tr>";
}
$r .= '</tbody>';
if (empty($options['rowCountControl'])) {
// Add table footer with button to add another row.
$r .= '<tfoot>';
$r .= '<tr><td colspan="' . (count($options['columns']) + 1 + $extraCols) .
'"><button class="add-btn ' . $indicia_templates['buttonHighlightedClass'] . '" type="button"><i class="fas fa-plus"></i>' . lang::get("Add another") . '</button></td></tr>';
$r .= '</tfoot>';
}
else {
// Link number of rows to rowCountControl value.
$escaped = str_replace(':', '\\\\:', $options['rowCountControl']);
data_entry_helper::$javascript .=
"$('#$escaped').val($rowCount);
$('#$escaped').change(function(e) {
changeComplexGridRowCount('$escaped', '$attrTypeTag', '$attrId');
});\n";
}
// Wrap in a table template.
$r = str_replace(
[
'{class}',
'{id}',
'{content}',
],
[
' class="complex-attr-grid table"',
" id=\"complex-attr-grid-$attrTypeTag-$attrId\"",
$r,
],
$indicia_templates['data-input-table']);
$r .= "<input type=\"hidden\" name=\"complex-attr-grid-encoding-$attrTypeTag-$attrId\" value=\"$options[encoding]\" />\n";
// Store information to allow adding rows in JavaScript.
self::$javascript .= "indiciaData.langPleaseSelect='" . lang::get('Please select') . "'\n";
self::$javascript .= "indiciaData.langCantRemoveEnoughRows='" .
lang::get('Please clear the values in some more rows before trying to reduce the number of rows further.') . "'\n";
$jsData = [
'cols' => $options['columns'],
'rowCount' => $options['defaultRows'],
'rowCountControl' => $options['rowCountControl'],
'deleteRows' => $options['deleteRows'],
];
self::$javascript .= "indiciaData['complexAttrGrid-$attrTypeTag-$attrId']=" . json_encode($jsData) . ";\n";
return $r;
}
/**
* Helper function to generate a sub list UI control.
*
* This control allows a user to create a new list by selecting some items
* from the caption 'field' of an existing database table while adding some
* new items. The resulting list is submitted and the new items are added to
* the existing table as skeleton entries while the id values for the items
* are stored as a custom attribute.
*
* An example usage would be to associate a list of people with a sample or
* location.
*
* The output of this control can be configured using the following
* templates:
* * sub_list - Defines the search input, plus container element for the list
* of items which will be added.
* * sub_list_item - Defines the template for a single item added to the list.
* * sub_list_add - Defines hidden inputs to insert onto the page which
* contain the items to add to the sublist, when loading existing records.
* * autocompleteControl - Defines the name of the data entry helper control
* function used to provide the autocomplete control. Defaults to
* autocomplete but can be swapped to species_autocomplete for species name
* lookup for example.
*
* @param array $options
* Options array with the following possibilities:
* * fieldname - Required. The name of the database field this control is
* bound to. This must be a custom attributes field of type integer which
* supports multiple values.
* * table - Required. Table name to get data from for the autocomplete
* options. The control will use the captionField from this table.
* Defaults to 'termlists_term'.
* * captionField - Field to draw values from to show in the control from.
* Defaults to 'term'.
* * valueField - Field to obtain the value to store for each item from.
* Defaults to 'id'.
* * extraParams - Required. Associative array of items to pass via the
* query string to the service. This should at least contain the read
* authorisation array.
* * id - Optional. The id to assign to the HTML control. Base value
* defaults to fieldname, but this is a compound control and the many
* sub-controls have id values with additiobnal suffixes.
* * default - Optional. An array of items to load into the control on page
* startup. Each entry must be an associative array with keys fieldname,
* caption and default.
* * class - Optional. CSS class names to add to the control.
* * numValues - Optional. Number of returned values in the drop down list.
* Defaults to 20.
* * allowTermCreation - Optional, defaults to false. If set to true and
* being used for a lookup custom attribute, then new terms will be
* inserted into the associated termlist if entries are added which are
* not already in the list. Otherwise, only existing entries can be
* added. The termlist_id should be supplied in the extraParams.
* * selectMode - Should the autocomplete simulate a select drop down control
* by adding a drop down arrow after the input box which, when clicked,
* populates the drop down list with all search results to a maximum of
* numValues. This is similar to typing * into the box. Default false.
*
* @return string
* HTML to insert into the page for the sub_list control.
*/
public static function sub_list(array $options) {
global $indicia_templates;
self::add_resource('sub_list');
// Unique ID for all sublists.
static $sub_list_idx = 0;
// Checks essential options, uses fieldname as id default and loads
// defaults if error or edit.
$options = self::check_options($options);
$options = array_merge([
'allowTermCreation' => FALSE,
'autocompleteControl' => 'autocomplete',
'subListAdd' => '',
], $options);
if ($options['autocompleteControl'] !== 'species_autocomplete') {
$options = array_merge([
'table' => 'termlists_term',
'captionField' => 'term',
'valueField' => 'id',
], $options);
}
// This control submits many values with the same control name so add [] to
// fieldname so PHP puts multiple submitted values in an array.
if (substr($options['fieldname'], -2) !== '[]') {
$options['fieldname'] .= '[]';
}
if ($options['allowTermCreation'] && $options['table'] === 'termlists_term'
&& isset($options['extraParams']) && isset($options['extraParams']['termlist_id'])) {
// Add a hidden input to store the language so new terms can be created.
$lang = iform_lang_iso_639_2(hostsite_get_user_field('language'));
$options['subListAdd'] = "<input name=\"$options[id]:allowTermCreationLang\" type=\"hidden\" value=\"$lang\" />";
}
// Prepare embedded search control for add bar panel.
$ctrlOptions = $options;
unset($ctrlOptions['helpText']);
$ctrlOptions['id'] = "$ctrlOptions[id]:search";
$ctrlOptions['fieldname'] = $ctrlOptions['id'];
$ctrlOptions['default'] = '';
$ctrlOptions['lockable'] = NULL;
$ctrlOptions['label'] = NULL;
$ctrlOptions['controlWrapTemplate'] = 'justControl';
$ctrlOptions['afterControl'] = str_replace(
[
'{id}',
'{title}',
'{class}',
'{caption}',
],
[
"$options[id]:add",
lang::get('Add the chosen term to the list.'),
" class=\"$indicia_templates[buttonDefaultClass]\"",
lang::get('Add'),
],
$indicia_templates['button']);
'<input id="{id}:add" type="button" value="' . lang::get('add') . '" />';
if (!empty($options['selectMode']) && $options['selectMode']) {
$ctrlOptions['selectMode'] = TRUE;
}
// Set up add panel.
$control = $options['autocompleteControl'];
$options['panel_control'] = self::$control($ctrlOptions);
// Prepare other main control options.
$options['inputId'] = "$options[id]:$options[captionField]";
$options = array_merge([
'template' => 'sub_list',
// Escape the ids for jQuery selectors.
'escaped_input_id' => self::jq_esc($options['inputId']),
'escaped_id' => self::jq_esc($options['id']),
'escaped_captionField' => self::jq_esc($options['captionField'])
], $options);
$options['idx'] = $sub_list_idx;
// Set up javascript.
self::$javascript .= <<<JS
indiciaFns.initSubList('$options[escaped_id]', '$options[escaped_captionField]',
'$options[fieldname]', '$indicia_templates[sub_list_item]');
JS;
// Load any default values for list items into display and hidden lists.
$items = "";
$r = '';
if (array_key_exists('default', $options) && is_array($options['default'])) {
foreach ($options['default'] as $item) {
$items .= str_replace(['{caption}', '{value}', '{fieldname}'],
[$item['caption'], $item['default'], $item['fieldname']],
$indicia_templates['sub_list_item']
);
// A hidden input to put a blank in the submission if it is deleted.
$r .= "<input type=\"hidden\" value=\"\" name=\"$item[fieldname]\">";
}
}
$options['items'] = $items;
// Layout the control.
$r .= self::apply_template($options['template'], $options);
$sub_list_idx++;
return $r;
}
/**
* Helper function to output an HTML checkbox control.
*
* This includes re-loading of existing values and displaying of validation
* error messages. The output of this control can be configured using the
* following templates:
* * checkbox - HTML template for the checkbox.
*
* @param array $options
* Options array with the following possibilities:
* * fieldname - Required. The name of the database field this control is
* bound to.
* * id - Optional. The id to assign to the HTML control. If not assigned
* the fieldname is used.
* * default - Optional. The default value to assign to the control. This
* is overridden when reloading a record with existing data for this
* control.
* * class - Optional. CSS class names to add to the control.
* * template - Optional. Name of the template entry used to build the HTML
* for the control. Defaults to checkbox.
*
* @return string
* HTML to insert into the page for the checkbox control.
*/
public static function checkbox(array $options) {
$options = self::check_options($options);
$default = isset($options['default']) ? $options['default'] : '';
$value = self::check_default_value($options['fieldname'], $default);
$options['checked'] = ($value === 'on' || $value === 1 || $value === '1' || $value === 't' || $value === TRUE) ? ' checked="checked"' : '';
$options['template'] = array_key_exists('template', $options) ? $options['template'] : 'checkbox';
return self::apply_template($options['template'], $options);
}
/**
* Helper function to output a checkbox for controlling training mode.
*
* Samples and occurrences submitted in training mode can be kept apart from
* normal records. The output of this control can be configured using the
* following templates:
* * training - HTML template for checkbox with hidden input.
*
* @param array $options
* Options array with the following possibilities:
* * id - Optional. The id to assign to the HTML control. If not assigned
* 'training' is used.
* * default - Optional. Boolean. The default value to assign to the
* control Defaults to true i.e to training mode. This is overridden when
* reloading a record with existing data for this control.
* * disabled - Optional. Boolean. Determines whether the user is prevented
* from changing the value. Defaults to true i.e control is disabled.
* * class - Optional. CSS class names to add to the control.
* * template - Optional. Name of the template entry used to build the HTML
* for the control. Defaults to training.
*
* @return string
* HTML to insert into the page for the checkbox control.
*/
public static function training(array $options) {
// The fieldname is fixed for the specific purpose of this control.
$options['fieldname'] = 'training';
// Apply default options which may be overriden by supplied values.
$options = array_merge([
'default' => TRUE,
'disabled' => TRUE,
'label' => 'Training mode',
'helpText' => 'Records submitted in training mode are segregated from genuine records. ',
'template' => 'training',
], $options);
// Apply standard options and update default value if loading existing record.
$options = self::check_options($options);
// Be flexible about the value to accept as meaning checked.
$v = $options['default'];
if ($v === 'on' || $v === 1 || $v === '1' || $v === 't' || $v === TRUE) {
$options['checked'] = ' checked="checked"';
$options['default'] = 1;
}
else {
$options['checked'] = '';
$options['default'] = 0;
}
// A disabled or unchecked checkbox sends no value so hidden input has to contain value.
if ($options['disabled']) {
$options['disabled'] = ' disabled="disabled"';
$options['hiddenValue'] = $options['default'];
}
else {
$options['disabled'] = '';
$options['hiddenValue'] = 0;
}
return self::apply_template($options['template'], $options);
}
/**
* Helper function to generate a list of checkboxes from a Indicia core service query.
*
* @param array $options
* Options array with the following possibilities:
* * **fieldname** - Required. The name of the database field this control is bound to.
* * **id** - Optional. The id to assign to the HTML control. If not assigned the fieldname is used.
* * **default** - Optional. The default value to assign to the control. This is verridden when reloading a record
* with existing data for this control.
* * **class** - Optional. CSS class names to add to the control. Defaults to inline when not sortable.
* * **table** - Required. Table name to get data from for the select options.
* * **captionField** - Optional. Field to draw values to show in the control from. Required unless lookupValues is
* specified.
* * **valueField** - Optional. Field to draw values to return from the control from. Defaults to the value of
* captionField.
* * **otherItemId** - Optional. The termlists_terms id of the checkbox_group item that will be considered as
* "Other". When this checkbox is selected then another textbox is displayed allowing specific details relating to
* the Other item to be entered. The otherValueAttrId and otherTextboxLabel options must be specified to use this
* feature.
* * **otherValueAttrId** - Optional. The attribute id where the "Other" text will be stored, e.g. smpAttr:10. See
* otherItemId option description. This attribute's control does not need to be explicitly added to the form - it
* will be autogenerated.
* * **otherTextboxLabel** - Optional. The label for the "Other" textbox. See otherItemId, otherValueAttrId option
* descriptions.
* * **extraParams** - Optional. Associative array of items to pass via the query string to the service. This
* should at least contain the read authorisation array.
* * **lookupValues** - If the group is to be populated with a fixed list of values, rather than via a service call,
* then the values can be passed into this parameter as an associated array of key=>caption.
* * **cachetimeout** - Optional. Specifies the number of seconds before the data cache times out - i.e. how long
* after a request for data to the Indicia Warehouse before a new request will refetch the data, rather than use a
* locally stored (cached) copy of the previous request. This speeds things up and reduces the loading on the
* Indicia Warehouse. Defaults to the global website-wide value; if this is not specified then 1 hour.
* * **template** - Optional. If specified, specifies the name of the template (in global $indicia_templates) to use
* for the outer control.
* * **itemTemplate** - Optional. If specified, specifies the name of the template (in global $indicia_templates) to
* use for each item in the control.
* * **captionTemplate** - Optional and only relevant when loading content from a data service call. Specifies the
* template used to build the caption, with each database field represented as {fieldname}.
* * **sortable** - Set to true to allow drag sorting of the list of checkboxes. If sortable, then the layout will
* be a vertical column of checkboxes rather than inline.
* * **termImageSize** - Optional. Set to an Indicia image size preset (normally thumb, med or original) to include
* term images in the output.
* The output of this control can be configured using the following templates:
* * **check_or_radio_group** - Container element for the group of checkboxes.
* * **check_or_radio_group_item** - Template for the HTML element used for each item in the group.
*
* @return string
* HTML to insert into the page for the group of checkboxes.
*/
public static function checkbox_group(array $options) {
$options = self::check_options($options);
$options = array_merge([
'class' => empty($options['sortable']) || !$options['sortable'] ? 'inline' : ''
], $options);
if (substr($options['fieldname'], -2) !== '[]') {
$options['fieldname'] .= '[]';
}
if (!empty($options['sortable']) && $options['sortable']) {
self::add_resource('sortable');
$escapedId = str_replace(':', '\\\\:', $options['id']);
self::$javascript .= "Sortable.create($('#$escapedId')[0], { handle: '.sort-handle' });\n";
self::$javascript .= "$('#$escapedId').disableSelection();\n";
// Resort the available options into the saved order.
if (!empty($options['default']) && !empty($options['lookupValues'])) {
$sorted = [];
// First copy over the ones that are ticked, in order.
foreach ($options['default'] as $option) {
if (!empty($options['lookupValues'][$option])) {
$sorted[$option] = $options['lookupValues'][$option];
}
}
// Now the unticked ones in original order.
foreach ($options['lookupValues'] as $option => $caption) {
if (!isset($sorted[$option])) {
$sorted[$option] = $caption;
}
}
$options['lookupValues'] = $sorted;
}
}
return self::check_or_radio_group($options, 'checkbox');
}
/**
* Helper function to insert a date picker control.
*
* The output of this control can be configured using the following
* templates:
* * date_picker - HTML The output of this control for the text input element
* used for the date picker. Other functionality is added using JavaScript.
*
* @param array $options
* Options array with the following possibilities:
* * fieldname - Required. The name of the database field this control is
* bound to, for example 'sample:date'.
* * id - Optional. The id to assign to the HTML control. If not assigned
* the fieldname is used.
* * default - Optional. The default value to assign to the control. This
* is overridden when reloading a record with existing data for this
* control.
* * class - Optional. CSS class names to add to the control.
* * allowFuture - Optional. If true, then future dates are allowed.
* Default is false.
* * allowVagueDates - Optional. Set to true to enable vague date input,
* which disables client side validation for standard date input formats.
* * placeholder - Optional. Control the placeholder text shown in the text
* box before a value has been added. Only shown on browsers which don't
* support the HTML5 date input type.
* * attributes - Optional. Additional HTML attribute to attach, e.g.
* data-es_* attributes.
*
* @return string
* HTML to insert into the page for the date picker control.
*/
public static function date_picker(array $options) {
$options = self::check_options($options);
self::add_resource('datepicker');
$options = array_merge([
'allowVagueDates' => FALSE,
'default' => '',
'isFormControl' => TRUE,
'allowFuture' => FALSE,
'attributes' => [],
'vagueLabel' => lang::get('Vague date mode'),
], $options);
// Force vague date mode if loading existing data that requires it.
if (isset(self::$entity_to_load["$options[fieldname]_start"]) && isset(self::$entity_to_load["$options[fieldname]_end"]) &&
self::$entity_to_load["$options[fieldname]_start"] !== self::$entity_to_load["$options[fieldname]_end"]) {
if ($options['allowVagueDates'] === FALSE) {
$options['allowVagueDates'] = TRUE;
$options['helpText'] = (empty($options['helpText']) ? '' : "$options[helpText] ") .
lang::get("Vague dates enabled as this existing form's date is not an exact day.");
}
// Force the toggle on so the existing date can display.
self::$indiciaData['enableVagueDateToggle'] = TRUE;
}
// Date pickers should be limited width, otherwise icon too far to right.
$options['wrapClasses'] = ['not-full-width-' . ($options['allowVagueDates'] ? 'md' : 'sm')];
$dateFormatLabel = str_replace(['d', 'm', 'Y'], ['dd', 'mm', 'yyyy'], helper_base::$date_format);
if (!isset($options['placeholder'])) {
$options['placeholder'] = $options['allowVagueDates'] ? lang::get('{1} or vague date', $dateFormatLabel) : $dateFormatLabel;
}
$attrArray = [];
$attrArrayDate = [
'placeholder' => 'placeholder="' . $dateFormatLabel . '"',
];
if (!empty($options['placeholder'])) {
$attrArray[] = 'placeholder="' . htmlspecialchars($options['placeholder']) . '"';
}
foreach ($options['attributes'] as $attrName => $attrValue) {
$attrArray[] = "$attrName=\"$attrValue\"";
}
if (!$options['allowFuture']) {
$dateTime = new DateTime();
$attrArrayDate[] = 'max="' . $dateTime->format('Y-m-d') . '"';
}
$options['attribute_list'] = implode(' ', $attrArray);
// Options for date control if using a free text vague date input.
$options['attribute_list_date'] = implode(' ', $attrArrayDate);
if (isset($options['default'])) {
if ($options['default'] === 'today') {
$options['default'] = date(self::$date_format);
}
elseif (preg_match('/^\d{4}-\d{2}-\d{2}/', $options['default'])) {
$options['default'] = date(self::$date_format, strtotime($options['default']));
}
}
// Text box class helps sync to date picker control.
$options['class'] .= ' date-text';
$options['datePickerClass'] = 'precise-date-picker';
global $indicia_templates;
$options['datePickerClass'] .= " $indicia_templates[formControlClass]";
if ($options['allowVagueDates']) {
$options['afterControl'] = self::apply_static_template('date_picker_mode_toggle', $options);
}
return self::apply_template('date_picker', $options);
}
/**
* Outputs a file upload control suitable for linking images to records.
*