-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathimport_helper.php
More file actions
1956 lines (1891 loc) · 90.1 KB
/
Copy pathimport_helper.php
File metadata and controls
1956 lines (1891 loc) · 90.1 KB
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
* Helper class for data imports.
*
* 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/warehouse/
*/
/**
* Link in other required php files.
*/
require_once 'lang.php';
require_once 'helper_base.php';
define('EMBED_REUPLOAD_OFF', 0);
define('EMBED_REUPLOAD_ERRORS_ONLY', 1);
define('EMBED_REUPLOAD_ON', 2);
/**
* Static helper class that provides methods for dealing with imports.
*/
class import_helper extends helper_base {
/**
* Can host system support remembered mappings?
*
* Flag set to true if the host system is capable of storing our user's
* remembered import mappings for future imports.
*
* @var bool
*
*/
private static $rememberingMappings = TRUE;
/**
* @var array List of field to column mappings that we managed to set automatically
*/
private static $automaticMappings = [];
/**
* Outputs an import wizard.
*
* The csv file to be imported should be available in the $_POST data.
* Additionally, if there are any preset values which apply to each row in
* the import data then you can pass these to the importer in the $_POST
* data. For example, you could set taxa_taxon_list:taxon_list_id=3 in the
* $_POST data when importing species data to force it to go into list 3.
*
* @param array $options
* Options array with the following possibilities:
* * **model** - Required. The name of the model data is being imported
* into.
* * **auth** - Read and write authorisation tokens.
* * **presetSettings** - Optional associative array of any preset values
* for the import settings. Any settings which have a presetSetting
* specified will be ommitted from the settings form.
* * **occurrenceAssociations** - set to true to enable import of
* associated occurrences or false to disable it. Default false.
* * **fieldMap** - array of configurations of the fields available to
* import, one per survey. The importer will generate a list of all
* possible fields in the database to import into for a given survey.
* This typically includes all the standard "core" database fields such
* as species name and sample date, as well as a list of all custom
* attributes for a survey. This list is quite long and some of the
* default core database fields provided might not be appropriate to your
* survey dataset, leading to possible confusion. So you can use this
* parameter to define database fields and column titles in the
* spreadsheet that will automatically map to them. Provide an array,
* with each array entry being an associative array containing the
* definition of the fields for 1 survey dataset. In the associative
* array provide a value called survey_id to link this definition to a
* survey dataset. Also provide a value called fields containing a list
* of database fields you are defining for this dataset, one per line. If
* you want to link this field to a column title then follow the database
* field name with an equals, then the column title, e.g.
* sample:date=Record date or occAttr:fk_293=Life stage.
* * **onlyAllowMappedFields** - set to true and supply field mappings in
* the fieldMap parameter to ensure that only the fields you have
* specified for the selected survey will be available for selection.
* This allows you to hide all the import fields that you don't want to
* be used for importing into a given survey dataset, thus tidying up the
* list of options to improve ease of use. Default true.
* * **skipMappingIfPossible** - set to true to completely bypass the field
* to column mappings setup stage of the import tool if all the columns
* in the supplied spreadsheet are mapped. Combine this with the fieldMap
* parameter to make predefined import configurations that require little
* effort to use as long as a matching spreadsheet structure is supplied.
* * **embed_reupload** - set to EMBED_REUPLOAD_ON to embed an upload form
* into the page shown on completion of an upload, allowing another file
* to be uploaded. Or, set to EMBED_REUPLOAD_ERRORS_ONLY to embed the
* upload form into this page only when the last upload had errors, in
* which case a message is shown explaining that the user can use the
* form to upload the errors file. Defaults to EMBED_REUPLOAD_OFF.
* * **importPreventCommitBehaviour** - default is 'partial_import' which
* allows working rows to commit and reports errors on failing rows.
* 'user_defined' displays a checkbox allowing the user to select which
* behaviour to use and 'prevent' prevents any commit if there are any
* errors.
* * **importSampleLogic** - @todo Document.
* * **allowExcel** - set to TRUE to enable experimental Excel import.
* Currently defaults to false but may change to true when the Excel
* import development is stable.
*
* @return string
* HTML for the next page of the importer.
*
* @throws \exception
*/
public static function importer($options) {
$options = array_merge([
// Default is to allow working rows to commit and only report errors on
// failing rows.
'importPreventCommitBehaviour' => 'partial_import',
// Default which to not use sample example key for verification.
'importSampleLogic' => 'consecutive_rows',
'allowExcel' => TRUE,
], $options);
// Currently the preventCommitsOnError on error option won't work with existing data updates.
// Hopefully this will change in the future, the problem is the preserve_fields function does
// not currently preserve the existing data lookup selections because preserve fields was coded first.
if (!empty($_POST['preventCommitsOnError']) && $_POST['preventCommitsOnError'] == TRUE) {
self::$javascript .= "
$('#lookupSelectsample').attr('disabled', 'disabled');
$('#lookupSelectoccurrence').attr('disabled', 'disabled');
$('#lookup-mode-warning').show();";
}
self::add_resource('jquery_ui');
self::add_resource('import');
// If there is no upload total yet and no import step we know to show the
// very first screen.
if (!isset($_POST['import_step']) && !isset($_POST['total'])) {
if (count($_FILES) === 1) {
return self::importSettingsForm($options);
}
else {
return self::uploadForm($options);
}
}
elseif (isset($_POST['import_step']) && $_POST['import_step'] == 1) {
// If we have the Prevent Commits On Any Error option on, then the first pass of the upload
// process will always be to check errors and not commit to DB, so set variable to control this
if ((isset($_POST['preventCommitsOnError'])&&$_POST['preventCommitsOnError'] == TRUE)||
(isset($_POST['setting']['preventCommitsOnError'])&&$_POST['setting']['preventCommitsOnError'] == TRUE)) {
$options['allowCommitToDB'] = FALSE;
}
else {
$options['allowCommitToDB'] = TRUE;
}
return self::uploadMappingsForm($options);
// Import step 2 is only shown if the preventCommitsOnError option has been set.
// This means we don't commit any rows at all if any errors are found, therefore we need
// an extra error checking step
}
elseif ((isset($_POST['import_step']) && $_POST['import_step'] == 2)) {
$options['allowCommitToDB'] = FALSE;
return self::runUpload($options);
}
elseif ((isset($_POST['import_step']) && $_POST['import_step'] == 3)) {
$options['allowCommitToDB'] = TRUE;
return self::runUpload($options);
}
elseif (isset($_POST['total']) && empty($_POST['import_step'])) {
return self::uploadResult($options);
}
else {
throw new exception('Invalid importer state');
}
}
/**
* Returns the HTML for a simple file upload form.
*/
private static function uploadForm($options) {
$reload = self::get_reload_link_parts();
$reloadpath = $reload['path'] . '?' . self::array_to_query_string($reload['params']);
$r = '<form action="' . $reloadpath . '" method="post" enctype="multipart/form-data">';
$excel = $options['allowExcel'] ? ' or Excel (*.xls, *.xlsx)' : '';
$r .= '<label for="upload">' . lang::get("Select Comma Separated Values (*.csv)$excel file to upload") . ':</label>';
$r .= '<input type="file" name="upload" id="upload"/>';
$r .= '<input type="Submit" value="' . lang::get('Upload') . '"></form>';
return $r;
}
/**
* Generates the import settings form.
*
* If none available, then outputs the upload mappings form.
*
* @param array $options
* Options array passed to the import control.
*/
private static function importSettingsForm(array $options) {
$_SESSION['uploaded_file'] = self::uploadFile($options);
// By this time, we should always have an existing file.
if (empty($_SESSION['uploaded_file'])) {
throw new Exception('File to upload could not be found');
}
$request = parent::$base_url . "index.php/services/import/get_import_settings/" . $options['model'];
$request .= '?' . self::array_to_query_string($options['auth']['read']);
$switches = isset($options['switches']) && is_array($options['switches']) ? $options['switches'] : [];
if (!empty($options['occurrenceAssociations'])) {
$switches['occurrence_associations'] = 't';
}
$request .= '&' . self::array_to_query_string($switches);
$response = self::http_post($request, []);
if (!empty($response['output'])) {
// Get the path back to the same page.
$reload = self::get_reload_link_parts();
$reloadpath = $reload['path'] . '?' . self::array_to_query_string($reload['params']);
$r = '<div class="page-notice ui-state-highlight ui-corner-all">' . lang::get('import_settings_instructions') . "</div>\n" .
"<form method=\"post\" id=\"entry_form\" action=\"$reloadpath\" class=\"iform\">\n" .
"<fieldset><legend>" . lang::get('Import Settings') . "</legend>\n";
$formArray = json_decode($response['output'], TRUE);
if (!is_array($formArray)) {
if (class_exists('kohana')) {
kohana::log('error', 'Problem occurred during upload. Sent request to get_import_settings and received invalid response.');
kohana::log('error', "Request: $request");
kohana::log('error', 'Response: ' . print_r($response, TRUE));
}
return 'Could not upload file. Please check that the indicia_svc_import module is enabled on the Warehouse.';
}
$formOptions = array(
'form' => $formArray,
'readAuth' => $options['auth']['read'],
'nocache' => TRUE,
);
if (isset($options['presetSettings'])) {
// Skip parts of the form we have a preset value for.
$formOptions['extraParams'] = $options['presetSettings'];
}
else {
$formOptions['extraParams'] = [];
}
// Copy any $_POST data into the extraParams, as this would mean preset
// values that are provided by the form which the uploader was triggered
// from. E.g. if on a species checklist, this could be this checklists ID
// which the user does not need to pick.
foreach ($_POST as $key => $value) {
$formOptions['extraParams'][$key] = $value;
}
$form = self::build_params_form($formOptions, $hasVisibleContent);
// If there are no settings required, skip to the next step.
if (!$hasVisibleContent) {
return self::uploadMappingsForm($options);
}
$r .= $form;
if (isset($options['presetSettings'])) {
// The presets might contain some extra values to apply to every row -
// must be output as hiddens.
$extraHiddens = array_diff_key($options['presetSettings'], $formArray);
unset($extraHiddens['password']);
foreach ($extraHiddens as $hidden => $value) {
$r .= "<input type=\"hidden\" name=\"$hidden\" value=\"$value\" />\n";
}
}
// If import behaviour is to be specified by the user, then provide
// options on the screen for them. If not specified by the user they
// must be hidden in the background.
if (($options['importPreventCommitBehaviour'] === 'user_defined') ||
($options['importSampleLogic'] === 'user_defined' && ($options['model'] === 'occurrence'||$options['model'] === 'sample'))) {
$r .= '<hr>';
}
// In this case the administrator has specific on the Edit Tab that any
// errors will prevent the import. Keep this information in a hidden
// checkbox.
if ($options['importPreventCommitBehaviour'] === 'prevent') {
$r .= '<input type="checkbox" style="display:none;" name="preventCommitsOnError" checked>';
}
// In this case the administrator has specific on the Edit Tab that any
// errors will only affect affected rows and working rows can be
// committed. Keep this information in a hidden checkbox.
if ($options['importPreventCommitBehaviour'] === 'partial_import') {
$r .= '<input type="checkbox" style="display:none;" name="preventCommitsOnError" >';
}
// Admin has specified that user can provide option so display to screen.
if ($options['importPreventCommitBehaviour'] === 'user_defined') {
$r .= data_entry_helper::checkbox(array(
'label' => lang::get('Reject entire import if there are any errors'),
'fieldname' => 'preventCommitsOnError',
'helpText' => 'Select this checkbox to prevent the importing of any rows ' .
'if there are any errors at all. Leave this checkbox switched off to import valid rows. Please note: Functionality to update ' .
'existing data is currently disabled when this option is selected, only new data can be imported.'
));
}
// Same logic for other behaviour option.
if ($options['importSampleLogic'] === 'sample_ext_key') {
$r .= '<input type="checkbox" style="display:none;" name="verifySamplesUsingExternalKey" checked>';
}
if ($options['importSampleLogic'] === 'consecutive_rows') {
$r .= '<input type="checkbox" style="display:none;" name="verifySamplesUsingExternalKey" >';
}
if ($options['importSampleLogic'] === 'user_defined' && ($options['model'] === 'occurrence' || $options['model'] === 'sample')) {
$r .= data_entry_helper::checkbox([
'label' => lang::get('Samples verified by sample key field'),
'fieldname' => 'verifySamplesUsingExternalKey',
'helpText' => 'Select this checkbox to verify imported samples using the sample external key field to determine consistency between the imported rows. '.
'e.g. occurrences with the same external key on the row cannot have different sample dates. Note that rows for the same sample must still be placed consecutively in the import file.'
]);
}
$r .= '<input type="hidden" name="import_step" value="1" />';
$r .= '<input type="submit" name="submit" value="' . lang::get('Next') . '" class="ui-corner-all ui-state-default button" />';
// Copy any $_POST data into the form, as this would mean preset values
// that are provided by the form which the uploader was triggered from.
// E.g. if on a species checklist, this could be this checklists ID which
// the user does not need to pick.
foreach ($_POST as $key => $value) {
$r .= "<input type=\"hidden\" name=\"$key\" value=\"$value\" />\n";
}
$r .= '</fieldset></form>';
return $r;
}
else {
// No settings form, so output the mappings form instead which is the
// next step.
return self::uploadMappingsForm($options);
}
}
/**
* Outputs the form for mapping columns to the import fields.
*
* @param array $options
* Options array passed to the import control.
*/
private static function uploadMappingsForm(array $options) {
$t = self::getTranslations([
'Because you are looking up existing records to import into, required field validation will only be applied when the new data are merged into the existing data during import.',
'Column in import File',
'column_mapping_instructions',
'Maps to attribute',
'Tasks',
'The following database attributes must be matched to a column in your import file before you can continue',
'There are currently two or more drop-downs allocated to the same value.',
'Used in lookup of existing data?',
]);
self::addLanguageStringsToJs('import', [
'lookup_selected_help' => '{1} with the same {2} as rows in the import file will be updated.',
'lookup_unavailable_reason' => 'Looking up {1} based on {2} requires {3} to match but {4} {5} in your import.',
'not_available_plural' => 'are not available',
'not_available_singular' => 'is not available',
'not_imported' => 'Not imported',
'value_plural' => 'values',
'value_singular' => 'value',
'unavailable_lookup_options' => 'Unavailable lookup options',
]);
$filename = basename($_SESSION['uploaded_file']);
$mappingsAndSettings = self::getMappingsAndSettings($options);
$settings = $mappingsAndSettings['settings'];
$request = parent::$base_url . "index.php/services/import/get_import_fields/" . $options['model'];
$request .= '?' . self::array_to_query_string($options['auth']['read']);
// Include survey and website information in the request if available, as
// this limits the availability of custom attributes.
if (!empty($settings['website_id'])) {
$request .= '&website_id=' . trim($settings['website_id']);
}
if (!empty($settings['survey_id'])) {
$request .= '&survey_id=' . trim($settings['survey_id']);
}
if (!empty($settings['useAssociations']) && $settings['useAssociations']) {
$request .= '&use_associations=true';
}
if (($options['model'] === 'sample' || $options['model'] === 'occurrence')
&& isset($settings['sample:sample_method_id'])
&& trim($settings['sample:sample_method_id']) !== '') {
$request .= '&sample_method_id=' . trim($settings['sample:sample_method_id']);
}
elseif ($options['model'] === 'location'
&& isset($settings['location:location_type_id'])
&& trim($settings['location:location_type_id']) !== '') {
$request .= '&location_type_id=' . trim($settings['location:location_type_id']);
}
elseif ($options['model'] === 'taxa_taxon_list'
&& isset($settings['taxa_taxon_list:taxon_list_id'])
&& trim($settings['taxa_taxon_list:taxon_list_id']) !== '') {
$request .= '&taxon_list_id=' . trim($settings['taxa_taxon_list:taxon_list_id']);
}
$response = self::http_post($request, []);
$fields = json_decode($response['output'], TRUE);
if (!is_array($fields)) {
return "curl request to $request failed. Response " . print_r($response, TRUE);
}
// Restrict the fields if there is a setting for this survey Id.
if (!empty($settings['survey_id'])) {
self::limitFields($fields, $options, $settings['survey_id']);
}
if (isset($options['importMergeFields']) && is_string($options['importMergeFields'])) {
$options['importMergeFields'] = json_decode($options['importMergeFields']);
}
if (isset($options['synonymProcessing']) && is_string($options['synonymProcessing'])) {
$options['synonymProcessing'] = json_decode($options['synonymProcessing']);
}
if (isset($options['importMergeFields']) && $options['importMergeFields'] != '' && $options['importMergeFields'] != '{}') {
foreach ($options['importMergeFields'] as $modelSpec) {
if (!isset($modelSpec->model) || ($modelSpec->model = $options['model'])) {
foreach ($modelSpec->fields as $fieldSpec) {
foreach ($fieldSpec->virtualFields as $subFieldSpec) {
// Merge the field in at the end on the similar fields.
$newFields = [];
$parts = explode(':', $fieldSpec->fieldName);
$lastMatch = FALSE;
foreach ($fields as $key => $value) {
$keyParts = explode(':', $key);
if ($lastMatch && $keyParts[0] != $parts[0]) {
$lastMatch = FALSE;
$newFields[$fieldSpec->fieldName . ':' . $subFieldSpec->fieldNameSuffix] = lang::get($subFieldSpec->description) .
' (' . lang::get('merged to form {1}', lang::get($fieldSpec->description)) . ')';
}
elseif (!$lastMatch && $keyParts[0] === $parts[0]) {
$lastMatch = TRUE;
}
$newFields[$key] = $value;
}
if ($lastMatch) {
$newFields[$fieldSpec->fieldName . ':' . $subFieldSpec->fieldNameSuffix] = lang::get($subFieldSpec->description) .
' (' . lang::get('merged to form {1}', lang::get($fieldSpec->description)) . ')';
}
$fields = $newFields;
}
}
}
}
}
if (isset($options['synonymProcessing'])) {
$synonymProcessing = $options['synonymProcessing'];
if (isset($synonymProcessing->separateSynonyms) && $synonymProcessing->separateSynonyms === TRUE) {
$fields['synonym:tracker'] = lang::get("Main record vs Synonym");
$fields['synonym:identifier'] = lang::get("Field to group records together");
}
}
$request = str_replace('get_import_fields', 'get_required_fields', $request);
$response = self::http_post($request);
$responseIds = json_decode($response['output'], TRUE);
if (!is_array($responseIds)) {
return "curl request to $request failed. Response " . print_r($response, TRUE);
}
$model_required_fields = self::expand_ids_to_fks($responseIds);
$preset_fields = !empty($settings) ? self::expand_ids_to_fks(array_keys(array_filter($settings))) : [];
$unlinked_fields = !empty($preset_fields) ? array_diff_key($fields, array_combine($preset_fields, $preset_fields)) : $fields;
// Only use the required fields that are available for selection - the rest
// are handled somehow else.
$unlinked_required_fields = array_intersect($model_required_fields, array_keys($unlinked_fields));
$columns = self::getImportFileColumns($options);
$reload = self::get_reload_link_parts();
$reloadpath = $reload['path'] . '?' . self::array_to_query_string($reload['params']);
self::clear_website_survey_fields($unlinked_fields, $settings);
self::clear_website_survey_fields($unlinked_required_fields, $settings);
$autoFieldMappings = self::getAutoFieldMappings($options, $settings);
$fieldMap = self::getFieldMap($options, $settings);
// If the user checked the Remember All checkbox need to remember this
// setting.
$checkedRememberAll = isset($autoFieldMappings['rememberall']) ? ' checked="checked"' : '';
$r = <<<HTML
<form method="post" id="entry_form" action="$reloadpath" class="iform">
<p>{$t['column_mapping_instructions']}</p>
<div class="ui-helper-clearfix import-mappings-table">
<table class="ui-widget ui-widget-content">
<thead class="ui-widget-header">
<tr><th>{$t['Column in import File']}</th><th>{$t['Maps to attribute']}</th>
HTML;
if (self::$rememberingMappings) {
$r .= "<th>" . lang::get('Remember choice?') .
"<br/><input type='checkbox' name='RememberAll' id='RememberAll' value='1' title='" .
lang::get('Tick all boxes to remember every column mapping next time you import.') . "'$checkedRememberAll/></th>";
self::$javascript .= "
$('#RememberAll').on('change', function() {
if (this.checked) {
$(\".rememberField\").attr(\"checked\",\"checked\")
} else {
$(\".rememberField\").removeAttr(\"checked\")
}
});\n";
}
$request = str_replace('get_required_fields', 'get_existing_record_options', $request);
$response = self::http_post($request);
// The $existingDataLookupOptions variable holds the required fields that must be filled in for a particular existing lookup option to work
// e.g. external_key can't be used unless external_key is filled in
// However these options come from the importDuplicateCheckCombinations option in the model, some fields from here are not suitable for use
// and if left in cause problems. Remove this options (held in $importDuplicateCheckCombinationsToRemove)
$existingDataLookupOptions = [];
$importDuplicateCheckCombinations = json_decode($response['output'], TRUE);
if (isset($importDuplicateCheckCombinations[$options['model']])) {
$importDuplicateCheckCombinationsToRemove = array('taxa_taxon_list:taxon_id', 'sample:sample_method_id');
foreach ($importDuplicateCheckCombinations[$options['model']] as $idx => $importDuplicateCheckCombination) {
foreach ($importDuplicateCheckCombination['fields'] as $idx2 => $field) {
if (!empty($field['fieldName']) && in_array($field['fieldName'], $importDuplicateCheckCombinationsToRemove)) {
unset($importDuplicateCheckCombinations[$options['model']][$idx]['fields'][$idx2]);
}
}
}
$existingDataLookupOptions = $importDuplicateCheckCombinations;
if (!is_array($existingDataLookupOptions)) {
// There is a possibility that the warehouse is not as advanced as the form: in this case we carry on as if no options are avaailable.
$existingDataLookupOptions = [];
}
if (count($existingDataLookupOptions) > 0) {
$r .= "<th>{$t['Used in lookup of existing data?']}</th>";
}
}
$r .= '</tr></thead><tbody>';
$importableColCount = 0;
foreach ($columns as $column) {
$column = trim($column ?? '');
if (!empty($column)) {
if (!in_array($column, ['Number of problems', 'Problem description', 'Row no.', 'Import ID'])) {
$importableColCount++;
}
$colFieldName = self::columnMachineName($column);
$r .= "<tr><td>$column</td><td><select name=\"$colFieldName\" id=\"$colFieldName\">";
$r .= self::getColumnOptions(
$options['model'],
$unlinked_fields,
$column,
$autoFieldMappings,
$fieldMap,
count($existingDataLookupOptions) > 0,
array_key_exists('allowDataDeletions', $options) ? $options['allowDataDeletions'] : FALSE
);
$r .= "</select></td></tr>\n";
}
}
$r .= <<<HTML
</tbody>
</table>
<div id="import-mappings-instructions">
<h2>$t[Tasks]</h2>
<div id="required-instructions">
<span>{$t['The following database attributes must be matched to a column in your import file before you can continue']}</span>
<ul></ul>
<br/>
</div>
<div id="updating-instructions">
<span>{$t['Because you are looking up existing records to import into, required field validation will only be applied when the new data are merged into the existing data during import.']}</span>
<br/>
</div>
<div id="duplicate-instructions">
<span id="duplicate-instruct">{$t['There are currently two or more drop-downs allocated to the same value.']}</span>
<ul></ul>
<br/>
</div>
</div>
</div>
HTML;
$usedOptions = [];
if (count($existingDataLookupOptions) > 0 || !empty($options['existingRecordLookupMethod'])) {
$r .= '<div id="lookup-mode-warning" class="alert alert-danger" style="display:none">' . lang::get('Note that updating of existing records is only available when the Prevent Commits On Any Error importer option is not being used').'</div>';
$r .= '<fieldset><legend>' . lang::get('Lookup of existing records') . '</legend>';
if (!empty($options['existingRecordLookupMethod'])) {
// Configuration forces a particular lookup method.
$msg = lang::get('Data will be used to lookup and update existing records where possible.');
$r .= <<<HTML
<div class="alert alert-info">$msg</div>
HTML;
}
else {
// User can choose lookup method.
foreach ($existingDataLookupOptions as $model => $combinations) {
$r .= '<label for="lookupSelect' . $model . '\">' . lang::get(ucfirst($model) . ' records') . '</label>';
$r .= "<select name=\"lookupSelect" . $model . "\" id=\"lookupSelect" . $model . "\" class=\"lookupSelects\">";
$r .= "<option value=\"\" >" . lang::get('Do not look up existing records') . "</option>";
foreach ($combinations as $combination) {
if (!in_array($model . $combination['description'], $usedOptions)) {
array_push($usedOptions, $model . $combination['description']);
// Each possible field for existing record lookup has the list of
// fields that need to be filled in for it to work specified as
// json in its value.
$optionLabel = self::getLookupOptionLabel($model, $combination['description']);
$r .= "<option value=\"" . htmlspecialchars(json_encode($combination['fields'])) . "\">" . htmlspecialchars($optionLabel) . "</option>";
}
}
$r .= "</select>";
$r .= '<div id="lookupHelplookupSelect' . $model . '" class="lookup-selected-help alert alert-info" style="display:none"></div>';
$r .= '<div><a href="#" id="lookupReasonTogglelookupSelect' . $model . '" class="lookup-reason-toggle" style="display:none">' .
lang::get('Explain why some options are disabled') . '</a></div>';
$r .= '<div id="lookupReasonlookupSelect' . $model . '" class="lookup-disabled-reason" style="display:none"></div>';
$r .= "<br/>";
}
}
$r .= "</fieldset>";
self::$javascript .= <<<JS
indiciaData.presetFields = [];
indiciaData.enableExistingDataLookup = true;
JS;
foreach ($settings as $key => $value) {
if (!is_array($value) && trim((string) $value) !== '') {
self::$javascript .= "indiciaData.presetFields.push(\"$key\");\n";
}
}
}
else {
self::$javascript .= "indiciaData.enableExistingDataLookup = false;\n";
}
// We need to rerun this even though we run this earlier in this function.
// The earlier call wouldn't have retrieved any mappings as
// get_column_options wouldn't have been run yet.
$mappingsAndSettings = self::getMappingsAndSettings($options);
self::send_mappings_and_settings_to_warehouse($filename, $options, $mappingsAndSettings);
// If skip mapping is on, then we don't actually need to show this page and
// can skip straight to the upload or error checking stage (which will be
// determined by runUpload using the allowCommitToDB option).
if (!empty($options['skipMappingIfPossible']) && $options['skipMappingIfPossible'] == TRUE && count(self::$automaticMappings) === $importableColCount) {
// Need to pass true to stop the mappings and settings being sent to the warehouse during the runUpload function
// as we have already done that here
return self::runUpload($options, TRUE);
}
// Preserve the post from the website/survey selection screen.
if (isset($options['allowCommitToDB'])&&$options['allowCommitToDB'] === FALSE) {
//If we are error checking before upload we do an extra step, which is import step 2
$r .= self::preserve_fields($options, $filename, 2, FALSE);
} else {
$r .= self::preserve_fields($options, $filename, 3, FALSE);
}
$r .= '<input type="submit" name="submit" id="submit" value="' . lang::get('Upload') . '" class="ui-corner-all ui-state-default button" />';
$r .= '</form>';
self::$javascript .= "required_fields={};\n";
foreach ($unlinked_required_fields as $field) {
$caption = $unlinked_fields[$field];
if (empty($caption)) {
$tokens = explode(':', $field);
$fieldname = $tokens[count($tokens) - 1];
$caption = lang::get(self::processLabel(preg_replace(array('/^fk_/', '/_id$/'), array('', ''), $fieldname)));
}
$caption = self::translate_field($field, $caption, $fieldMap);
self::$javascript .= "required_fields['$field']='$caption';\n";
}
self::$onload_javascript .= <<<JS
// Initial setup.
indiciaFns.detectDuplicateFields();
indiciaFns.updateRequiredFields();
indiciaFns.checkLookupOptions();
JS;
return $r;
}
/**
* Retrieve the list of column names from the import file.
*
* Uses the get_column_names service end-point on the warehouse.
*/
private static function getImportFileColumns($options) {
$request = parent::$base_url . "index.php/services/import/get_column_names?file=$_SESSION[uploaded_file]&" . self::array_to_query_string($options['auth']['read']);
$response = self::http_post($request, []);
return json_decode($response['output']);
}
/* Function used to preserve the post from previous stages as we move through the importer otherwise values are lost from
2 steps ago. Also preserves the automatic mappings used to skip the mapping stage by saving it to the post */
private static function preserve_fields($options, $filename, $importStep, $formWrapper) {
$mappingsAndSettings = self::getMappingsAndSettings($options);
$settingFields = $mappingsAndSettings['settings'];
$mappingFields = $mappingsAndSettings['mappings'];
$reload = self::get_reload_link_parts();
$reload['params']['uploaded_csv'] = $filename;
$reloadpath = $reload['path'] . '?' . self::array_to_query_string($reload['params']);
$r = $formWrapper
? "<div><form method=\"post\" id=\"fields_to_retain_form\" action=\"$reloadpath\" class=\"iform\">\n"
: '';
foreach ($settingFields as $field => $value) {
if (!empty($settingFields[$field])) {
if (!empty($value) && $field !== 'import_step' && $field !== 'submit') {
$r .= "<input type=\"hidden\" name=\"setting[$field]\" id=\"setting[$field]\" value=\"$value\"/>\n";
}
}
}
foreach ($mappingFields as $field => $value) {
if (!empty($mappingFields[$field])) {
if (is_string($field)&&is_string($value)&&!empty($value) && $field !== 'import_step' && $field !==' submit') {
$value = htmlspecialchars($value);
$r .= "<input type=\"hidden\" name=\"mapping[$field]\" id=\"mapping[$field]\" value=\"$value\"/>\n";
}
}
}
if (!empty($importStep)&&$importStep != NULL) {
$r .= '<input type="hidden" name="import_step" value="' . $importStep . '" />';
}
if ($formWrapper) {
$r .= '<input id="hidden_submit" type="submit" style="display: none" value="' . lang::get('Upload') . '">';
$r .= "</form><div>\n";
}
return $r;
}
/**
* Converts field mappings configuration text to an array.
*
* The fieldMap config is a list of database fields with optional '=column
* titles' added to them. Need a list of column titles mapped to fields so
* swap this around.
*/
private static function extractFieldData($fieldText, &$autoFieldMappings) {
$fields = self::explode_lines($fieldText);
foreach ($fields as $field) {
$tokens = explode('=', $field);
if (count($tokens) === 2) {
$autoFieldMappings[self::strForCompare($tokens[1])] = $tokens[0];
}
}
}
/**
* Returns an array of field to column title mappings that were previously stored in the user profile,
* or mappings that were provided via the page's configuration form.
* If the user profile does not support saving mappings then sets self::$rememberingMappings to false.
*
* @param array $options
* Options array passed to the import helper which might contain a fieldMap.
* @param array $settings
* Settings array for this import which might contain the survey_id.
*
* @return array|mixed
*/
private static function getAutoFieldMappings($options, $settings) {
$autoFieldMappings = [];
// Get the user's checked preference for the import page.
if (function_exists('hostsite_get_user_field') && function_exists('hostsite_set_user_field')) {
$json = hostsite_get_user_field('import_field_mappings');
if ($json === FALSE) {
if (!hostsite_set_user_field('import_field_mappings', '[]')) {
self::$rememberingMappings = FALSE;
}
}
else {
$json = trim($json);
$autoFieldMappings = json_decode(strtolower(trim($json)), TRUE);
}
}
else {
// Host does not support user profiles, so we can't remember mappings.
self::$rememberingMappings = FALSE;
}
if (!empty($settings['survey_id']) && !empty($options['fieldMap'])) {
foreach ($options['fieldMap'] as $surveyFieldMap) {
if (isset($surveyFieldMap['survey_id']) && isset($surveyFieldMap['fields']) &&
$surveyFieldMap['survey_id'] == $settings['survey_id']) {
self::extractFieldData($surveyFieldMap['fields'], $autoFieldMappings);
}
}
}
elseif (empty($settings['survey_id']) && !empty($options['fieldMap'])) {
// For locations, there is no survey ID, so do the same but with special
// survey check.
foreach ($options['fieldMap'] as $surveyFieldMap) {
if (!isset($surveyFieldMap['survey_id']) && isset($surveyFieldMap['fields']) /* Used for locations */) {
self::extractFieldData($surveyFieldMap['fields'], $autoFieldMappings);
}
}
}
return $autoFieldMappings;
}
/**
* Retrieve any configured field mappings for the chosen survey dataset.
*
* @param array $options
* Options array passed to the import helper which might contain a fieldMap.
* @param array $settings
* Settings array for this import which might contain the survey_id.
*
* @return array
* Associative array mapping fields to captions.
*/
private static function getFieldMap($options, $settings) {
if (!empty($settings['survey_id']) && !empty($options['fieldMap'])) {
foreach ($options['fieldMap'] as $surveyFieldMap) {
if (isset($surveyFieldMap['survey_id']) && isset($surveyFieldMap['fields']) &&
$surveyFieldMap['survey_id'] == $settings['survey_id']) {
preg_match_all("/([^=\r\n]+)=([^\r\n]+)/", $surveyFieldMap['fields'], $pairs);
$pairs[1] = array_map('trim', $pairs[1]);
$pairs[2] = array_map('trim', $pairs[2]);
$r = [];
foreach ($pairs[1] as $idx => $key) {
if (!isset($r[$key])) {
$r[$key] = $pairs[2][$idx];
}
}
return $r;
}
}
}
return [];
}
/**
* If the configuration only allows the supplied fields for a given survey ID, then limits the
* list of available fields retrieve from the warehouse for this survey to that configured list.
* @param array $fields Field list obtained from the warehouse for this survey. Disallowed fields
* will be removed.
* @param array $options Import helper options array
* @param integer $survey_id ID of the survey being imported
*/
private static function limitFields(&$fields, $options, $survey_id) {
if (isset($options['onlyAllowMappedFields']) && $options['onlyAllowMappedFields'] && isset($options['fieldMap'])) {
foreach ($options['fieldMap'] as $surveyFieldMap) {
if (isset($surveyFieldMap['survey_id']) && isset($surveyFieldMap['fields']) &&
($surveyFieldMap['survey_id']==$survey_id || $surveyFieldMap['survey_id']=="*" /* Used for locations */)) {
$allowedFields = self::explode_lines($surveyFieldMap['fields']);
array_walk($allowedFields, function(&$val) {
$tokens = explode("=",$val);
$val = $tokens[0];
});
$fields = array_intersect_key($fields, array_combine($allowedFields, $allowedFields));
}
}
}
}
/**
* When an array (e.g. $_POST containing preset import values) has values with actual ids in it, we need to
* convert these to fk_* so we can compare the array of preset data with other arrays of expected data.
* @param array $arr Array of IDs.
*/
private static function expand_ids_to_fks($arr) {
$ids = preg_grep('/_id$/', $arr);
foreach ($ids as &$id) {
$id = preg_replace('/_id$/', '', $id);
if (strpos($id, ':') === FALSE) {
$id = "fk_$id";
}
else {
$id = str_replace(':', ':fk_', $id);
}
}
return array_merge($arr, $ids);
}
/**
* Takes an array of fields, and removes the website ID or survey ID fields within the arrays if
* the website and/or survey id are set in the $settings data.
* @param array $array Array of fields.
* @param array $settings Global settings which apply to every row, which may include the website_id
* and survey_id.
*/
private static function clear_website_survey_fields(&$array, $settings) {
foreach ($array as $idx => $field) {
if (!empty($settings['website_id']) && (preg_match('/:fk_website$/', $idx) || preg_match('/:fk_website$/', $field))) {
unset($array[$idx]);
}
if (!empty($settings['survey_id']) && (preg_match('/:fk_survey$/', $idx) || preg_match('/:fk_survey$/', $field))) {
unset($array[$idx]);
}
}
}
/**
* Display the page which outputs the upload progress bar. Adds JavaScript to the page which performs the chunked upload.
* @param array $options Array of options passed to the import control.
* @param boolean $calledFromSkippedMappingsPage Indicates if this function was call by the mappings page if that stage is
* being skipped on screen. That function will have already sent the settings and mappings to the warehouse so we don't need
* to again.
*/
private static function runUpload($options, $calledFromSkippedMappingsPage = FALSE) {
self::add_resource('jquery_ui');
$filename = $_SESSION['uploaded_file'];
$reload = self::get_reload_link_parts();
$reload['params']['uploaded_csv'] = $filename;
$mappingsAndSettings=self::getMappingsAndSettings($options);
if ($calledFromSkippedMappingsPage===false) {
self::send_mappings_and_settings_to_warehouse($filename,$options,$mappingsAndSettings);
}
$r = '';
// If we are using the sample external key to verify samples,
// then we need to check the sample data is consistant between the
// rows which share the same external key. If not, warn the user.
if ($options['model']==='occurrence'||$options['model']==='sample') {
if (!empty($mappingsAndSettings['settings']['verifySamplesUsingExternalKey'])&&$mappingsAndSettings['settings']['verifySamplesUsingExternalKey']==true) {
// @TODO convert the following to server side as currently only works for CSV.
$rows=file($_SESSION['uploaded_file']);
$checkArrays = self::sample_external_key_issue_checks($options, $rows);
$inconsistencyFailureRows = $checkArrays['inconsistencyFailureRows'];
$clusteringFailureRows = $checkArrays['clusteringFailureRows'];
if (!empty($inconsistencyFailureRows)||!empty($clusteringFailureRows)) {
$r.= self::display_sample_external_key_data_mismatches($inconsistencyFailureRows,$clusteringFailureRows);
if (!empty($r))
return $r;
}
}
}
if (isset($options['allowCommitToDB'])&&$options['allowCommitToDB']===false) {
//If we hit this line it means we are doing the error checking step and the next step
//is step 3 which is the actual upload. Preserve the fields from previous steps in the post
$r .= self::preserve_fields($options, $filename, 3, TRUE);
} else {
//This line is hit if we are doing the actual upload now (rather than error check).
//The next step is the results step which does not have an import_step number
$r .= self::preserve_fields($options, $filename, NULL, TRUE);
}
// If there is an upload total as this point, it means an error check stage must of just been run, so we
// need to check for errors in the response
if (isset($_POST['total'])) {
// If we have reached this line, it means the previous step was the error check stage and we are
// about to attempt to upload, however we need to skip straight to results if we detected any errors
$output=self::collect_errors($options,$filename);
if (!is_array($output) || (isset($output['problems'])&&$output['problems']>0)) {
return self::displayResultAsErrorCheckStageFailed($options,$output);
}
//Need to re-send metadata as we need to call warehouse again for upload (rather than error check)
$mappingsAndSettings=self::getMappingsAndSettings($options);
self::send_mappings_and_settings_to_warehouse($filename,$options,$mappingsAndSettings);
}
// Progress message depends if we are uploading or simply checking for
// errors.
if ($options['allowCommitToDB']) {
$progressMessage = lang::get('{1} records uploaded');
} else {
$progressMessage = lang::get('{1} records checked');
}
$errorMessage = 'and {1} error(s) encountered.';
// initiate local javascript to do the upload with a progress feedback
$r .= <<<HTML
<div id="progress">
<progress id="progress-bar" class="progress" value="0" max="100">0 %</progress>
HTML;
if (isset($options['allowCommitToDB']) && $options['allowCommitToDB']) {
$actionMessage='Preparing to upload.';
} else {
$actionMessage='Checking file for errors..';
}
$r .= "<div id='progress-text'>$actionMessage.</div>
</div>
";
self::$onload_javascript .= <<<JS
/**
* Upload a single chunk of a file, by doing an AJAX get. If there is more, then on receiving the response upload the
* next chunk.
*/
uploadChunk = function() {
var limit = 50;
$.ajax({
url: indiciaData.warehouseUrl + 'index.php/services/import/upload?offset=' + total + '&limit=' + limit +
'&filepos=' + filepos + '&uploaded_csv=$filename' +
'&model=$options[model]&allow_commit_to_db=$options[allowCommitToDB]',
dataType: 'jsonp',
crossDomain: true
})
.done(function(response) {
var allowCommitToDB = '$options[allowCommitToDB]';
var message;
total = total + response.uploaded;
filepos = response.filepos;
message = '$progressMessage'.replace('{1}', total - response.errorCount);
if (response.errorCount > 0) {
message += ' $errorMessage'.replace('{1}', response.errorCount);
}
jQuery('#progress-text').html(message);
$('#progress-bar').val(response.progress);
$('#progress-bar').text(response.progress + ' %');
if (response.uploaded >= limit) {
uploadChunk();
} else {
if (allowCommitToDB) {
if (response.errorCount > 0) {
jQuery('#progress-text').html('Upload finished with errors.');
} else {
jQuery('#progress-text').html('Upload complete.');
}
//We only need total at end of wizard, so we can just refresh page with total as param to use in the post of next step
} else {
jQuery('#progress-text').html('Checks complete.');
}
$('#fields_to_retain_form').append('<input type=\"hidden\" name=\"total\" id=\"total\" value=\"'+total+'\"/>');
$('#fields_to_retain_form').submit();
}
})
.fail(function(r) {
alert('Error uploading file. More information is in the warehouse logs.');
jQuery('#progress-text').html('Error uploading file. More information is in the warehouse logs.');
});
};
var total = 0, filepos = 0;
jQuery('#progress-bar').val(0);