-
Notifications
You must be signed in to change notification settings - Fork 4
/
ElasticsearchReportHelper.php
2856 lines (2760 loc) · 116 KB
/
ElasticsearchReportHelper.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
/**
* @file
* A helper class for Elasticsearch reporting code.
*
* 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
*/
use IForm\IndiciaConversions;
/**
* A helper class for Elasticsearch reporting code.
*/
class ElasticsearchReportHelper {
/**
* Count controls to make unique IDs.
*
* @var int
*/
private static $controlIndex = 0;
/**
* Track control IDs so warning can be given if duplicate IDs are used.
*
* @var array
*/
private static $controlIds = [];
private static $esMappings;
/**
* Has the ES proxy been setup on this page?
*
* @var bool
* Set to true when done to prevent double-initialisation.
*/
private static $proxyEnabled = FALSE;
/**
* Remember if an attempt made to enable which failed.
*
* @var bool
*/
private static $proxyEnableFailed = FALSE;
/**
* List of ES fields with caption and description for each.
*
* @internal
*/
const MAPPING_FIELDS = [
'@timestamp' => [
'caption' => 'Indexing timestamp',
'description' => 'Timestamp when the record was indexed into to the reporting system.',
],
'id' => [
'caption' => 'ID',
'description' => 'Unique record ID.',
],
'event.event_id' => [
'caption' => 'Sample ID',
'description' => 'Unique sample ID.',
],
'#datasource_code#' => [
'caption' => 'Datasource codes',
'description' => 'Website and survey dataset the record is sourced from, in abbreviated encoded form.',
],
'#status_icons#' => [
'caption' => 'Record status icons',
'description' => "Icons showing the record's verification status and sensitivity information.",
],
'#data_cleaner_icons#' => [
'caption' => 'Automated checks',
'description' => "Icons showing the results of automated checks on the record.",
],
'metadata.created_on' => [
'caption' => 'Submitted on',
'description' => 'Date the record was submitted.',
],
'metadata.licence_code' => [
'caption' => 'Licence',
'description' => 'Code for the licence that applies to the record.',
],
'metadata.website.id' => [
'caption' => 'Website ID',
'description' => 'Unique ID of the website the record was submitted from.',
],
'metadata.website.title' => [
'caption' => 'Website title',
'description' => 'Title of the website the record was submitted from.',
],
'metadata.survey.id' => [
'caption' => 'Survey dataset ID',
'description' => 'Unique ID of the survey dataset the record was submitted to.',
],
'metadata.survey.title' => [
'caption' => 'Survey dataset title',
'description' => 'Title of the survey dataset the record was submitted to.',
],
'metadata.group.id' => [
'caption' => 'Group ID',
'description' => 'Unique ID of the recording group the record was submitted to.',
],
'metadata.group.title' => [
'caption' => 'Group title',
'description' => 'Title of the recording group the record was submitted to.',
],
'metadata.import_guid' => [
'caption' => 'Import GUID',
'description' => 'Unique identifier for the import that this records was added by, if relevant.',
],
'#event_date#' => [
'caption' => 'Date',
'description' => 'Date of the record.',
],
'event.day_of_year' => [
'caption' => 'Day of year',
'description' => 'Numeric day within the year of the record (1-366).',
],
'event.month' => [
'caption' => 'Month',
'description' => 'Numeric month of the record.',
],
'event.year' => [
'caption' => 'Year',
'description' => 'Year of the record.',
],
'event.event_remarks' => [
'caption' => 'Sample comment',
'description' => 'Comment given for the sample by the recorder.',
],
'event.habitat' => [
'caption' => 'Habitat',
'description' => 'Habitat recorded for the sample.',
],
'event.recorded_by' => [
'caption' => 'Recorder name(s)',
'description' => 'Name of the people involved in the field record.',
],
'event.sampling_protocol' => [
'caption' => 'Sample method',
'description' => 'Method for the sample if provided.',
],
'identification.identified_by' => [
'caption' => 'Identified by',
'description' => 'Identifier (determiner) of the record.',
],
'identification.recorder_certainty' => [
'caption' => 'Recorder certainty',
'description' => 'Certainty that the identification is correct as attributed by the recorder.',
],
'identification.verifier.name' => [
'caption' => 'Verifier name',
'description' => "Name of the verifier responsible for record's current verification status.",
],
'identification.verified_on' => [
'caption' => 'Verified on',
'description' => "Date/time of the current verification decision.",
],
'identification.verification_decision_source' => [
'caption' => 'Verification decision source',
'description' => 'Either M for machine based verification or H for human verification decisions.',
],
'taxon.taxon_name' => [
'caption' => 'Taxon name',
'description' => 'Name as recorded for the taxon.',
],
'taxon.taxon_name_authorship' => [
'caption' => 'Taxon name author',
'description' => 'Author and date of the recorded accepted name.',
],
'taxon.accepted_name' => [
'caption' => 'Accepted name',
'description' => 'Currently accepted name for the recorded taxon.',
],
'taxon.accepted_name_authorship' => [
'caption' => 'Accepted name author',
'description' => 'Author and date of the published accepted name.',
],
'taxon.vernacular_name' => [
'caption' => 'Common name',
'description' => 'Common name for the recorded taxon.',
],
'#taxon_label#' => [
'caption' => 'Taxon label',
'description' => 'Combination of accepted and common name.',
],
'taxon.group' => [
'caption' => 'Taxon group',
'description' => 'Taxon reporting group associated with the current identification of this record.',
],
'taxon.kingdom' => [
'caption' => 'Kingdom',
'description' => 'Taxonomic kingdom associated with the current identification of this record.',
],
'taxon.phylum' => [
'caption' => 'Phylum',
'description' => 'Taxonomic phylum associated with the current identification of this record.',
],
'taxon.class' => [
'caption' => 'Class',
'description' => 'Taxonomic class associated with the current identification of this record.',
],
'taxon.order' => [
'caption' => 'Order',
'description' => 'Taxonomic order associated with the current identification of this record.',
],
'taxon.family' => [
'caption' => 'Family',
'description' => 'Taxonomic family associated with the current identification of this record.',
],
'taxon.subfamily' => [
'caption' => 'Subfamily',
'description' => 'Taxonomic subfamily associated with the current identification of this record.',
],
'taxon.taxon_rank' => [
'caption' => 'Taxon rank',
'description' => 'Taxonomic rank associated with the current identification of this record.',
],
'taxon.genus' => [
'caption' => 'Genus',
'description' => 'Taxonomic genus associated with the current identification of this record.',
],
'taxon.species' => [
'caption' => 'Species',
'description' => 'Species name associated with the current identification of this record. Will still return the species ranked name where the record is of a taxon below species level.',
],
'taxon.species_authorship' => [
'caption' => 'Species name author',
'description' => 'Species name author and date associated with the current identification of this record. Will still return the species ranked name\'s author where the record is of a taxon below species level.',
],
'taxon.species_vernacular' => [
'caption' => 'Species common name',
'description' => 'Species name associated with the current identification of this record. Will still return the species ranked name where the record is of a taxon below species level.',
],
'location.verbatim_locality' => [
'caption' => 'Location name',
'description' => 'Location name associated with the record.',
],
'location.name' => [
'caption' => 'Location',
'description' => 'Location associated with the record where the record was linked to a defined location.',
],
'location.location_id' => [
'caption' => 'Location ID',
'description' => 'Unique ID of the location associated with the record where the record was linked to a defined location.',
],
'location.parent_name' => [
'caption' => 'Parent location',
'description' => 'Parent location associated with the record where the record was linked to a defined location which has a hierarchical parent.',
],
'location.parent_location_id' => [
'caption' => 'Parent location ID',
'description' => 'Unique ID of the parent location associated with the record where the record was linked to a defined location which has a hierarchical parent.',
],
'location.output_sref' => [
'caption' => 'Display spatial reference',
'description' => 'Spatial reference in the recommended local grid system.',
],
'location.output_sref_system' => [
'caption' => 'Display spatial reference system',
'description' => 'System used for the spatial reference in the recommended local grid system.',
],
'location.input_sref' => [
'caption' => 'Input spatial reference',
'description' => 'Spatial reference as input by the recorder.',
],
'location.input_sref_system' => [
'caption' => 'Input spatial reference system',
'description' => 'System used for the spatial reference as input by the recorder.',
],
'location.coordinate_uncertainty_in_meters' => [
'caption' => 'Coordinate uncertainty in metres',
'description' => 'Uncertainty of a provided GPS point.',
],
'#lat_lon#' => [
'caption' => 'Lat/lon',
'description' => 'Latitude and longitude of the record.',
],
'#occurrence_media#' => [
'caption' => 'Media',
'description' => 'Thumbnails for any occurrence photos and other media.',
],
'occurrence.sex' => [
'caption' => 'Sex',
'description' => 'Sex of the recorded organism',
],
'occurrence.life_stage' => [
'caption' => 'Life stage',
'description' => 'Life stage of the recorded organism.',
],
'occurrence.individual_count' => [
'caption' => 'Count',
'description' => 'Numeric abundance count of the recorded organism.',
],
'occurrence.organism_quantity' => [
'caption' => 'Quantity',
'description' => 'Abundance of the recorded organism (numeric or text).',
],
'occurrence.occurrence_remarks' => [
'caption' => 'Occurrence comment',
'description' => 'Comment given for the occurrence by the recorder.',
],
];
/**
* Prepares the page for interacting with the Elasticsearch proxy.
*
* @param int $nid
* Node ID or NULL if not on a node.
*
* @return bool
* True if enabled, false if there was an error and it failed to enable.
*
* @link https://indicia-docs.readthedocs.io/en/latest/site-building/iform/helpers/elasticsearch-report-helper.html#elasticsearchreporthelper-enableelasticsearchproxy
*/
public static function enableElasticsearchProxy($nid = NULL) {
if (!self::$proxyEnabled && !self::$proxyEnableFailed) {
// Retrieve the Elasticsearch mappings.
try {
$config = hostsite_get_es_config($nid);
self::getMappings($config);
helper_base::add_resource('datacomponents');
// Prepare the stuff we need to pass to the JavaScript.
$mappings = self::$esMappings;
$esProxyAjaxUrl = hostsite_get_url('iform/esproxy');
helper_base::$indiciaData['esProxyAjaxUrl'] = $esProxyAjaxUrl;
helper_base::$indiciaData['esSources'] = [];
helper_base::$indiciaData['esMappings'] = $mappings;
helper_base::$indiciaData['gridMappingFields'] = self::MAPPING_FIELDS;
helper_base::$indiciaData['esVersion'] = (int) $config['es']['version'];
helper_base::$indiciaData['esScope'] = $config['es']['scope'];
self::$proxyEnabled = TRUE;
}
catch (Exception $e) {
self::$proxyEnableFailed = TRUE;
\Drupal::logger('iform')->error('Elasticsearch proxy enable failed: ' . $e->getMessage());
}
}
return self::$proxyEnabled;
}
/**
* An Elasticsearch bulk editor tool.
*
* @return string
* Button container HTML.
*
* @link https://indicia-docs.readthedocs.io/en/latest/site-building/iform/helpers/elasticsearch-report-helper.html#elasticsearchreporthelper-bulkeditor
*/
public static function bulkEditor(array $options) {
self::checkOptions(
'bulkEditor',
$options,
['linkToDataControl'],
[]
);
$options = array_merge([
'caption' => 'Bulk edit records',
'restrictToOwnData' => TRUE,
], $options);
$dataOptions = helper_base::getOptionsForJs($options, [
'id',
'linkToDataControl',
'restrictToOwnData',
], TRUE);
helper_base::addLanguageStringsToJs('bulkEditor', [
'allowSampleSplitting' => 'Allow sample splitting?',
'bulkEditorDialogMessageAll' => 'You are about to edit the entire list of <span>{1}</span> records.',
'bulkEditorDialogMessageSelected' => 'You are about to edit <span>{1}</span> selected records.',
'bulkEditProgress' => 'Edited {samples} samples and {occurrences} occurrences.',
'cannotProceed' => 'Cannot proceed',
'confirm' => 'Confirm',
'done' => 'Records successfully edited. They will now be processed so they are available with their new values shortly.',
'error' => 'An error occurred whilst trying to edit the records.',
'errorEditNotFilteredToCurrentUser' => 'The records cannot be edited because the current page is not filtered to limit the records to only your data.',
'noUpdatesSpecified' => 'Please specify the values you would like to update using the form before previewing the changes.',
'noValue' => '-value not set-',
'preparing' => 'Preparing to edit the records...',
'promptAllowSampleSplit' => '<p>The list of records to update contains occurrences which belong to samples that contain other occurrences which are not being updated. ' .
'For example, sample {1} contains an occurrence {2} which is being updated, but it also contains occurrence {3} which is not being updated.</p>' .
'<p>Please confirm that you would like to split the samples so that the data values for the list of records you are editing can be updated without affecting other occurrences in the same samples.</p>',
'warningNoChanges' => 'Please define at least one field value that you would like to change when bulk editing the records.',
'warningNothingToDo' => 'There are no selected records to edit.',
]);
$lang = [
'bulkEditRecords' => lang::get($options['caption']),
'cancel' => lang::get('Cancel'),
'close' => lang::get('Close'),
'editing' => lang::get('Editing records'),
'editInstructions' => 'Specify values to apply to all the edited records in the following controls, or leave blank for the data values to remain unchanged.',
'preview' => lang::get('Preview'),
'previewInfo' => lang::get('The following table shows a selection of the records you are about to bulk edit. This is just a sample of the records about to be updated.'),
'proceed' => lang::get('Proceed'),
];
helper_base::add_resource('fancybox');
$recorderNameControl = data_entry_helper::text_input([
'fieldname' => 'edit-recorder-name',
'label' => lang::get('Recorder name'),
]);
$dateControl = data_entry_helper::date_picker([
'fieldname' => 'edit-date',
'label' => lang::get('Date'),
]);
$locationNameControl = data_entry_helper::text_input([
'fieldname' => 'edit-location-name',
'label' => lang::get('Location name'),
]);
$srefControl = data_entry_helper::sref_and_system([
'fieldname' => 'edit-sref',
'label' => lang::get('Spatial reference'),
'findMeButton' => FALSE,
]);
global $indicia_templates;
$html = <<<HTML
<button type="button" class="bulk-edit-records-btn $indicia_templates[buttonHighlightedClass]">$lang[bulkEditRecords]</button>
<div style="display: none">
<div id="$options[id]-dlg" class="bulk-editor-dlg">
<h2>$lang[bulkEditRecords]</h2>
<p class="message"></p>
<p>$lang[editInstructions]</p>
<div class="bulk-edit-form-controls">
$recorderNameControl
$dateControl
$locationNameControl
$srefControl
</div>
<div class="preview-output" style="display: none">
<p class="alert alert-warning"><i class="fas fa-exclamation-triangle fa-2x"></i> $lang[previewInfo]</p>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Species</th>
<th>Common name</th>
<th>Date</th>
<th>Location</th>
<th>Grid ref</th>
<th>Recorded by</th>
</tr>
<thead>
<tbody>
</tbody>
</table>
</div>
<div class="form-buttons bulk-edit-action-buttons">
<button type="button" class="$indicia_templates[buttonHighlightedClass] preview-bulk-edit">$lang[preview]</button>
<button type="button" class="$indicia_templates[buttonHighlightedClass] proceed-bulk-edit" disabled>$lang[proceed]</button>
<button type="button" class="$indicia_templates[buttonHighlightedClass] close-bulk-edit-dlg">$lang[cancel]</button>
</div>
<div class="post-bulk-edit-info">
<h2>$lang[editing]</h2>
<div class="output"></div>
<div class="form-buttons">
<button type="button" class="$indicia_templates[buttonHighlightedClass] close-bulk-edit-dlg" disabled="disabled">$lang[close]</button>
</div>
</div>
</div>
</div>
HTML;
return self::getControlContainer('bulkEditor', $options, $dataOptions, $html);
}
/**
* An Elasticsearch records card gallery.
*
* @return string
* Gallery container HTML.
*
* @link https://indicia-docs.readthedocs.io/en/latest/site-building/iform/helpers/elasticsearch-report-helper.html#elasticsearchreporthelper-cardgallery
*/
public static function cardGallery(array $options) {
self::checkOptions(
'cardGallery',
$options,
['source'],
[
'actions',
'columns',
'rowsPerPageOptions',
]
);
$options = array_merge([
'class' => 'flexgrid',
], $options);
helper_base::addLanguageStringsToJs('cardGallery', [
'checkToIncludeInList' => 'Check this box to include the record in the list which any verification actions will be applied to.',
'collapseCard' => 'Return card to normal size (C or +)',
'expandCard' => 'Expand this card (C or +)',
'fullScreenToolHint' => 'Click to view grid in full screen mode',
'noHeading' => 'no heading',
'clickToSort' => 'Click on the data value to sort by:',
'sortConfiguration' => 'Sort configuration',
'sortToolHint' => 'Click to select the sort order',
]);
$lang = [
'next' => lang::get('Next record'),
'prev' => lang::get('Previous record'),
];
// Map options alias, so consistent with dataGrid.
if (isset($options['sortable']) && !isset($options['includeSortTool'])) {
$options['includeSortTool'] = $options['sortable'];
}
$dataOptions = helper_base::getOptionsForJs($options, [
'actions',
'columns',
'class',
'includeFieldCaptions',
'includeFullScreenTool',
'includeMultiSelectTool',
'includePager',
'includeSortTool',
'keyboardNavigation',
'rowsPerPageOptions',
'source',
], TRUE);
// Extra setup required after gallery loads.
helper_base::$late_javascript .= <<<JS
$('#$options[id]').idcCardGallery('bindControls');
JS;
return self::getControlContainer('cardGallery', $options, $dataOptions) . <<<HTML
<div id="card-nav-buttons-cntr" style="display: none">
<div id="card-nav-buttons">
<button class="nav-prev indicia-button" title="$lang[prev]"><span class="fas fa-caret-left"></span></button>
<button class="nav-next indicia-button" title="$lang[next]"><span class="fas fa-caret-right"></span></button>
</div>
</div>
HTML;
}
/**
* A control for managing layout, e.g. for verification pages.
*
* @link https://indicia-docs.readthedocs.io/en/latest/site-building/iform/helpers/elasticsearch-report-helper.html#elasticsearchreporthelper-controllayout
*/
public static function controlLayout(array $options) {
self::checkOptions(
'controlLayout',
$options,
['setOriginY'],
[
'alignTop',
'alignBottom',
'setHeightPercent',
]
);
$options = array_merge([
'breakpoint' => 992,
'alignTop' => [],
'alignBottom' => [],
'setHeightPercent' => [],
], $options);
$options = array_intersect_key($options, [
'alignTop' => NULL,
'alignBottom' => NULL,
'breakpoint' => NULL,
'setHeightPercent' => NULL,
'setOriginY' => NULL,
]);
helper_base::$indiciaData['esControlLayout'] = $options;
}
/**
* A control for flexibly outputting data formatted using a custom script.
*
* @link https://indicia-docs.readthedocs.io/en/latest/site-building/iform/helpers/elasticsearch-report-helper.html#elasticsearchreporthelper-customscript
*/
public static function customScript(array $options) {
self::checkOptions('customScript', $options, ['source', 'functionName'], []);
$options = array_merge([
'template' => '',
], $options);
$dataOptions = helper_base::getOptionsForJs($options, [
'source',
'functionName',
], TRUE);
return self::getControlContainer('customScript', $options, $dataOptions, $options['template']);
}
/**
* An Elasticsearch or Indicia powered grid control.
*
* @return string
* Grid container HTML.
*
* @link https://indicia-docs.readthedocs.io/en/latest/site-building/iform/helpers/elasticsearch-report-helper.html#elasticsearchreporthelper-datagrid
*/
public static function dataGrid(array $options) {
self::checkOptions(
'dataGrid',
$options,
['source'],
[
'actions',
'applyFilterRowToSources',
'availableColumns',
'columns',
'responsiveOptions',
'rowClasses',
'rowsPerPageOptions',
]
);
if (!empty($options['scrollY']) && !preg_match('/^-?\d+px$/', $options['scrollY'])) {
throw new Exception('Control [dataGrid] @scrollY parameter must be of CSS pixel format, e.g. 100px');
}
if (isset($options['columns'])) {
foreach ($options['columns'] as &$columnDef) {
if (empty($columnDef['field'])) {
throw new Exception('Control [dataGrid] @columns option does not contain a field for every item.');
}
if (!isset($columnDef['caption'])) {
$columnDef['caption'] = '';
}
// To aid transition from older code versions, auto-enable the media
// special field handling. This may be removed in future.
if ($columnDef['field'] === 'occurrence.media') {
$columnDef['field'] = '#occurrence_media#';
}
}
}
helper_base::add_resource('sortable');
helper_base::add_resource('font_awesome');
helper_base::add_resource('indiciaFootableReport');
// Add footableSort for simple aggregation tables.
if (!empty($options['aggregation']) && $options['aggregation'] === 'simple') {
helper_base::add_resource('footableSort');
}
// Fancybox for image popups.
helper_base::add_resource('fancybox');
helper_base::addLanguageStringsToJs('dataGrid', [
'checkToIncludeInList' => 'Check this box to include the record in the list which any verification actions will be applied to.',
'columnSettingsToolHint' => 'Click to show grid column settings',
'fullScreenToolHint' => 'Click to view grid in full screen mode',
'noHeading' => 'no heading',
'siteNameWitheld' => 'Site name witheld as record is sensitive or private.',
'status' => 'Status',
]);
$dataOptions = helper_base::getOptionsForJs($options, [
'actions',
'applyFilterRowToSources',
'availableColumns',
'autoResponsiveCols',
'autoResponsiveExpand',
'columns',
'cookies',
'includeColumnHeadings',
'includeColumnSettingsTool',
'includeFilterRow',
'includeFullScreenTool',
'includeMultiSelectTool',
'includePager',
'keyboardNavigation',
'responsive',
'responsiveOptions',
'rowClasses',
'rowsPerPageOptions',
'scrollY',
'source',
'sortable',
], TRUE);
// Extra setup required after grid loads.
helper_base::$late_javascript .= <<<JS
$('#$options[id]').idcDataGrid('bindControls');
JS;
$lang = [
'cancel' => lang::get('Cancel'),
'columnConfigIntro' => lang::get('The following columns are available for this table. Tick the ones you want to include. Drag and drop the columns into your preferred order.'),
'columnConfiguration' => lang::get('Column configuration'),
'restoreDefaults' => lang::get('Restore defaults'),
'save' => lang::get('Save'),
'toggleTick' => lang::get('Tick/untick all'),
];
$content = <<<HTML
<div class="loading-spinner" style="display: none">
<div>Loading...</div>
</div>
<div class="data-grid-settings-cntr" style="display: none">
<div class="data-grid-settings" data-el="$options[id]">
<h3>$lang[columnConfiguration]</h3>
<p>$lang[columnConfigIntro]</p>
<div>
<button class="btn btn-default toggle">$lang[toggleTick]</button>
<button class="btn btn-default restore">$lang[restoreDefaults]</button>
<button class="btn btn-default cancel">$lang[cancel]</button>
<button class="btn btn-primary save">$lang[save]</button>
</div>
<ol></ol>
</div>
</div>
HTML;
return self::getControlContainer('dataGrid', $options, $dataOptions, $content);
}
/**
* A button for downloading the ES data from a source.
*
* @return string
* HTML for download button and progress display.
*
* @link https://indicia-docs.readthedocs.io/en/latest/site-building/iform/helpers/elasticsearch-report-helper.html#elasticsearchreporthelper-download
*/
public static function download(array $options) {
// Compatibility with legacy config.
if (!empty($options['linkToDataGrid'])) {
$options['linkToDataControl'] = $options['linkToDataGrid'];
}
self::checkOptions('esDownload', $options,
[['source', 'linkToDataControl']],
['addColumns', 'removeColumns', 'sort']
);
if (empty($options['source']) && !empty($options['columnsTemplate'])) {
throw new Exception('Download control @source option must be specified if @columnsTemplate option is used (cannot be used with @linkToDataControl).');
}
$options = array_merge([
'caption' => 'Download',
'title' => 'Download information',
], $options);
// If columnsTemplate options specifies an array, then create control
// options for a select control that will be used to indicate the selected
// columns template.
if (!empty($options['columnsTemplate']) && is_array($options['columnsTemplate'])) {
$availableColTypes = [
"easy-download" => lang::get("Standard download format"),
"mapmate" => lang::get("Simple download format"),
];
$optionArr = [];
foreach ($options['columnsTemplate'] as $colType) {
$optionArr[$colType] = $availableColTypes[$colType];
}
$controlOptions = [
'id' => "$options[id]-template",
'fieldname' => 'columnsTemplate',
'lookupValues' => $optionArr,
];
unset($options['columnsTemplate']);
}
global $indicia_templates;
$button = str_replace(
[
'{id}',
'{title}',
'{class}',
'{caption}',
], [
"$options[id]-button",
lang::get($options['title']),
"class=\"$indicia_templates[buttonHighlightedClass] do-download\"",
lang::get($options['caption']) . '<span class="fas fa-file-download"></span>',
],
$indicia_templates['button']
);
if (isset($controlOptions)) {
$html = "<div class=\"idc-download-ctl-part\">$button</div>";
$html .= '<div class="idc-download-ctl-part">' . data_entry_helper::select($controlOptions) . '</div>';
}
else {
$html = $button;
}
$progress = <<<HTML
<div class="progress-circle-container">
<svg>
<circle class="circle"
cx="-90"
cy="90"
r="80"
style="stroke-dashoffset:503px;"
stroke-dasharray="503"
transform="rotate(-90)" />
</svg>
<div class="progress-text"></div>
</div>
HTML;
$html .= str_replace(
[
'{attrs}',
'{col-1}',
'{col-2}',
], [
'',
$progress,
'<div class="idc-download-files"><h2>' . lang::get('Files') . ':</h2></div>',
],
$indicia_templates['two-col-50']);
// This does nothing at the moment - just a placeholder for if and when we
// add some download options.
$dataOptions = helper_base::getOptionsForJs($options, [
'addColumns',
'aggregation',
'buttonContainerElement',
'columnsTemplate',
'columnsSurveyId',
'linkToDataControl',
'removeColumns',
'sort',
'source',
], TRUE);
return self::getControlContainer('esDownload', $options, $dataOptions, $html);
}
/**
* A scale for grid square opacity.
*
* Showing the number of records for each level.
*
* @param array $options
* Control options.
*
* @return string
* Scale container HTML.
*
* @link https://indicia-docs.readthedocs.io/en/latest/site-building/iform/helpers/elasticsearch-report-helper.html#elasticsearchreporthelper-gridsquareopacityscale
*/
public static function gridSquareOpacityScale(array $options) {
self::checkOptions('gridSquareOpacityScale', $options,
['linkToDataControl', 'layer'],
[]
);
helper_base::addLanguageStringsToJs('gridSquareOpacityScale', [
'noOfRecords' => 'No. of records',
]);
$dataOptions = helper_base::getOptionsForJs($options, [
'id',
'linkToDataControl',
'layer',
], TRUE);
return self::getControlContainer('gridSquareOpacityScale', $options, $dataOptions);
}
/**
* Integrates the page with groups (activities).
*
* @param array $options
* Control options.
* @param bool $checkPage
* Set to false to disable checking that the current page path is an iform
* page linked to the group.
*
* @link https://indicia-docs.readthedocs.io/en/latest/site-building/iform/helpers/elasticsearch-report-helper.html#elasticsearchreporthelper-groupintegration
*
* @return string
* Control HTML
*/
public static function groupIntegration(array $options, $checkPage = TRUE) {
$options = array_merge([
'missingGroupIdBehaviour' => 'error',
'showGroupSummary' => FALSE,
'showGroupPages' => FALSE,
], $options);
if (isset($options['group_id'])) {
$group_id = $options['group_id'];
$implicit = array_key_exists('implicit', $options) ? $options['implicit'] : FALSE;
}
elseif (!empty($_GET['group_id'])) {
$group_id = $_GET['group_id'];
$implicit = array_key_exists('implicit', $_GET) ? $_GET['implicit'] : FALSE;
}
if (empty($group_id) && $options['missingGroupIdBehaviour'] !== 'showAll') {
hostsite_show_message(lang::get('The link you have followed is invalid.'), 'warning', TRUE);
hostsite_goto_page('<front>');
return '';
}
require_once 'prebuilt_forms/includes/groups.php';
$membership = group_get_user_membership($group_id, $options['readAuth'], $checkPage);
$output = '';
if (!empty($group_id)) {
$groups = data_entry_helper::get_population_data([
'table' => 'group',
'extraParams' => $options['readAuth'] + [
'view' => 'detail',
'id' => $group_id,
]
]);
if (!count($groups)) {
hostsite_show_message(lang::get('The link you have followed is invalid.'), 'warning', TRUE);
hostsite_goto_page('<front>');
return '';
}
$group = $groups[0];
// Apply filtering by group.
$groupFilterInfo = [
'id' => $group['id'],
'implicit' => IndiciaConversions::toBool($implicit),
'container' => IndiciaConversions::toBool($group['container']),
'contained_by_group_id' => $group['contained_by_group_id'],
];
helper_base::$indiciaData['applyGroupFilter'] = $groupFilterInfo;
if ($options['showGroupSummary'] || $options['showGroupPages']) {
if ($options['showGroupSummary']) {
$output .= self::getGroupSummaryHtml($group);
}
if ($options['showGroupPages']) {
$output .= self::getGroupPageLinksHtml($group, $options, $membership);
}
}
$filterBoundaries = helper_base::get_population_data([
'report' => 'library/groups/group_boundary_transformed',
'extraParams' => $options['readAuth'] + ['group_id' => $group_id],
'cachePerUser' => FALSE,
]);
if (count($filterBoundaries) > 0) {
helper_base::$indiciaData['reportBoundaries'] = [];
foreach ($filterBoundaries as $boundary) {
helper_base::$indiciaData['reportBoundaries'][] = $boundary['boundary'];
}
helper_base::$late_javascript .= <<<JS
indiciaFns.loadReportBoundaries();
JS;
}
}
return $output;
}
/**
* Return the HTML for a summary panel for a group.
*
* @param array $group
* Group data loaded from the database.
*
* @return string
* HTML for the panel.
*/
public static function getGroupSummaryHtml(array $group) {
$path = data_entry_helper::get_uploaded_image_folder();
$logo = empty($group['logo_path']) ? '' : "<img style=\"width: 30%; float: left; padding: 0 5% 5%;\" alt=\"Logo\" src=\"$path$group[logo_path]\"/>";
$msg = "<h3>$group[title]</h3>";
if (!empty($group['description'])) {
$msg .= "<p>$group[description]</p>";
}
return $logo . $msg;
}
/**
* Return an array with information required to create a group's page links.
*
* @param array $group
* Group data loaded from the database.
* @param array $options
* [groupIntegration] control options. Can include joinLink=true to add a
* link for joining for non-members and a class name for the links in
* linkClass. Provide an option called editPath with a path to the group
* edit page, this will generate a link for admins to edit the group
* metadata.
* @param GroupMembership $membership
* Current user's membership or admin status.
* @param bool $caching
* Set to false to disable caching (e.g. if in a cached Drupal block).
*
* @return array
* List of links with label and icon info.
*/
public static function getGroupPageLinksArray(array $group, array $options, GroupMembership $membership, $caching = TRUE): array {
$pageData = data_entry_helper::get_population_data([
'table' => 'group_page',
'extraParams' => $options['readAuth'] + [
'group_id' => $group['id'],
'query' => json_encode(['in' => ['administrator' => ['', 'f']]]),
'orderby' => 'caption',
],
'caching' => $caching,
'cachePerUser' => FALSE,
]);
$links = [];
$options = array_merge([
'containedGroupLabel' => 'sub-group',
], $options);
if ($membership === GroupMembership::NonMember && ($group['joining_method'] === 'P' || $group['joining_method'] === 'I')) {
$titleForLink = trim(preg_replace('/[^a-z0-9\-]/', '', preg_replace('/[ ]/', '-', strtolower($group['title']))), '-');
$titleEscaped = htmlspecialchars($group['title']);
$links["/join/$titleForLink"] = ['label' => "Join $titleEscaped", 'icon' => '<i class="fas fa-file-signature"></i>'];
}
if ($membership === GroupMembership::Admin && isset($options['editPath'])) {
$editLink = helper_base::getRootFolder() . $options['editPath'] . "?group_id=$group[id]&redirect_on_success=" . hostsite_get_current_page_path();
$links[$editLink] = ['label' => lang::get('Edit'), 'icon' => '<i class="fas fa-pen"></i>'];
if (!empty($group['container'])) {
$addSubGroupLink = helper_base::getRootFolder() . $options['editPath'] . "?container_group_id=$group[id]&redirect_on_success=" . hostsite_get_current_page_path();
$links[$addSubGroupLink] = ['label' => lang::get('Add {1}', $options['containedGroupLabel']), 'icon' => '<i class="fas fa-folder-plus"></i>'];
}