-
Notifications
You must be signed in to change notification settings - Fork 4
/
ElasticsearchProxyHelper.php
3225 lines (3081 loc) · 111 KB
/
ElasticsearchProxyHelper.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 proxy 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 Firebase\JWT\JWT;
use IForm\IndiciaConversions;
/**
* Exception class for request abort.
*/
class ElasticsearchProxyAbort extends Exception {
}
/**
* Helper class with library functions to support Elasticsearch proxying.
*/
class ElasticsearchProxyHelper {
/**
* Elasticsearch config.
*
* @var array
*/
private static $config;
/**
* Track if filter applied specifies confidential flag.
*
* If not specified, then code can apply a default confidential=f filter.
*
* @var bool
*/
private static $confidentialFilterApplied = FALSE;
/**
* Track if filter applied specifies releast_status flag.
*
* If not specified, then code can apply a default releast_status=R filter.
*
* @var bool
*/
private static $releaseStatusFilterApplied = FALSE;
/**
* If a filter is selected in a permissionFilters control, apply scope.
*
* E.g. if a verification filter selected, apply the verification scope.
*
* @var int
* Filter ID.
*/
private static $setScopeUsingFilter;
/**
* Route into the functions provided by the proxy.
*
* @param string $method
* Method name.
* @param int $nid
* Node ID.
*
* @return mixed
* JSON (as object or string, whichever is more efficient).
*/
public static function callMethod($method, $nid) {
self::$config = hostsite_get_es_config($nid);
if (empty(self::$config['es']['endpoint']) ||
(self::$config['es']['auth_method'] === 'directClient' && (empty(self::$config['es']['user']) || empty(self::$config['es']['secret'])))) {
throw new ElasticsearchProxyAbort('Method not allowed as server configuration incomplete', 405);
}
switch ($method) {
case 'attrs':
return self::proxyAttrDetails($nid);
case 'comments':
return self::proxyComments($nid);
case 'doesUserSeeNotifications':
return self::proxyDoesUserSeeNotifications($nid);
case 'download':
return self::proxyDownload($nid);
case 'mediaAndComments':
return self::proxyMediaAndComments($nid);
case 'rawsearch':
return self::proxyRawsearch();
case 'searchbyparams':
return self::proxySearchByParams($nid);
case 'verifyall':
return self::proxyVerifyAll($nid);
case 'verifyspreadsheet':
return self::proxyVerifySpreadsheet();
case 'verifyids':
return self::proxyVerifyIds();
case 'verificationQueryEmail':
return self::proxyVerificationQueryEmail();
case 'redetall':
return self::proxyRedetAll($nid);
case 'redetids':
return self::proxyRedetIds();
case 'bulkmoveall':
return self::proxyBulkMoveAll($nid);
case 'bulkmoveids':
return self::proxyBulkMoveIds($nid);
case 'bulkeditall':
return self::proxyBulkEditAll($nid);
case 'bulkeditids':
return self::proxyBulkEditIds($nid);
case 'bulkeditpreview':
return self::proxyBulkEditPreview();
case 'clearcustomresults':
return self::proxyClearCustomResults($nid);
case 'runcustomruleset':
return self::proxyRunCustomRuleset($nid);
default:
throw new ElasticsearchProxyAbort('Method not found', 404);
}
}
/**
* Retrieve the Elasticsearch endpoint to use.
*
* @return string
* The endpoint name (e.g. es-occurrences).
*/
private static function getEsEndpoint() {
// Request can modify the endpoint, but only if on a list of allowed
// endpoints.
if (!empty($_GET['endpoint']) && !empty(self::$config['es']['alternative_endpoints'])
&& in_array($_GET['endpoint'], helper_base::explode_lines(self::$config['es']['alternative_endpoints']))) {
return $_GET['endpoint'];
}
else {
return self::$config['es']['endpoint'];
}
}
/**
* Returns the URL required to call the Elasticsearch service.
*
* @return string
* URL.
*/
private static function getEsUrl() {
$endpoint = self::getEsEndpoint();
return self::$config['indicia']['base_url'] . "index.php/services/rest/$endpoint";
}
/**
* Ajax method which echoes custom attribute data to the client.
*
* At the moment, this info is built from the Indicia warehouse, not
* Elasticsearch.
*
* @param int $nid
* Node ID to obtain connection info from.
*
* @return array
* Attribute details associative array.
*/
private static function proxyAttrDetails($nid) {
iform_load_helpers(['report_helper']);
$conn = iform_get_connection_details($nid);
$readAuth = helper_base::get_read_auth($conn['website_id'], $conn['password']);
$options = [
'dataSource' => 'reports_for_prebuilt_forms/dynamic_elasticsearch/record_details',
'readAuth' => $readAuth,
// @todo Sharing should be dynamically set in a form parameter (use $nid param).
'sharing' => 'verification',
'extraParams' => ['occurrence_id' => $_GET['occurrence_id']],
];
$reportData = report_helper::get_report_data($options);
// Convert the output to a structured JSON object, including fresh read
// auth tokens.
$data = ['auth' => $readAuth];
// Organise some attributes by system function, so we can make output
// consistent.
$sysFuncAttrs = [];
$sysFuncList = [
'Additional occurrence' => [
'behaviour',
'certainty',
'reproductive_condition',
'sex_stage_count',
'sex',
'stage',
'sex_stage',
],
'Additional sample' => ['biotope'],
];
foreach ($reportData as $key => $attribute) {
if (isset($sysFuncList[$attribute['attribute_type']])
&& in_array($attribute['system_function'], $sysFuncList[$attribute['attribute_type']])) {
$sysFuncAttrs[$attribute['system_function']] = $attribute;
unset($reportData[$key]);
}
}
// Now build the special system function output first.
foreach ($sysFuncList as $heading => $sysFuncs) {
$headingData = [];
foreach ($sysFuncs as $sysFunc) {
if (isset($sysFuncAttrs[$sysFunc])) {
$headingData[] = [
'caption' => $sysFuncAttrs[$sysFunc]['caption'],
'value' => $sysFuncAttrs[$sysFunc]['value'],
'system_function' => $sysFuncAttrs[$sysFunc]['system_function'],
];
}
}
if (!empty($headingData)) {
$data["$heading attributes"] = $headingData;
}
}
// Now the rest.
foreach ($reportData as $attribute) {
if (!empty($attribute['value'])) {
if (!isset($data[$attribute['attribute_type'] . ' attributes'])) {
$data[$attribute['attribute_type'] . ' attributes'] = [];
}
$data[$attribute['attribute_type'] . ' attributes'][] = [
'caption' => $attribute['caption'],
'value' => $attribute['value'],
'system_function' => $attribute['system_function'],
];
}
elseif ($attribute['attribute_type'] === 'Output geom') {
$data['public_geom'] = $attribute['raw_value'];
}
}
return $data;
}
/**
* Provides information on a user's ability to see notifications.
*
* Used when querying records for verification.
*
* @param int $nid
* Node ID.
*
* @return array
* Data to return, containing a messsage indicating the information
* requested.
*/
private static function proxyDoesUserSeeNotifications($nid) {
iform_load_helpers(['VerificationHelper']);
$conn = iform_get_connection_details($nid);
$readAuth = helper_base::get_read_auth($conn['website_id'], $conn['password']);
return ['msg' => VerificationHelper::doesUserSeeNotifications($readAuth, $_GET['user_id'])];
}
/**
* Ajax handler for the [recordDetails] comments tab.
*
* @param int $nid
* Node ID to obtain connection info from.
*
* @return array
* Comments data array loaded from the report.
*
* @todo Consider switch to using VerificationHelper::getComments().
*/
private static function proxyComments($nid) {
iform_load_helpers(['report_helper']);
$conn = iform_get_connection_details($nid);
$readAuth = helper_base::get_read_auth($conn['website_id'], $conn['password']);
$options = [
'dataSource' => 'reports_for_prebuilt_forms/verification_5/occurrence_comments_and_dets',
'readAuth' => $readAuth,
// @todo Sharing should be dynamically set in a form parameter (use $nid param).
'sharing' => 'verification',
'extraParams' => [
'occurrence_id' => $_GET['occurrence_id'],
],
];
$reportData = report_helper::get_report_data($options);
return $reportData;
}
/**
* A search proxy that processes Indicia search info to ES.
*
* @param int $nid
* Node ID.
*
* @return string
* JSON string data returned by Elasticsearch.
*/
private static function proxySearchByParams($nid) {
iform_load_helpers(['helper_base']);
$conn = iform_get_connection_details($nid);
$readAuth = helper_base::get_read_auth($conn['website_id'], $conn['password']);
self::checkPermissionsFilter($_POST, $readAuth, $nid);
$url = self::getEsUrl() . '/_search';
$query = self::buildEsQueryFromRequest($_POST);
return self::curlPost($url, $query);
}
/**
* A search proxy that passes through the data as is.
*
* Should only be used with aggregations where the size parameter is zero to
* avoid permissions issues, as it does not apply the basic permissions
* filter. For example a report page that shows "my records" may also include
* aggregated data across the entire dataset which is not limited by the page
* permissions.
*
* @return string
* JSON string data returned by Elasticsearch.
*/
private static function proxyRawsearch() {
$url = self::getEsUrl() . '/_search';
$query = array_merge($_POST);
$query['size'] = 0;
return self::curlPost($url, $query);
}
/**
* A search proxy that handles build of a CSV download file.
*
* @return string
* JSON string, describing the download process in an object.
*/
private static function proxyDownload($nid) {
$isScrollToNextPage = array_key_exists('scroll_id', $_GET);
if (!$isScrollToNextPage) {
iform_load_helpers(['helper_base']);
$conn = iform_get_connection_details($nid);
$readAuth = helper_base::get_read_auth($conn['website_id'], $conn['password']);
self::checkPermissionsFilter($_POST, $readAuth, $nid);
}
$url = self::getEsUrl() . '/_search?' . self::getPassThroughUrlParams(['format' => 'csv'], [
'aggregation_type',
'uniq_id',
'state',
]);
if (isset($_GET['aggregation_type']) && isset($_GET['uniq_id']) && isset($_GET['state'])) {
// Pass through parameters for aggregation download file chunking.
$url .= "&aggregation_type=$_GET[aggregation_type]";
$url .= "&uniq_id=$_GET[uniq_id]";
$url .= "&state=$_GET[state]";
}
else {
// Download will use Elasticsearch scroll if doing documents.
$url .= '&scroll';
if ($isScrollToNextPage) {
$url .= '&scroll_id=' . $_GET['scroll_id'];
}
}
$query = self::buildEsQueryFromRequest($_POST);
return self::curlPost($url, $query);
}
/**
* Proxy method to retrieve media and comments for emails.
*
* When an email is sent to query a record, the comments and media are
* injected into the HTML. Echoes an array with a media entry and a comments
* entry, both containing the required HTML.
*
* @return array
* Media and comments data.
*/
private static function proxyMediaAndComments($nid) {
iform_load_helpers(['VerificationHelper']);
$conn = iform_get_connection_details($nid);
$readAuth = helper_base::get_read_auth($conn['website_id'], $conn['password']);
$params = array_merge(['sharing' => 'verification'], hostsite_get_node_field_value($nid, 'params'));
return [
'media' => VerificationHelper::getMedia($readAuth, $params, $_GET['occurrence_id'], $_GET['sample_id']),
'comments' => VerificationHelper::getComments($readAuth, $params, $_GET['occurrence_id'], TRUE),
];
}
/**
* Proxy method that receives a list of IDs to verify in Elastic.
*
* Used by the verification system when in checklist mode to allow setting a
* comment and status on multiple records in one go.
*/
private static function proxyVerifyIds() {
if (empty(self::$config['es']['warehouse_prefix'])) {
throw new ElasticsearchProxyAbort('Method not allowed as server configuration incomplete', 405);
}
$statuses = $_POST['doc']['identification'] ?? [];
return [
'updated' => self::internalModifyListOnEs(
$_POST['ids'],
$statuses,
$_POST['doc']['metadata']['website']['id'] ?? NULL
),
];
}
/**
* Retrieve the list of occurrence IDs for an ES filter.
*
* @return array
* List of occurrence IDs.
*/
private static function getOccurrenceIdsFromFilter($nid, $filter) {
iform_load_helpers(['helper_base']);
$conn = iform_get_connection_details($nid);
$readAuth = helper_base::get_read_auth($conn['website_id'], $conn['password']);
self::checkPermissionsFilter($filter, $readAuth, $nid);
$url = self::getEsUrl() . '/_search';
$query = self::buildEsQueryFromRequest($filter);
// Limit response for efficiency.
$_GET['filter_path'] = 'hits.hits._source.id';
// Maximum 10000.
$query['size'] = 10000;
$r = self::curlPost($url, $query);
$esResponse = json_decode($r);
unset($_GET['filter_path']);
$ids = [];
foreach ($esResponse->hits->hits as $item) {
$ids[] = $item->_source->id;
}
return $ids;
}
/**
* Retrieve a page of occurrence IDs for an ES filter.
*
* Similar to getOccurrenceIdsFromFilter but retrieves a smaller batch of
* record IDs, with search_after information that can be used in the next
* request in order to paginate through the data. Ensures each batch of
* records is divided on a sample ID (event.event_id) boundary so that
* checks for complete samples don't fail.
*
* @param int $nid
* Node ID.
* @param array $filter
* Filted definition.
* @param array $searchAfter
* Values to pass to the search_after option on ES, in order to request the
* next page of data, or NULL for the first page.
*
* @return array
* Associative array containing a search_after property to be used in the
* next request and and ids property containing a list of occurrence IDs.
*/
private static function getOccurrenceIdPageFromFilter($nid, $filter, $searchAfter) {
iform_load_helpers(['helper_base']);
$conn = iform_get_connection_details($nid);
$readAuth = helper_base::get_read_auth($conn['website_id'], $conn['password']);
self::checkPermissionsFilter($filter, $readAuth, $nid);
$url = self::getEsUrl() . '/_search';
$query = self::buildEsQueryFromRequest($filter);
$query['sort'] = [
['event.event_id' => 'asc'],
['id' => 'asc'],
];
if ($searchAfter) {
$query['search_after'] = $searchAfter;
}
// Limit response for efficiency.
$_GET['filter_path'] = 'hits.hits._source.id,hits.hits._source.event.event_id';
// Maximum 1000 - should be more than the max size of a sample.
$query['size'] = 1000;
$r = self::curlPost($url, $query);
$esResponse = json_decode($r);
unset($_GET['filter_path']);
if (empty($esResponse->hits) || empty($esResponse->hits->hits)) {
return ['ids' => []];
}
if (count($esResponse->hits->hits) >= $query['size']) {
// Find the last event_id as we need to skip records for this sample, in
// case there is a paging split within the sample.
$lastEventId = $esResponse->hits->hits[count($esResponse->hits->hits) - 1]->_source->event->event_id;
}
else {
// Set dummy value to disable event ID filter, as all remaining records
// have been found.
$lastEventId = -1;
}
$ids = [];
$searchAfter = [];
foreach ($esResponse->hits->hits as $item) {
if ($item->_source->event->event_id !== $lastEventId) {
$ids[] = $item->_source->id;
$searchAfter = [$item->_source->event->event_id, $item->_source->id];
}
}
return [
'ids' => $ids,
'search_after' => $searchAfter,
];
}
/**
* Apply verification or redet action to all records in the current filter.
*
* @param int $nid
* Node ID.
* @param array $statuses
* Record status data to update.
* @param int $websiteIdToModify
* Set to 0 if clearing the website ID as a temporary measure to disable
* records after redetermination, until Logstash fills in the taxonomy
* again.
*
* @return int
* Number of updated records.
*/
private static function processWholeEsFilter($nid, array $statuses, $websiteIdToModify = NULL) {
if (empty(self::$config['es']['warehouse_prefix'])) {
throw new ElasticsearchProxyAbort('Method not allowed as server configuration incomplete', 405);
}
if (empty($_POST['website_id'])) {
throw new ElasticsearchProxyAbort('Missing website_id parameter', 400);
}
$ids = self::getOccurrenceIdsFromFilter($nid, $_POST['occurrence:idsFromElasticFilter']);
self::internalModifyListOnEs($ids, $statuses, $websiteIdToModify);
try {
self::updateWarehouseVerificationAction($ids, $nid);
}
catch (Exception $e) {
throw new ElasticsearchProxyAbort('Error whilst updating warehouse records: ' . $e->getMessage(), 500);
}
return count($ids);
}
/**
* Proxy method to apply verification change to entire results set.
*
* Uses a filter definition passed in the post to retrieve the records from
* ES then applies the decision to all aof them.
*
* @return array
* Data to return from the proxy request, including the number of updated
* records.
*/
private static function proxyVerifyAll($nid) {
$statuses = [
'verification_status' => $_POST['occurrence:record_status'],
'verification_substatus' => empty($_POST['occurrence:record_substatus']) ? 0 : $_POST['occurrence:record_substatus'],
];
return [
'updated' => self::processWholeEsFilter($nid, $statuses),
];
}
/**
* Applies an uploaded spreadsheet containing verification decisions.
*
* Forwards the spreadsheet to the /occurrences/verify-spreadsheet end-point,
* applying the decisons to the records on the warehouse. The client JS code
* should call this multiple times, the first time with the file in a POSTed
* field called decisions, then subsequently send back the fileId (returned
* in the response metadata). This will process the file in chunks, which
* should continue until the response contains state=done.
*/
private static function proxyVerifySpreadsheet() {
$url = self::$config['indicia']['base_url'] . 'index.php/services/rest/occurrences/verify-spreadsheet';
if (isset($_FILES['decisions'])) {
// Initial file upload.
$file = $_FILES['decisions'];
$payload = [
'decisions' => curl_file_create($file['tmp_name'], $file['type'], $file['name']),
'filter_id' => $_POST['filter_id'],
'user_id' => hostsite_get_user_field('indicia_user_id'),
'es_endpoint' => $_POST['es_endpoint'],
'id_prefix' => $_POST['id_prefix'],
'warehouse_name' => $_POST['warehouse_name'],
];
}
else {
if (!empty($_POST['fileId'])) {
// Subsequent processing request.
$payload = [
'fileId' => $_POST['fileId'],
];
}
}
if (empty($payload)) {
throw new ElasticsearchProxyAbort('Missing decisions file or fileId parameter', 400);
}
return self::curlPost($url, $payload, [], TRUE);
}
/**
* Proxy method that receives a list of IDs to redet in Elastic.
*
* Used by the verification system when in checklist mode to allow setting a
* redetermination on multiple records in one go.
*/
private static function proxyRedetIds() {
if (empty(self::$config['es']['warehouse_prefix'])) {
throw new ElasticsearchProxyAbort('Method not allowed as server configuration incomplete', 405);
}
// Set website ID to 0, basically disabling the ES copy of the record until
// a proper update with correct taxonomy information comes through.
return [
'updated' => self::internalModifyListOnEs($_POST['ids'], [], 0),
];
}
/**
* Proxy method that redetermines all records in the current filter.
*/
private static function proxyRedetAll($nid) {
// Set website ID to 0, basically disabling the ES copy of the record until
// a proper update with correct taxonomy information comes through.
return [
'updated' => self::processWholeEsFilter($nid, [], 0),
];
}
/**
* Proxy method to send an email querying a record.
*/
private static function proxyVerificationQueryEmail() {
$emailBody = $_POST['body'];
// Format correct HTML.
$emailBody = str_replace("\n", '<br/>', $emailBody);
// Send email. Depends upon settings in php.ini being correct.
$success = hostsite_send_email($_POST['to'], $_POST['subject'], $emailBody);
return [
'status' => $success ? 'OK' : 'Fail',
];
}
/**
* Creates a query string for the URL to pass through.
*
* Only passes through parameters in $_GET where the key matches one of the
* provided.
*
* @param array $default
* List of paramaters that should appear in the query string no matter
* what.
* @param array $params
* Names of $_GET keys that will be copied into the resulting query string
* if provided.
*/
private static function getPassThroughUrlParams(array $default, array $params) {
$query = $default;
foreach ($params as $param) {
if (!empty($_GET[$param])) {
$query[$param] = $_GET[$param];
}
}
return http_build_query($query);
}
/**
* Apply verification result to a list of occurrences on ES.
*
* Used by both update for multi-select checkboxes and the entire data table.
*
* @param array $ids
* List of occurrence IDs.
* @param array $statuses
* Status data to apply (verification_status, verification_substatus,
* query).
* @param int $websiteIdToModify
* If changing the website ID (i.e. setting to 0 to temporarily hide the
* record), set it here.
*
* @return int
* Number of records updated.
*/
private static function internalModifyListOnEs(array $ids, array $statuses, $websiteIdToModify) {
$url = self::getEsUrl() . "/_update_by_query";
$scripts = [];
if (!empty($statuses['verification_status'])) {
$scripts[] = "ctx._source.identification.verification_status = '" . $statuses['verification_status'] . "'";
}
if (!empty($statuses['verification_substatus'])) {
$scripts[] = "ctx._source.identification.verification_substatus = '" . $statuses['verification_substatus'] . "'";
}
if (!empty($statuses['query'])) {
$scripts[] = "ctx._source.identification.query = '" . $statuses['query'] . "'";
}
if ($websiteIdToModify !== NULL) {
$scripts[] = "ctx._source.metadata.website.id = '" . $websiteIdToModify . "'";
}
if (empty($scripts)) {
throw new exception('Unsupported field for update. ' . var_export($_POST['doc'], TRUE));
}
$_ids = [];
// Convert Indicia IDs to the document _ids for ES. Also make a 2nd version
// for full precision copies of sensitive records.
foreach ($ids as $id) {
$_ids[] = self::$config['es']['warehouse_prefix'] . $id;
$_ids[] = self::$config['es']['warehouse_prefix'] . "$id!";
}
$doc = [
'script' => [
'source' => implode("; ", $scripts),
'lang' => 'painless',
],
'query' => [
'terms' => [
'_id' => $_ids,
],
],
];
// Update index and overwrite update conflicts.
$r = self::curlPost($url, $doc, [
'conflicts' => 'proceed',
]);
$rObj = json_decode($r);
// Since the verification alias can only see 1 copy of each record (e.g.
// full precision), the total in the response will correspond to the number
// of occurrences updated.
return $rObj->updated;
}
/**
* When updating an entire ES filter result, also update the warehouse.
*
* Since we want to be sure that the warehouse update changes exactly the
* same set of records as in the current ES filter, the proxy takes
* responsibility for the warehouse update as well.
*
* @param array $ids
* List of occurrence IDs.
* @param int $nid
* Node ID for authentication.
*/
private static function updateWarehouseVerificationAction(array $ids, $nid) {
$data = [
'website_id' => $_POST['website_id'],
'user_id' => $_POST['user_id'],
'occurrence:ids' => implode(',', $ids),
];
if (!empty($_POST['occurrence_comment:comment'])) {
$data['occurrence_comment:comment'] = $_POST['occurrence_comment:comment'];
}
if (!empty($_POST['occurrence:record_status'])) {
$data['occurrence:record_decision_source'] = 'H';
$data['occurrence:record_status'] = $_POST['occurrence:record_status'];
}
if (!empty($_POST['occurrence:record_substatus'])) {
$data['occurrence:record_substatus'] = $_POST['occurrence:record_substatus'];
}
if (!empty($_POST['occurrence:taxa_taxon_list_id'])) {
$data['occurrence:taxa_taxon_list_id'] = $_POST['occurrence:taxa_taxon_list_id'];
// Switch endpoint if redetermining.
$action = 'list_redet';
}
else {
$action = 'list_verify';
}
$conn = iform_get_connection_details($nid);
$auth = helper_base::get_read_write_auth($conn['website_id'], $conn['password']);
$request = helper_base::$base_url . "index.php/services/data_utils/$action";
$postargs = helper_base::array_to_query_string(array_merge($data, $auth['write_tokens']), TRUE);
$response = helper_base::http_post($request, $postargs);
if ($response['output'] !== 'OK') {
throw new exception($response['output']);
}
}
/**
* Retrieves the required HTTP headers for an Elasticsearch request.
*
* Header sets content type to application/json and adds an Authorization
* header appropriate to the method.
*
* @param array $config
* Elasticsearch configuration.
* @param string $contentType
* Content type, defaults to application/json.
*
* @return array
* Header strings.
*/
public static function getHttpRequestHeaders($config, $contentType = 'application/json') {
$headers = [
"Content-Type: $contentType",
];
if (empty($config['es']['auth_method']) || $config['es']['auth_method'] === 'directClient') {
$headers[] = 'Authorization: USER:' . $config['es']['user'] . ':SECRET:' . $config['es']['secret'];
}
elseif ($config['es']['auth_method'] === 'directWebsite') {
iform_load_helpers(['helper_base']);
$conn = iform_get_connection_details();
$tokens = [
'WEBSITE_ID',
$conn['website_id'],
'SECRET',
$conn['password'],
];
if (isset($config['es']['scope'])) {
$tokens[] = 'SCOPE';
$tokens[] = $config['es']['scope'];
$userId = hostsite_get_user_field('indicia_user_id');
if ($userId) {
$tokens[] = 'USER_ID';
$tokens[] = $userId;
}
}
$headers[] = 'Authorization: ' . implode(':', $tokens);
}
else {
$keyFile = \Drupal::service('file_system')->realpath("private://") . '/private.key';
if (!file_exists($keyFile)) {
// Fall back on legacy setup.
$keyFile = \Drupal::service('file_system')->realpath("private://") . '/rsa_private.pem';
}
if (!file_exists($keyFile)) {
\Drupal::logger('iform')->error('Missing private key file for jwtUser Elasticsearch authentication.');
throw new ElasticsearchProxyAbort('Method not allowed as server configuration incomplete', 405);
}
$privateKey = file_get_contents($keyFile);
$payload = [
'iss' => rtrim(hostsite_get_url('<front>', [], FALSE, TRUE), '/'),
'http://indicia.org.uk/user:id' => hostsite_get_user_field('indicia_user_id'),
'scope' => $config['es']['scope'],
'exp' => time() + 300,
];
$modulePath = \Drupal::service('module_handler')->getModule('iform')->getPath();
// @todo persist the token in the cache?
require_once "$modulePath/lib/php-jwt/vendor/autoload.php";
$token = JWT::encode($payload, $privateKey, 'RS256');
$headers[] = "Authorization: Bearer $token";
}
return $headers;
}
/**
* A simple wrapper for the cUrl functionality to POST to Elastic.
*
* @param string $url
* Warehouse REST API Elasticsearch endpoint URL.
* @param array $data
* ES request object. Can contain a property `proxyCacheTimeout` if the
* response should be cached for a number of seconds.
* @param array $getParams
* Optional query string parameters to add to the URL, e.g. _source.
* @param bool $multipart
* Set to TRUE if doint a multi-part form submission.
*/
public static function curlPost($url, array $data, array $getParams = [], $multipart = FALSE) {
$curlResponse = FALSE;
$cacheTimeout = FALSE;
if (!empty($data['proxyCacheTimeout'])) {
$cacheKey = [
'post' => json_encode($data),
'get' => json_encode($getParams),
];
$curlResponse = helper_base::cacheGet($cacheKey);
if ($curlResponse) {
$curlResponse = json_decode($curlResponse, TRUE);
}
else {
$cacheTimeout = $data['proxyCacheTimeout'];
}
unset($data['proxyCacheTimeout']);
}
if (!$curlResponse) {
$allowedGetParams = ['filter_path'];
// Additional GET params should only be used if valid for ES.
foreach ($allowedGetParams as $param) {
if (!empty($_GET[$param])) {
$getParams[$param] = $_GET[$param];
}
}
if (count($getParams)) {
$url .= '?' . http_build_query($getParams);
}
$session = curl_init($url);
curl_setopt($session, CURLOPT_POST, 1);
curl_setopt($session, CURLOPT_POSTFIELDS, $multipart ? $data : json_encode($data));
curl_setopt($session, CURLOPT_HTTPHEADER, self::getHttpRequestHeaders(self::$config, $multipart ? 'multipart/form-data' : 'application/json'));
curl_setopt($session, CURLOPT_REFERER, $_SERVER['HTTP_HOST']);
curl_setopt($session, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($session, CURLOPT_HEADER, FALSE);
curl_setopt($session, CURLOPT_RETURNTRANSFER, TRUE);
// Do the POST and then close the session.
$response = curl_exec($session);
$curlResponse = [
'output' => $response,
'headers' => curl_getinfo($session),
'httpCode' => curl_getinfo($session, CURLINFO_HTTP_CODE),
];
curl_close($session);
}
// Check for an error, or check if the http response was not OK.
if ($curlResponse['httpCode'] != 200) {
http_response_code($curlResponse['httpCode']);
}
elseif ($cacheTimeout) {
helper_base::array_to_query_string($cacheKey);
helper_base::cacheSet($cacheKey, json_encode($curlResponse), $cacheTimeout);
}
return $curlResponse['output'];
}
/**
* Confirm that a permissions filter in the request is allowed for the user.
*
* For example, permissions may be different for accessing my vs all records
* so this method checks against the Drupal permissions defined on the edit
* tab, ensuring calls to the proxy can't be easily hacked.
*
* @param array $post
* Section of the $_POST data which holds the filter info.
* @param array $readAuth
* Read authentication tokens.
* @param int $nid
* Node ID to load configuration from.
*/
private static function checkPermissionsFilter(array $post, array $readAuth, $nid) {
$permissionsFilter = empty($post['permissions_filter']) ? 'p-all' : $post['permissions_filter'];
$roleBasedPermissionsFilters = [
'p-all',
'p-my',
'p-location_collation',
];
$permissionName = substr($permissionsFilter, 2) . '_records_permission';
if (in_array($permissionsFilter, $roleBasedPermissionsFilters)) {
if (!hostsite_user_has_permission(self::$config['es'][$permissionName])) {
throw new ElasticsearchProxyAbort("User does not have permission to $permissionName", 401);
}
}
else {
$options = ['readAuth' => $readAuth];
iform_load_helpers(['ElasticsearchReportHelper']);
if ($nid) {
// Fetch available permissions filters for node.
$nodeParams = hostsite_get_node_field_value($nid, 'params');
if (!empty($nodeParams['structure'])) {
$structure = helper_base::explode_lines($nodeParams['structure']);
$state = 'search';
foreach ($structure as $line) {
if ($line === '[permissionFilters]') {
$state = 'foundControl';
}
elseif ($state === 'foundControl') {
if (substr($line, 0, 1) === '@') {
$parts = explode('=', $line, 2);
$decoded = json_decode($parts[1]);
$options[substr($parts[0], 1)] = $decoded ?? $parts[1];
}
else {
// Finish loop as done permissionFilters control options.
break;
}
}
}
}
}
$availablePermissionFilters = ElasticsearchReportHelper::getPermissionFiltersOptions($options);
// Check $permissionsFilter in list, else access denied.
if (!array_key_exists($permissionsFilter, $availablePermissionFilters)) {
throw new ElasticsearchProxyAbort("Unauthorised - $permissionsFilter not in " . var_export($availablePermissionFilters, TRUE), 401);
}
}
}
/**
* Convert a posted request to an ES query.
*
* @param array $post
* Posted request data.
*/