forked from Symbiota/Symbiota
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathOccurrenceHarvester.php
2625 lines (2495 loc) · 113 KB
/
OccurrenceHarvester.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
include_once($SERVER_ROOT.'/classes/OccurrenceCollectionProfile.php');
include_once($SERVER_ROOT.'/classes/TaxonomyUtilities.php');
include_once($SERVER_ROOT.'/classes/TaxonomyHarvester.php');
include_once($SERVER_ROOT.'/classes/UuidFactory.php');
include_once($SERVER_ROOT.'/config/symbini.php');
class OccurrenceHarvester{
private $conn;
private $activeCollid = 0;
private $collectionArr = array();
private $fateLocationArr;
private $taxonCodeArr = array();
private $taxonArr = array();
private $stateArr = array();
private $personnelArr = array();
private $timezone = 'America/Denver';
private $sampleClassArr = array();
private $domainSiteArr = array();
private $replaceFieldValues = false;
private $neonApiBaseUrl;
private $neonApiKey;
private $errorStr;
private $errorLogArr = array();
public function __construct(){
$this->conn = MySQLiConnectionFactory::getCon('write');
$this->neonApiBaseUrl = 'https://data.neonscience.org/api/v0';
if(isset($GLOBALS['NEON_API_KEY'])) $this->neonApiKey = $GLOBALS['NEON_API_KEY'];
}
public function __destruct(){
if($this->conn) $this->conn->close();
}
//Occurrence harvesting functions
public function getHarvestReport($shipmentPK){
$retArr = array();
$sql = 'SELECT s.errorMessage AS errMsg, COUNT(s.samplePK) as sampleCnt, COUNT(o.occid) as occurrenceCnt '.
'FROM NeonSample s LEFT JOIN omoccurrences o ON s.occid = o.occid '.
'WHERE s.checkinuid IS NOT NULL AND s.sampleReceived = 1';
if($shipmentPK) $sql .= 'AND s.shipmentPK = '.$shipmentPK;
$sql .= ' GROUP BY errMsg';
$rs= $this->conn->query($sql);
while($r = $rs->fetch_object()){
$errMsg = $r->errMsg;
if(!$errMsg) $errMsg = 'null';
$retArr[$errMsg]['s-cnt'] = $r->sampleCnt;
$retArr[$errMsg]['o-cnt'] = $r->occurrenceCnt;
}
$rs->free();
return $retArr;
}
public function batchHarvestOccid($postArr){
//Set variables
$status = false;
if(isset($postArr['replaceFieldValues']) && $postArr['replaceFieldValues']) $this->setReplaceFieldValues(true);
$sqlWhere = '';
$sqlPrefix = '';
if(isset($postArr['scbox'])){
$sqlWhere = 'AND s.samplePK IN('.implode(',',$postArr['scbox']).')';
}
elseif($postArr['action'] == 'harvestOccurrences'){
if(isset($postArr['nullOccurrencesOnly'])){
$sqlWhere .= 'AND (s.occid IS NULL) ';
}
if($postArr['collid']){
$sqlWhere .= 'AND (o.collid = '.$postArr['collid'].') ';
}
if($postArr['errorStr'] == 'nullError'){
$sqlWhere .= 'AND (s.errorMessage IS NULL) ';
}
elseif($postArr['errorStr']){
$sqlWhere .= 'AND (s.errorMessage = "'.$this->cleanInStr($postArr['errorStr']).'") ';
}
if($postArr['sessionid']){
$sqlWhere .= 'AND (s.sessionID = "'.$this->cleanInStr($postArr['sessionid']).'") ';
}
if($postArr['harvestDate']){
$sqlWhere .= 'AND (s.harvestTimestamp IS NULL OR s.harvestTimestamp < "'.$postArr['harvestDate'].'") ';
}
$sqlPrefix = 'ORDER BY s.shipmentPK ';
if(isset($postArr['limit']) && is_numeric($postArr['limit'])) $sqlPrefix .= 'LIMIT '.$postArr['limit'];
else $sqlPrefix .= 'LIMIT 1000 ';
}
if($sqlWhere){
$sqlWhere = 'WHERE s.checkinuid IS NOT NULL AND s.acceptedForAnalysis = 1 '.$sqlWhere;
$status = $this->batchHarvestOccurrences($sqlWhere.$sqlPrefix);
}
return $status;
}
private function batchHarvestOccurrences($sqlWhere){
set_time_limit(3600);
if($sqlWhere){
$this->setStateArr();
$this->setDomainSiteArr();
//if(!$this->setSampleClassArr()) echo '<li>'.$this->errorStr.'</li>';
echo '<li>Target record count: '.number_format($this->getTargetCount($sqlWhere)).'</li>';
$collArr = array();
$cnt = 1;
$shipmentPK = '';
$sql = 'SELECT s.samplePK, s.shipmentPK, s.sampleID, s.hashedSampleID, s.alternativeSampleID, s.sampleUuid, s.sampleCode, s.sampleClass, s.taxonID, '.
's.individualCount, s.filterVolume, s.namedLocation, s.collectDate, s.symbiotaTarget, s.igsnPushedToNEON, s.occid '.
'FROM NeonSample s LEFT JOIN omoccurrences o ON s.occid = o.occid '.
$sqlWhere;
$rs = $this->conn->query($sql);
while($r = $rs->fetch_object()){
$this->errorStr = '';
if($shipmentPK != $r->shipmentPK){
$shipmentPK = $r->shipmentPK;
echo '<li><b>Processing shipment #'.$shipmentPK.'</b></li>';
}
echo '<li style="margin-left:15px">'.$cnt.': '.($r->occid?($this->replaceFieldValues?'Rebuilding':'Appending'):'Harvesting').' '.($r->sampleID?$r->sampleID:$r->sampleCode).' ('.date('Y-m-d H:i:s').')... </li>';
$sampleArr = array();
$sampleArr['samplePK'] = $r->samplePK;
$sampleArr['sampleID'] = strtoupper($r->sampleID ?? '');
$sampleArr['hashedSampleID'] = $r->hashedSampleID ?? '';
$sampleArr['alternativeSampleID'] = strtoupper($r->alternativeSampleID ?? '');
$sampleArr['sampleUuid'] = $r->sampleUuid ?? '';
$sampleArr['sampleCode'] = $r->sampleCode ?? '';
$sampleArr['sampleClass'] = $r->sampleClass ?? '';
$sampleArr['taxonID'] = $r->taxonID ?? '';
//$sampleArr['individualCount'] = $r->individualCount ?? '';
$sampleArr['filterVolume'] = $r->filterVolume ?? '';
$sampleArr['namedLocation'] = $r->namedLocation ?? '';
$sampleArr['collectDate'] = $r->collectDate ?? '';
$sampleArr['symbiotaTarget'] = $r->symbiotaTarget ?? '';
$sampleArr['igsnPushedToNEON'] = $r->igsnPushedToNEON ?? 0;
$sampleArr['occid'] = $r->occid ?? '';
if($r->occid){
if($occurrenceID = $this->getCurrentOccurrenceID($r->occid)){
$sampleArr['occurrenceID'] = $occurrenceID;
}
}
if($this->harvestNeonApi($sampleArr)){
if($dwcArr = $this->getDarwinCoreArr($sampleArr)){
$this->subSampleIdentifications($dwcArr, $r->occid);
if($occid = $this->loadOccurrenceRecord($dwcArr, $r->occid, $r->samplePK)){
if(!in_array($dwcArr['collid'],$collArr)) $collArr[] = $dwcArr['collid'];
echo '<li style="margin-left:30px">Record successfully harvested: <a href="'.$GLOBALS['CLIENT_ROOT'].'/collections/individual/index.php?occid='.$occid.'" target="_blank">'.$occid.'</a></li>';
}
if($this->errorStr) echo '<li style="margin-left:30px">WARNING: '.$this->errorStr.'</li>';
}
else{
echo '<li style="margin-left:30px">'.$this->errorStr.'</li>';
}
}
else{
echo '<li style="margin-left:30px">ABORT: '.trim($this->errorStr, ';, ').'</li>';
}
$cnt++;
flush();
ob_flush();
}
$rs->free();
if($shipmentPK){
$this->adjustTaxonomy();
//Set recordID GUIDs
echo '<li>Setting recordID UUIDs for all occurrence records...</li>';
$uuidManager = new UuidFactory();
$uuidManager->setSilent(1);
$uuidManager->populateGuids();
//Update stats for each collection affected
if($collArr){
echo '<li>Update stats and associations for each collection...</li>';
if(in_array(7, $collArr)) {$collArr[] = 108;}
if(in_array(8, $collArr)) {$collArr[] = 109;}
if(in_array(9, $collArr)) { $collArr[] = 107;}
if(in_array(22, $collArr)) {$collArr[] = 100;}
if(in_array(45, $collArr)) {$collArr[] = 104;}
//if(in_array(47, $collArr)) {$collArr[] = 110;}
//if(in_array(49, $collArr)) {$collArr[] = 111;}
if(in_array(50, $collArr)) {$collArr[] = 105;}
if(in_array(52, $collArr)) {$collArr[] = 101;}
if(in_array(53, $collArr)) {$collArr[] = 102;}
if(in_array(57, $collArr)) {$collArr[] = 103;}
if(in_array(73, $collArr)) {$collArr[] = 106;}
$collManager = new OccurrenceCollectionProfile();
foreach($collArr as $collID){
echo '<li style="margin-left:15px">Stat update for collection <a href="'.$GLOBALS['CLIENT_ROOT'].'/collections/misc/collprofiles.php?collid='.$collID.'" target="_blank">#'.$collID.'</a>...</li>';
$collManager->setCollid($collID);
$collManager->updateStatistics(false);
flush();
ob_flush();
}
}
}
else echo '<li><b>No records processed. Note that records have to be checked in before occurrences can be harvested.</b></li>';
//Log any notices, warnings, and errors
if($this->errorLogArr){
$logPath = $GLOBALS['SERVER_ROOT'].'/neon/content/logs/occurHarvest_error_'.date('Y-m-d').'.log';
$logFH = fopen($logPath, 'a');
fwrite($logFH,'Harvesting event: '.date('Y-m-d H:i:s')."\n");
fwrite($logFH,'-------------------------'."\n");
foreach($this->errorLogArr as $errStr){
fwrite($logFH,$errStr."\n");
}
fwrite($logFH,"\n\n");
fclose($logFH);
}
}
return false;
}
private function getTargetCount($sqlWhere){
$retCnt = 0;
$sql = 'SELECT COUNT(s.samplePK) AS cnt FROM NeonSample s LEFT JOIN omoccurrences o ON s.occid = o.occid '.$sqlWhere;
$rs = $this->conn->query($sql);
while($r = $rs->fetch_object()){
$retCnt = $r->cnt;
}
$rs->free();
return $retCnt;
}
private function harvestNeonApi(&$sampleArr){
//returning true/false changes the 'success' of the sample
$this->setSampleErrorMessage($sampleArr['samplePK'], '');
$sampleViewArr = array();
// Define an array of URL configurations based on sample identifiers
$urlConfigs = [
['key' => 'sampleCode', 'param' => 'barcode'],
['key' => 'sampleUuid', 'param' => 'sampleUuid'],
['key' => 'occurrenceID', 'param' => 'archiveGuid'],
['key' => 'sampleID', 'param' => 'sampleTag',
'key2' => 'sampleClass', 'param2' => 'sampleClass']
];
$anyKeyExists = array_reduce($urlConfigs, function ($carry, $config) use ($sampleArr) {
return $carry || isset($sampleArr[$config['key']]);
}, false);
if (!$anyKeyExists) {
$this->errorStr = 'Sample identifiers incomplete';
$this->setSampleErrorMessage($sampleArr['samplePK'], $this->errorStr);
return false;
}
foreach ($urlConfigs as $config) {
$url = '';
if (!empty($sampleArr[$config['key']])) $url = $this->buildApiurl($config, $sampleArr);
if (!empty($url)){
//echo 'url: ' . $url . '<br/>';
$sampleViewArr = $this->checkApiforData($url, $sampleArr);
if ($sampleViewArr) {
return $this->checkApiDataforErrors($sampleArr, $sampleViewArr);
}
}
}
return false;
}
private function buildApiurl($config, $sampleArr){
$url = $this->neonApiBaseUrl . '/samples/view?' . $config['param'] . '=' . urlencode($sampleArr[$config['key']]);
if ($config['key'] == 'sampleID'){
if (!empty($sampleArr[$config['key2']])){
$url .= '&' . $config['param2'] . '=' . urlencode($sampleArr['sampleClass']);
} else {
$this->errorStr = 'Searching by sampleID, but no sampleClass given';
$this->setSampleErrorMessage($sampleArr['samplePK'], $this->errorStr);
return;
}
}
$url .= '&apiToken=' . $this->neonApiKey;
return $url;
}
private function checkApiforData($url, $sampleArr){
$this->errorLogArr = [];
$this->errorStr = '';
$sampleViewArr = $this->getNeonApiArr($url);
if(!isset($sampleViewArr['sampleViews'])){
$this->errorStr = 'NEON API failed to return sample data';
//$this->errorStr .= ': (<a href="'.$url.'" target="_blank">'.$url.'</a>)';
$this->updateSampleRecord(array('errorMessage'=>$this->errorStr),$sampleArr['samplePK']);
return;
}
return $sampleViewArr;
}
private function checkApiDataforErrors(&$sampleArr, &$sampleViewArr){
//true = successful, false = error
$this->errorLogArr = [];
$this->errorStr = '';
if(count($sampleViewArr['sampleViews']) > 1){
$this->errorStr = 'Harvest skipped: NEON API returned multiple sampleViews ';
$this->updateSampleRecord(array('errorMessage'=>$this->errorStr),$sampleArr['samplePK']);
return false;
}
$viewArr = current($sampleViewArr['sampleViews']);
if(!$this->checkIdentifiers($viewArr, $sampleArr)) return false;
//Get fateLocation and process parent samples
unset($this->fateLocationArr);
$this->fateLocationArr = array();
$this->processViewArr($sampleArr, $sampleViewArr);
if($this->fateLocationArr){
ksort($this->fateLocationArr);
$locArr = current($this->fateLocationArr);
$sampleArr['fate_location'] = $locArr['loc'];
if(!isset($sampleArr['collect_end_date'])) $sampleArr['collect_end_date'] = $locArr['date'];
}
return true;
}
private function checkIdentifiers($viewArr, &$sampleArr){
$status = true;
$neonSampleUpdate = array();
if(isset($viewArr['sampleUuid']) && $viewArr['sampleUuid']){
//Populate or verify/coordinate sampleUuid
if(!$sampleArr['sampleUuid']){
$sampleArr['sampleUuid'] = $viewArr['sampleUuid'];
$neonSampleUpdate['sampleUuid'] = $viewArr['sampleUuid'];
}
elseif($sampleArr['sampleUuid'] != $viewArr['sampleUuid']){
$this->errorLogArr[] = 'NOTICE: sampleUuid updated from '.$sampleArr['sampleUuid'].' to '.$viewArr['sampleUuid'];
$this->errorStr .= '; DATA ISSUE: sampleUuid failing to match (old: '.$sampleArr['sampleUuid'].', new: '.$viewArr['sampleUuid'].')';
$status = false;
}
}
//missing a barcode, just record within NeonSample error field and then skip harvest of this record
if(empty($sampleArr['sampleCode']) && isset($viewArr['barcode'])){
$this->errorStr .= '; DATA ISSUE: Barcode missing in database records, but available in API ('.$viewArr['barcode'].')';
$status = false;
} elseif (!empty($sampleArr['sampleCode']) && !isset($viewArr['barcode'])){
$this->errorStr .= '; DATA ISSUE: Barcode missing in API, but available in database records ('.$sampleArr['sampleCode'].')';
$status = false;
}
if(!empty($sampleArr['sampleCode']) && isset($viewArr['barcode']) && $sampleArr['sampleCode'] != $viewArr['barcode']){
//sampleCode/barcode are not equal; don't update, just record within NeonSample error field and then skip harvest of this record
$this->errorStr .= '; DATA ISSUE: Barcode failing to match (old: '.$sampleArr['sampleCode'].', new: '.$viewArr['barcode'].')';
$status = false;
}
if($sampleArr['sampleClass'] && isset($viewArr['sampleClass']) && $sampleArr['sampleClass'] != $viewArr['sampleClass']){
//sampleClass are not equal; don't update, just record within NeonSample error field and then skip harvest of this record
$this->errorStr .= '; DATA ISSUE: sampleClass failing to match (old: '.$sampleArr['sampleClass'].', new: '.$viewArr['sampleClass'].')';
$status = false;
}
if(isset($viewArr['archiveGuid']) && $viewArr['archiveGuid']){
$igsnMatch = array();
if(preg_match('/(NEON[A-Z,0-9]{5})/', $viewArr['archiveGuid'], $igsnMatch)){
if($sampleArr['occid']){
//This is a reharvest event, check to make sure IGSNs match
if(isset($sampleArr['occurrenceID']) && $sampleArr['occurrenceID']){
if($sampleArr['occurrenceID'] == $igsnMatch[1]){
$neonSampleUpdate['igsnPushedToNEON'] = 1;
}
else{
$this->setSampleErrorMessage($sampleArr['samplePK'], 'DATA ISSUE: IGSN failing to match with API value');
$neonSampleUpdate['igsnPushedToNEON'] = 2;
}
}
else{
if(!$this->igsnExists($igsnMatch[1],$sampleArr)){
if(!$this->updateOccurrenceIgsn($igsnMatch[1], $sampleArr['occid'])){
$this->setSampleErrorMessage($sampleArr['samplePK'], 'NOTICE: unable to update igsn: '.$this->conn->error);
$neonSampleUpdate['igsnPushedToNEON'] = 3;
}
}
}
}
else{
//New record should use ISGN, if it is not already assigned to another record
if(!$this->igsnExists($igsnMatch[1],$sampleArr)) $sampleArr['occurrenceID'] = $igsnMatch[1];
}
}
}
if($sampleArr['sampleID'] && isset($viewArr['sampleTag']) && $sampleArr['sampleID'] != $viewArr['sampleTag'] && $sampleArr['hashedSampleID'] != $viewArr['sampleTag']){
//sampleIDs (sampleTags) are not equal; report error and abort harvest
if(substr($viewArr['sampleTag'],-1) == '=' || !preg_match('/[_\.]+/',$viewArr['sampleTag'])){
$neonSampleUpdate['hashedSampleID'] = $viewArr['sampleTag'];
$sampleArr['hashedSampleID'] = $viewArr['sampleTag'];
}
else{
$this->errorStr .= '; DATA ISSUE: sampleID failing to match';
$status = false;
/*
if($this->updateSampleID($viewArr['sampleTag'], $sampleArr['sampleID'], $sampleArr['samplePK'], $sampleArr['occid'])){
$this->errorLogArr[] = 'NOTICE: sampleID updated from '.$sampleArr['sampleID'].' to '.$viewArr['sampleTag'].' (samplePK: '.$sampleArr['samplePK'].', occid: '.$sampleArr['occid'].')';
}
else{
$errMsg = (isset($neonSampleUpdate['errorMessage'])?$neonSampleUpdate['errorMessage'].'; ':'');
$errMsg .= 'DATA ISSUE: failed to reset sampleID using changed API value';
$this->setSampleErrorMessage($sampleArr['samplePK'], $errMsg);
}
*/
}
}
if(!$status) $this->setSampleErrorMessage($sampleArr['samplePK'], trim($this->errorStr, '; '));
$this->updateSampleRecord($neonSampleUpdate,$sampleArr['samplePK']);
return $status;
}
private function updateSampleID($newSampleID, $oldSampleID, $samplePK, $occid){
$status = true;
$sql = 'UPDATE NeonSample SET sampleID = "'.$newSampleID.'", alternativeSampleID = CONCAT_WS(", ",alternativeSampleID,"'.$oldSampleID.'") WHERE samplePK = '.$samplePK;
if(!$this->conn->query($sql)){
$status = false;
}
if($occid){
$sql = 'UPDATE omoccuridentifiers SET identifierValue = "'.$newSampleID.'" WHERE identifiername = "NEON sampleID" AND occid = '.$occid;
if(!$this->conn->query($sql)){
$status = false;
}
}
return $status;
}
private function updateSampleRecord($neonSampleUpdate,$samplePK){
if($neonSampleUpdate){
$sqlInsert = '';
foreach($neonSampleUpdate as $field => $value){
$sqlInsert .= $field.' = "'.$this->cleanInStr($value).'", ';
}
$sql = 'UPDATE NeonSample SET '.trim($sqlInsert,', ').' WHERE (samplePK = '.$samplePK.')';
if(!$this->conn->query($sql)){
echo '</li><li style="margin-left:30px">ERROR updating NeonSample record: '.$this->conn->error.'</li>';
}
}
}
private function igsnExists($igsn, &$sampleArr){
$occid = 0;
$sql = 'SELECT occid FROM omoccurrences WHERE occurrenceid = "'.$igsn.'" ';
$rs = $this->conn->query($sql);
if($r = $rs->fetch_object()){
$occid = $r->occid;
}
$rs->free();
if($occid){
//Another records exists within the portal with the same IGSN (not ideal)
$sampleArr['occurrenceID'] = $igsn.'-dupe (data issue!)';
$errMsg = 'DATA ISSUE: another record exists with duplicate IGSN registered within NEON API';
$this->setSampleErrorMessage($sampleArr['samplePK'], $errMsg);
return true;
}
return false;
}
private function updateOccurrenceIgsn($igsn, $occid){
$status = false;
$sql = 'UPDATE omoccurrences SET occurrenceID = "'.$igsn.'" WHERE occurrenceid IS NULL AND occid = '.$occid;
if($this->conn->query($sql)) $status = true;
return $status;
}
private function processViewArr(&$sampleArr, $viewArr, $sampleRank = 0){
if(!isset($viewArr['sampleViews'])){
$this->errorStr = 'sampleViews object failed to be returned from NEON API';
return false;
}
$viewArr = current($viewArr['sampleViews']);
//if(isset($viewArr['sampleClass']) && $viewArr['sampleClass'] == 'mam_pertrapnight_in.tagID') $this->createRelationship($viewArr['childSampleIdentifiers']);
//parse Sample Event details
$eventArr = $viewArr['sampleEvents'];
$harvestIdentifications = true;
if($sampleRank && isset($sampleArr['identifications'])) $harvestIdentifications = false;
if($eventArr){
foreach($eventArr as $eArr){
$tableName = $eArr['ingestTableName'];
if(strpos($tableName,'shipment')) continue;
//if(strpos($tableName,'identification')) continue;
//if(strpos($tableName,'sorting')) continue;
if(strpos($tableName,'scs_archive')) continue;
//if(strpos($tableName,'barcoding')) continue;
if(strpos($tableName,'dnaStandardTaxon')) continue;
if(strpos($tableName,'dnaExtraction')) continue;
if(strpos($tableName,'markerGeneSequencing')) continue;
if(strpos($tableName,'metagenomeSequencing')) continue;
if(strpos($tableName,'metabarcodeTaxonomy')) continue;
if(strpos($tableName,'pcrAmplification')) continue;
//if(strpos($tableName,'perarchivesample')) continue;
//if(strpos($tableName,'persample')) continue;
//if(strpos($tableName,'pertaxon')) continue;
if(strpos($tableName,'zoo_perVial_in')) continue;
if($tableName == 'mpr_perpitprofile_in') continue;
$fieldArr = $eArr['smsFieldEntries'];
$fateLocation = ''; $fateDate = '';
$readAssocTaxon = false;
$identRemarks = array();
$identArr = array(); $assocMedia = array(); $assocTaxa = array();
$tableArr = array();
foreach($fieldArr as $fArr){
if($tableName == 'tck_pathogenresults_in'){
if($fArr['smsKey'] == 'analysis_type' && $fArr['smsValue'] == 'Positive'){
$readAssocTaxon = true;
}
if($fArr['smsKey'] == 'taxon' && $fArr['smsValue'] != 'HardTick DNA Quality' && $readAssocTaxon){
$assocTaxa['verbatimSciname'] = $fArr['smsValue'];
$assocTaxa['relationship'] = 'hostOf';
}
}
else{
if($fArr['smsKey'] == 'fate_location') $fateLocation = $fArr['smsValue'];
elseif($fArr['smsKey'] == 'collection_location' && $fArr['smsValue']) $tableArr['collection_location'] = $fArr['smsValue'];
elseif($fArr['smsKey'] == 'fate_date' && $fArr['smsValue']) $fateDate = $fArr['smsValue'];
elseif($fArr['smsKey'] == 'event_id' && $fArr['smsValue']) $tableArr['event_id'] = $fArr['smsValue'];
elseif($fArr['smsKey'] == 'collected_by' && $fArr['smsValue']) $tableArr['collected_by'] = $fArr['smsValue'];
elseif($fArr['smsKey'] == 'collect_start_date' && $fArr['smsValue']) $tableArr['collect_start_date'] = $fArr['smsValue'];
elseif($fArr['smsKey'] == 'collect_end_date' && $fArr['smsValue']) $tableArr['collect_end_date'] = $fArr['smsValue'];
elseif (
$fArr['smsKey'] == 'specimen_count' &&
$fArr['smsValue'] &&
!(
strpos($tableName, 'bet_') !== false ||
strpos($tableName, 'ptx_') !== false ||
strpos($tableName, 'cfc_') !== false ||
strpos($tableName, 'mic_') !== false ||
strpos($tableName, 'sls_') !== false ||
strpos($tableName, 'inv_') !== false ||
strpos($tableName, 'metabarcode') !== false
)
) {
$tableArr['specimen_count'] = $fArr['smsValue'];
}
elseif($fArr['smsKey'] == 'temperature' && $fArr['smsValue']) $tableArr['temperature'] = $fArr['smsValue'];
elseif($fArr['smsKey'] == 'decimal_latitude' && $fArr['smsValue']) $tableArr['decimal_latitude'] = $fArr['smsValue'];
elseif($fArr['smsKey'] == 'decimal_longitude' && $fArr['smsValue']) $tableArr['decimal_longitude'] = $fArr['smsValue'];
elseif($fArr['smsKey'] == 'coordinate_uncertainty' && $fArr['smsValue']) $tableArr['coordinate_uncertainty'] = $fArr['smsValue'];
elseif($fArr['smsKey'] == 'elevation' && $fArr['smsValue']) $tableArr['elevation'] = $fArr['smsValue'];
elseif($fArr['smsKey'] == 'elevation_uncertainty' && $fArr['smsValue']) $tableArr['elevation_uncertainty'] = $fArr['smsValue'];
elseif($fArr['smsKey'] == 'verbatim_depth' && $fArr['smsValue']) $tableArr['verbatim_depth'] = $fArr['smsValue'];
elseif($fArr['smsKey'] == 'minimum_depth_in_meters' && $fArr['smsValue']) $tableArr['minimum_depth_in_meters'] = $fArr['smsValue'];
elseif($fArr['smsKey'] == 'maximum_depth_in_meters' && $fArr['smsValue']) $tableArr['maximum_depth_in_meters'] = $fArr['smsValue'];
elseif($fArr['smsKey'] == 'reproductive_condition' && $fArr['smsValue']) $tableArr['reproductive_condition'] = $fArr['smsValue'];
elseif($fArr['smsKey'] == 'sex' && $fArr['smsValue']) $tableArr['sex'] = $fArr['smsValue'];
elseif (
$fArr['smsKey'] == 'life_stage' &&
$fArr['smsValue'] &&
!(
strpos($tableName, 'bet_') !== false ||
strpos($tableName, 'ptx_') !== false ||
strpos($tableName, 'cfc_') !== false ||
strpos($tableName, 'mic_') !== false ||
strpos($tableName, 'sls_') !== false ||
strpos($tableName, 'inv_') !== false ||
strpos($tableName, 'metabarcode') !== false
)
) {
$tableArr['life_stage'] = $fArr['smsValue'];
}
elseif($fArr['smsKey'] == 'associated_taxa' && $fArr['smsValue']) $tableArr['associated_taxa'] = $fArr['smsValue'];
elseif($fArr['smsKey'] == 'remarks' && $fArr['smsValue'] && !in_array($tableName,array('ptx_taxonomy_in'))) $tableArr['remarks'] = $fArr['smsValue'];
elseif($fArr['smsKey'] == 'preservative_concentration' && $fArr['smsValue']) $tableArr['preservative_concentration'] = $fArr['smsValue'];
elseif($fArr['smsKey'] == 'preservative_volume' && $fArr['smsValue']) $tableArr['preservative_volume'] = $fArr['smsValue'];
elseif($fArr['smsKey'] == 'preservative_type' && $fArr['smsValue']) $tableArr['preservative_type'] = $fArr['smsValue'];
elseif($fArr['smsKey'] == 'sample_type' && $fArr['smsValue'] && !in_array($tableName,array('ptx_taxonomy_in'))) $tableArr['sample_type'] = $fArr['smsValue'];
//elseif($fArr['smsKey'] == 'sample_condition' && $fArr['smsValue']) $tableArr['sample_condition'] = $fArr['smsValue'];
elseif($fArr['smsKey'] == 'sample_mass' && $fArr['smsValue']) $tableArr['sample_mass'] = $fArr['smsValue'];
elseif($fArr['smsKey'] == 'sample_volume' && $fArr['smsValue']) $tableArr['sample_volume'] = $fArr['smsValue'];
elseif($fArr['smsKey'] == 'associated_media'){
if(!strpos($fArr['smsValue'],'biorepo.neonscience.org/portal')) $assocMedia['url'] = $fArr['smsValue'];
}
elseif($fArr['smsKey'] == 'photographed_by') $assocMedia['photographer'] = $fArr['smsValue'];
if($harvestIdentifications && !($tableName == 'inv_pervial_in' && in_array($sampleArr['sampleClass'],array('inv_fielddata_in.sampleID','inv_persample_in.mixedInvertVialID','inv_persample_in.chironomidVialID','inv_persample_in.oligochaeteVialID')))){
if($fArr['smsKey'] == 'taxon' && $fArr['smsValue']){
$identArr['sciname'] = $fArr['smsValue'];
$identArr['taxon'] = $fArr['smsValue'];
}
elseif($fArr['smsKey'] == 'taxon_published' && $fArr['smsValue']){
//Temporarly keep to support possibility of this field still being used for certain sampleClasses
$identArr['taxonPublished'] = $fArr['smsValue'];
}
elseif($fArr['smsKey'] == 'taxon_published_processed_scientific_name' && $fArr['smsValue']){
$identArr['taxonPublished'] = $fArr['smsValue'];
}
elseif($fArr['smsKey'] == 'taxon_published_raw_scientific_name' && $fArr['smsValue']){
//We only want "raw" value if "processed" does not exists, thus we don't want to replace a set "processed" value with a "raw"
if(empty($identArr['taxonPublished'])) $identArr['taxonPublished'] = $fArr['smsValue'];
}
elseif($fArr['smsKey'] == 'taxon_published_processed_code' && $fArr['smsValue']){
$identArr['taxonPublishedCode'] = $fArr['smsValue'];
}
elseif($fArr['smsKey'] == 'taxon_published_raw_code' && $fArr['smsValue']){
if(empty($identArr['taxonPublishedCode'])) $identArr['taxonPublishedCode'] = $fArr['smsValue'];
}
elseif($fArr['smsKey'] == 'identified_by' && $fArr['smsValue']) $identArr['identifiedBy'] = $this->translatePersonnel($fArr['smsValue']);
elseif($fArr['smsKey'] == 'identified_date' && $fArr['smsValue']) $identArr['dateIdentified'] = $fArr['smsValue'];
elseif(in_array($tableName,array('ptx_taxonomy_in'))){
if($fArr['smsKey'] == 'sample_type' && $fArr['smsValue']){
$identRemarks[] = $fArr['smsValue'];
}
if($fArr['smsKey'] == 'remarks' && $fArr['smsValue']){
$identRemarks[] = $fArr['smsValue'];
}
if($fArr['smsKey'] == 'identification_remarks' && $fArr['smsValue']){
$identRemarks[] = $fArr['smsValue'];
}
$identArr['identificationRemarks'] = implode('; ',$identRemarks);
}
elseif(!in_array($tableName,array('ptx_taxonomy_in')) && $fArr['smsKey'] == 'identification_remarks' && $fArr['smsValue']) {
$identArr['identificationRemarks'] = $fArr['smsValue'];
}
elseif($fArr['smsKey'] == 'identification_references' && $fArr['smsValue']) $identArr['identificationReferences'] = $fArr['smsValue'];
elseif($fArr['smsKey'] == 'identification_qualifier' && $fArr['smsValue']) $identArr['identificationQualifier'] = $fArr['smsValue'];
elseif(in_array($tableName,array('zoo_perTaxon_in','inv_pertaxon_in')) && $fArr['smsKey'] == 'specimen_count' && $fArr['smsValue']) $identArr['subsampleIndividualCount'] = $fArr['smsValue'];
elseif(in_array($tableName,array('inv_pertaxon_in')) && $fArr['smsKey'] == 'life_stage' && $fArr['smsValue']) $identArr['subsampleLifeStage'] = $fArr['smsValue'];
}
}
}
if($assocMedia && isset($assocMedia['url'])) $tableArr['assocMedia'][] = $assocMedia;
if(empty($this->fateLocationArr[1]['loc'])){
//locationID has not yet been harvested from collection_location field, thus looking for value set within parent
if(!empty($tableArr['collection_location']) && !strpos($tableArr['collection_location'], ' ')){
//collection_location is first choice/ranking
$score = 1;
$this->fateLocationArr[$score]['loc'] = $tableArr['collection_location'];
$this->fateLocationArr[$score]['date'] = $fateDate;
}
elseif($fateDate && $fateLocation && !strpos($fateLocation, ' ')){
//If collection_location is not defined, use fate dates (old method of harvesting locationID and date)
$score = $sampleRank.':'.$fateDate;
if(strpos($tableName,'fielddata')) $score = 2;
$this->fateLocationArr[$score]['loc'] = $fateLocation;
$this->fateLocationArr[$score]['date'] = $fateDate;
}
}
$sampleArr = array_merge($tableArr, $sampleArr);
if($identArr && isset($identArr['sciname']) && $identArr['sciname']){
$identArr['taxonRemarks'] = 'Identification source: harvested from NEON API';
if(empty($identArr['dateIdentified'])){
if($fateDate) $identArr['dateIdentified'] = $fateDate;
else $identArr['dateIdentified'] = 's.d.';
}
if(empty($identArr['identifiedBy'])){
$identArr['identifiedBy'] = 'undefined';
}
$hash = hash('md5', str_replace(' ', '', $identArr['sciname'].$identArr['identifiedBy'].$identArr['dateIdentified']));
// allow for unique records for different life stages
if($tableName = 'inv_pertaxon_in'){
if(isset($identArr['subsampleIndividualCount'])){
$hash .= hash('md5', str_replace(' ', '', $identArr['subsampleIndividualCount']));
}
if(isset($identArr['subsampleLifeStage'])){
$hash .= hash('md5', str_replace(' ', '', $identArr['subsampleLifeStage']));
}
if(isset($identArr['identificationRemarks'])){
$hash .= hash('md5', str_replace(' ', '', $identArr['identificationRemarks']));
}
}
$sampleArr['identifications'][$hash] = $identArr;
}
if($assocTaxa && isset($assocTaxa['verbatimSciname'])){
$taxaArr = $this->getTaxonArr($assocTaxa['verbatimSciname']);
if(isset($taxaArr['tidInterpreted'])) $assocTaxa['tid'] = $taxaArr['tidInterpreted'];
$hash = hash('md5', str_replace(' ', '', $assocTaxa['verbatimSciname'].$assocTaxa['relationship']));
$sampleArr['associations'][$hash] = $assocTaxa;
}
}
}
$sampleRank++;
if(isset($viewArr['parentSampleIdentifiers'][0]['sampleUuid'])){
//Get parent data
$url = $this->neonApiBaseUrl.'/samples/view?sampleUuid='.$viewArr['parentSampleIdentifiers'][0]['sampleUuid'].'&apiToken='.$this->neonApiKey;
$parentViewArr = $this->getNeonApiArr($url);
$this->processViewArr($sampleArr, $parentViewArr, $sampleRank);
}
}
private function getDarwinCoreArr($sampleArr){
$dwcArr = array();
if($sampleArr['samplePK']){
if($this->setCollectionIdentifier($dwcArr,$sampleArr['sampleClass'])){
//Get data that was provided within manifest
$dwcArr['identifiers']['NEON sampleCode (barcode)'] = (isset($sampleArr['sampleCode'])?$sampleArr['sampleCode']:'');
$dwcArr['identifiers']['NEON sampleID'] = (isset($sampleArr['sampleID'])?$sampleArr['sampleID']:'');
$dwcArr['identifiers']['NEON sampleUUID'] = (isset($sampleArr['sampleUuid'])?$sampleArr['sampleUuid']:'');
$dwcArr['identifiers']['NEON sampleID Hash'] = (isset($sampleArr['hashedSampleID'])?$sampleArr['hashedSampleID']:'');
if(isset($sampleArr['event_id'])) $dwcArr['eventID'] = $sampleArr['event_id'];
if(isset($sampleArr['specimen_count'])) $dwcArr['individualCount'] = $sampleArr['specimen_count'];
elseif(isset($sampleArr['individualCount'])) $dwcArr['individualCount'] = $sampleArr['individualCount'];
if(isset($sampleArr['reproductive_condition'])) $dwcArr['reproductiveCondition'] = $sampleArr['reproductive_condition'];
if(isset($sampleArr['sex'])) $dwcArr['sex'] = $sampleArr['sex'];
if(isset($sampleArr['life_stage'])) $dwcArr['lifeStage'] = $sampleArr['life_stage'];
if(isset($sampleArr['associated_taxa'])) $dwcArr['associatedTaxa'] = $this->translateAssociatedTaxa($sampleArr['associated_taxa']);
$occurRemarks = array();
if(!in_array($dwcArr['collid'],array(46,73))){
if(isset($sampleArr['remarks'])) $occurRemarks[] = $sampleArr['remarks'];
if(isset($sampleArr['sample_type'])){
$sampleType = $sampleArr['sample_type'];
if($sampleType == 'M') $sampleType = 'mineral';
elseif($sampleType == 'O') $sampleType = 'organic';
$occurRemarks[] = 'sample type: '.$sampleType;
}
if($occurRemarks) $dwcArr['occurrenceRemarks'] = implode('; ',$occurRemarks);
}
if(isset($sampleArr['assocMedia'])) $dwcArr['assocMedia'] = $sampleArr['assocMedia'];
if(isset($sampleArr['coordinate_uncertainty']) && $sampleArr['coordinate_uncertainty']) $dwcArr['coordinateUncertaintyInMeters'] = $sampleArr['coordinate_uncertainty'];
if(isset($sampleArr['decimal_latitude'])) $dwcArr['decimalLatitude'] = $sampleArr['decimal_latitude'];
if(isset($sampleArr['decimal_longitude'])) $dwcArr['decimalLongitude'] = $sampleArr['decimal_longitude'];
if(isset($sampleArr['elevation'])){
if(isset($sampleArr['elevation_uncertainty'])){
$dwcArr['minimumElevationInMeters'] = round($sampleArr['elevation']-$sampleArr['elevation_uncertainty']);
$dwcArr['maximumElevationInMeters'] = round($sampleArr['elevation']+$sampleArr['elevation_uncertainty']);
$dwcArr['verbatimElevation'] = $sampleArr['elevation'].'m (+-'.$sampleArr['elevation_uncertainty'].'m)';
}
else{
$dwcArr['minimumElevationInMeters'] = $sampleArr['elevation'];
$dwcArr['maximumElevationInMeters'] = $sampleArr['elevation'];
}
}
$prepArr = array();
if(!in_array($dwcArr['collid'], array(7,8,9,19,28,42,46,17,64))){
if(!in_array($dwcArr['collid'],array(31,50,73))){
if(!empty($sampleArr['preservative_type'])) $prepArr[] = 'preservative type: '.$sampleArr['preservative_type'];
}
if(!empty($sampleArr['preservative_volume'])) $prepArr[] = 'preservative volume: '.$sampleArr['preservative_volume'];
if(!empty($sampleArr['preservative_concentration'])) $prepArr[] = 'preservative concentration: '.$sampleArr['preservative_concentration'];
if(!empty($sampleArr['sample_mass']) && strpos($sampleArr['symbiotaTarget'],'sample mass') === false) $prepArr[] = 'sample mass: '.$sampleArr['sample_mass'];
if(!empty($sampleArr['sample_volume']) && strpos($sampleArr['symbiotaTarget'],'sample volume') === false) $prepArr[] = 'sample volume: '.$sampleArr['sample_volume'];
if(!empty($sampleArr['sex'])){
if($sampleArr['sex'] == 'M') $dwcArr['sex'] = 'Male';
elseif($sampleArr['sex'] == 'F') $dwcArr['sex'] = 'Female';
elseif($sampleArr['sex'] == 'U') $dwcArr['sex'] = 'Unknown';
}
}
if($prepArr) $dwcArr['preparations'] = implode(', ',$prepArr);
$dynProp = array();
if(!empty($sampleArr['filterVolume'])) $dynProp[] = 'filterVolume: '.$sampleArr['filterVolume'];
if(!empty($sampleArr['temperature'])) $dynProp[] = 'temperature: '.$sampleArr['temperature'];
if(!empty($sampleArr['minimum_depth_in_meters'])) $dynProp[] = 'minimum depth: '.$sampleArr['minimum_depth_in_meters'].'m ';
if(!empty($sampleArr['maximum_depth_in_meters'])) $dynProp[] = 'maximum depth: '.$sampleArr['maximum_depth_in_meters'].'m ';
if(!empty($sampleArr['verbatim_depth'])) $dynProp[] = 'verbatim depth: '.$sampleArr['verbatim_depth'];
//if(isset($sampleArr['sample_condition'])) $dynProp[] = 'sample condition: '.$sampleArr['sample_condition'];
if($dynProp) $dwcArr['dynamicProperties'] = implode(', ',$dynProp);
if(!empty($sampleArr['collected_by'])) $dwcArr['recordedBy'] = $this->translatePersonnel($sampleArr['collected_by']);
if(!empty($sampleArr['collect_end_date'])){
if(!empty($sampleArr['collect_start_date']) && $sampleArr['collect_start_date'] != $sampleArr['collect_end_date']){
$dwcArr['eventDate'] = $sampleArr['collect_start_date'];
$dwcArr['eventDate2'] = $sampleArr['collect_end_date'];
}
else $dwcArr['eventDate'] = $sampleArr['collect_end_date'];
}
elseif(!empty($sampleArr['collectDate']) && $sampleArr['collectDate'] != '0000-00-00') $dwcArr['eventDate'] = $sampleArr['collectDate'];
elseif($sampleArr['sampleID']){
if(preg_match('/\.(20\d{2})(\d{2})(\d{2})\./',$sampleArr['sampleID'],$m)){
//Get date from sampleID
$dwcArr['eventDate'] = $m[1].'-'.$m[2].'-'.$m[3];
}
}
//Build proper location code
$locationStr = '';
if(!empty($sampleArr['fate_location'])) $locationStr = $sampleArr['fate_location'];
elseif($sampleArr['namedLocation']) $locationStr = $sampleArr['namedLocation'];
if($locationStr){
if($this->setNeonLocationData($dwcArr, $locationStr)){
if(isset($dwcArr['domainID'])){
$locStr = $this->domainSiteArr[$dwcArr['domainID']].' ('.$dwcArr['domainID'].'), ';
if(isset($dwcArr['siteID'])) $locStr .= $this->domainSiteArr[$dwcArr['siteID']].' ('.$dwcArr['siteID'].'), ';
if(isset($dwcArr['locality'])) $locStr .= $dwcArr['locality'];
$dwcArr['locality'] = trim($locStr,', ');
}
if(isset($dwcArr['plotDim'])){
$dwcArr['locality'] .= $dwcArr['plotDim'];
unset($dwcArr['plotDim']);
}
$dwcArr['locationID'] = $locationStr;
}
else{
$dwcArr['locality'] = $sampleArr['namedLocation'];
$this->errorStr = 'locality data failed to populate';
$this->setSampleErrorMessage($sampleArr['samplePK'], $this->errorStr);
//return false;
}
if(!empty($sampleArr['collection_location'])){
if(!isset($dwcArr['locationID']) || $dwcArr['locationID'] != $sampleArr['collection_location']) $dwcArr['locality'] .= ', '.trim($sampleArr['collection_location'],' ,;.');
}
if(!empty($dwcArr['locality'])) $dwcArr['locality'] = trim($dwcArr['locality'],' ,;.');
}
//Taxonomic fields
$skipTaxonomy = array(5,6,10,13,16,21,23,31,41,42,58,60,61,62,67,68,69,76,92);
if(!in_array($dwcArr['collid'],$skipTaxonomy)){
$identArr = array();
$taxonCode = '';
if(isset($sampleArr['identifications']) && !in_array($dwcArr['collid'], array(46,98))){
$identArr = $sampleArr['identifications'];
}
if(!$identArr && $sampleArr['taxonID'] && !in_array($dwcArr['collid'], array(46,98))){
$hash = hash('md5', str_replace(' ','',$sampleArr['taxonID'].'manifests.d.'));
$identArr[$hash] = array('sciname' => $sampleArr['taxonID'], 'identifiedBy' => 'manifest', 'dateIdentified' => 's.d.', 'taxonRemarks' => 'Identification source: inferred from shipment manifest');
}
if(!$identArr){
//Identifications not supplied via API nor manifest, thus try to grab from sampleID with collection specific format
$taxonCode = '';
$taxonRemarks = '';
if(in_array($dwcArr['collid'], array(46,98))){
if (preg_match('/\.\d{8}\.([a-zA-Z]{2,15})\./', $sampleArr['sampleID'], $m)) {
$taxonCode = $m[1];
$taxonRemarks = 'Identification source: parsed from NEON sampleID';
}
}
// Should not ever need this for collid 30 anymore, but leaving in case it's useful
// if($dwcArr['collid'] == 30){
// $identArr[] = array('sciname' => $dwcArr['identifications'][0]['sciname'],
// 'identifiedBy' => 'NEON Lab',
// 'dateIdentified' => 's.d.');
// }
elseif($dwcArr['collid'] == 56){
if(preg_match('/\.\d{4}\.\d{1,2}\.([A-Z]{2,15}\d{0,2})\./', $sampleArr['sampleID'], $m)){
$taxonCode = $m[1];
$taxonRemarks = 'Identification source: parsed from NEON sampleID';
}
}
// elseif(!in_array($dwcArr['collid'], array(22,50,57))){
// if(preg_match('/\.\d{8}\.([A-Z]{2,15}\d{0,2})\./',$sampleArr['sampleID'], $m)){
// $taxonCode = $m[1];
// $taxonRemarks = 'Identification source: parsed from NEON sampleID';
// }
// }
}
if($taxonCode){
$hash = hash('md5', str_replace(' ','',$taxonCode.'sampleIDs.d.'));
$identArr[$hash] = array('sciname' => $taxonCode, 'identifiedBy' => 'sampleID', 'dateIdentified' => 's.d.', 'taxonRemarks' => $taxonRemarks);
}
if($identArr){
$isCurrentKey = 0;
$bestDate = 0;
foreach($identArr as $idKey => &$idArr){
if(!isset($idArr['sciname'])) unset($identArr[$idKey]);
//Translate NEON taxon codes or check/clean scientific name submitted
if(preg_match('/^[A-Z0-9]+$/', $idArr['sciname'])){
//Taxon is a NEON code that needs to be translated
if($taxaArr = $this->translateTaxonCode($idArr['sciname'])){
$idArr = array_merge($idArr, $taxaArr);
}
}
else{
if($taxaArr = $this->getTaxonArr($idArr['sciname'])){
if(!empty($idArr['scientificNameAuthorship'])) unset($taxaArr['scientificNameAuthorship']);
$idArr = array_merge($idArr, $taxaArr);
}
}
//Evaluate if any incoming determinations should be tagged as isCurrent
if(!$isCurrentKey) $isCurrentKey = $idKey; //First determination is set as isCurrent as the default
if(isset($idArr['dateIdentified']) && preg_match('/^\d{4}/', $idArr['dateIdentified']) && $idArr['dateIdentified'] > $bestDate){
$bestDate = $idArr['dateIdentified'];
$isCurrentKey = $idKey;
}
}
if($isCurrentKey) $identArr[$isCurrentKey]['isCurrent'] = 1;
$appendIdentArr = array();
foreach($identArr as $idKey => &$idArr){
//Check to see if any determination needs to be protected
$protectTaxon = $this->protectTaxonomyTest($idArr);
if($protectTaxon){
$idArrClone = $idArr;
if($idArr['taxonPublished']) $idArrClone['sciname'] = $idArr['taxonPublished'];
else $idArrClone['sciname'] = $idArr['taxonPublishedCode'];
unset($idArrClone['scientificNameAuthorship']);
unset($idArrClone['family']);
if(preg_match('/^[A-Z0-9]+$/', $idArrClone['sciname'])){
//Taxon is a NEON code that needs to be translated
if($taxaArr = $this->translateTaxonCode($idArrClone['sciname'])){
$idArrClone = array_merge($idArrClone, $taxaArr);
}
}
else{
if($taxaArr = $this->getTaxonArr($idArrClone['sciname'])){
$idArrClone = array_merge($idArrClone, $taxaArr);
}
}
$appendIdentArr[] = $idArrClone;
$idArr['securityStatus'] = 1;
$idArr['securityStatusReason'] = 'Locked - NEON redaction list';
}
else{
$idArr['securityStatus'] = 0;
$idArr['securityStatusReason'] = '';
}
//Check to see if current taxon is the most current taxon
if(!empty($idArr['isCurrent'])){
if(isset($this->taxonArr[$idArr['sciname']]['accepted'])){
if($idArr['sciname'] != $this->taxonArr[$idArr['sciname']]['accepted']){
$idArr['scientificNameAuthorship'] = $this->taxonArr[$idArr['sciname']]['acceptedAuthor'];
$idArr['tidInterpreted'] = $this->taxonArr[$idArr['sciname']]['acceptedTid'];
$idArr['sciname'] = $this->taxonArr[$idArr['sciname']]['accepted'];
}
}
}
}
if($appendIdentArr) $identArr = array_merge($identArr, $appendIdentArr);
$dwcArr['identifications'] = $identArr;
}
}
// Occurrence associations
if(isset($sampleArr['associations'])){
$dwcArr['associations'] = $sampleArr['associations'];
}
//Add DwC fields that were imported as part of the manifest file
if($sampleArr['symbiotaTarget']){
if($symbArr = json_decode($sampleArr['symbiotaTarget'],true)){
foreach($symbArr as $symbField => $symbValue){
if($symbValue !== '' && !isset($dwcArr[$symbField])) $dwcArr[$symbField] = $symbValue;
}
}
}
}
else{
$this->errorStr = 'ERROR: unable to retrieve collid using sampleClass: '.$sampleArr['sampleClass'];
$this->setSampleErrorMessage($sampleArr['samplePK'], 'unable to retrieve collid using sampleClass');
return false;
}
}
if(isset($dwcArr['eventDate'])) $dwcArr['eventDate'] = $this->formatDate($dwcArr['eventDate']);
if(isset($dwcArr['eventDate2'])){
$dwcArr['eventDate2'] = $this->formatDate($dwcArr['eventDate2']);
if($dwcArr['eventDate'] == $dwcArr['eventDate2']) unset($dwcArr['eventDate2']);
}
$this->applyCustomAdjustments($dwcArr);
return $dwcArr;
}
private function setCollectionIdentifier(&$dwcArr,$sampleClass){
$status = false;
if($sampleClass){
$sql = 'SELECT collid, datasetName FROM omcollections
WHERE (datasetID = "'.$sampleClass.'") OR (datasetID LIKE "%,'.$sampleClass.',%") OR (datasetID LIKE "'.$sampleClass.',%") OR (datasetID LIKE "%,'.$sampleClass.'")';
$rs = $this->conn->query($sql);
if($rs->num_rows == 1){
$r = $rs->fetch_object();
$this->activeCollid = $r->collid;
$dwcArr['collid'] = $r->collid;
if($r->datasetName) $dwcArr['verbatimAttributes'] = $r->datasetName;
else $dwcArr['verbatimAttributes'] = $sampleClass;
$status = true;
}
$rs->free();
}
return $status;
}
private function setNeonLocationData(&$dwcArr, $locationName){
$url = $this->neonApiBaseUrl.'/locations/'.urlencode($locationName).'?history=true&apiToken='.$this->neonApiKey;
//echo 'loc url: '.$url.'<br/>';
$resultArr = $this->getNeonApiArr($url);
$eventDate = $dwcArr['eventDate'];
$matchingIndex = null;
if(!$resultArr) return false;
foreach ($resultArr['locationHistory'] as $index => $location) {
$startDate = $location['locationStartDate'];
$endDate = $location['locationEndDate'];
// Check if eventDate falls within the location history date range
if ($eventDate >= $startDate && (empty($endDate) || $eventDate <= $endDate)) {
$matchingIndex = $index;
break;
}
}
if ($matchingIndex == null) $matchingIndex = 0;
if(isset($resultArr['locationType']) && $resultArr['locationType']){
if($resultArr['locationType'] == 'SITE') $dwcArr['siteID'] = $resultArr['locationName'];
elseif($resultArr['locationType'] == 'DOMAIN') $dwcArr['domainID'] = $resultArr['locationName'];
}
if(isset($resultArr['locationDescription']) && $resultArr['locationDescription']){
$parStr = str_replace(array('"',', RELOCATABLE',', CORE','Parent'),'',$resultArr['locationDescription']);
$parStr = str_replace('re - Reach','Reach',$parStr);
$parStr = preg_replace('/ at site [A-Z]+/', '', $parStr);
$parStr = trim($parStr,' ,;');
if($parStr){
if($resultArr['locationType'] != 'SITE' && $resultArr['locationType'] != 'DOMAIN'){
$localityStr = '';
if(isset($dwcArr['locality'])) $localityStr = $dwcArr['locality'];
$dwcArr['locality'] = $parStr.', '.$localityStr;
}
}
}
$resultArr_history = $resultArr['locationHistory'][$matchingIndex];
if(!isset($dwcArr['decimalLatitude']) && isset($resultArr_history['locationDecimalLatitude']) && $resultArr_history['locationDecimalLatitude']){
$dwcArr['decimalLatitude'] = $resultArr_history['locationDecimalLatitude'];
}
if(!isset($dwcArr['decimalLongitude']) && isset($resultArr_history['locationDecimalLongitude']) && $resultArr_history['locationDecimalLongitude']){
$dwcArr['decimalLongitude'] = $resultArr_history['locationDecimalLongitude'];
}
if(!isset($dwcArr['verbatimCoordinates']) && isset($resultArr_history['locationUtmEasting']) && $resultArr_history['locationUtmEasting']){
$dwcArr['verbatimCoordinates'] = trim($resultArr_history['locationUtmZone'].$resultArr_history['locationUtmHemisphere'].' '.$resultArr_history['locationUtmEasting'].'E '.$resultArr_history['locationUtmNorthing'].'N');
}
$locPropArr_history = $resultArr_history['locationProperties'];