<?php
/**
* updating cached version of specimen record with original specimen data provider
* <br/><br/>
* final script, all subfiles ("Save_xy.php") provide final content in standardised way, used only for changing reference to voucher
* @author Gabriele Droege, DNA Bank Network <contact@dnabank-network.org>
* @version 2.0
* @package Search
* @copyright Copyright © 2011 DNA Bank Network http://www.dnabank-network.org<br>The contents of this file are subject to the Mozilla Public License Version 1.1
* @filesource
* @license http://www.mozilla.org/MPL/ MPL
*/
if (isset($_SESSION['guest']) || $_SESSION['guest']) {

echo "<tr><td colspan='3'><span class='error'>Sorry, as a guest you don't have permission for entering new DNA data! If you want to search for existing DNA data please use the Search function!</span></td></tr>"; }

else {

if($formSubmitNewRecord) {

$result = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT dataset.ID_Dataset AS ID_Dataset, " .
 "       schemata.QueryPart1b, " .
 "       schemata.QueryPart1_1, " .
 "       schemata.QueryPart1_2b, " .
 "       schemata.QueryPart2, " .
 "       schemata.QueryPart3, " .
 "       schemata.QueryPart4, " . 
 "       schemata.QueryPart5, " . 
 "       provider.Provider, " .
 "       dataset.Digir_Resource, " .
 "       dataset.Digir_Source, " .
 "		 dataset.FK_Provider, " .
 "		 dataset.Protocol, " .
 "       provider.FK_Schema " .
 "  FROM dataset " .
 "  LEFT JOIN provider ON dataset.FK_Provider = provider.ID_Provider " . 
 "  LEFT JOIN schemata ON provider.FK_Schema = schemata.ID_Schema " .
 " WHERE dataset.ID_Dataset = '$ID_Dataset'");
 
 while($row = mysqli_fetch_object($result)) 
      {
$ID_Dataset = $row->ID_Dataset;      
$Provider = $row->Provider; 
$QueryPart1b = $row->QueryPart1b;
$QueryPart1_1 = $row->QueryPart1_1;
$QueryPart1_2b = $row->QueryPart1_2b;
$QueryPart2 = $row->QueryPart2;
$QueryPart2a = $row->QueryPart2a;
$QueryPart3 = $row->QueryPart3;
$QueryPart4 = $row->QueryPart4;
$QueryPart5 = $row->QueryPart5;
$Digir_Resource = $row->Digir_Resource;
$Digir_Source = $row->Digir_Source;
$ID_Schema = $row->FK_Schema;
$FK_Provider = $row->FK_Provider;
$Protocol = $row->Protocol;
}

$SourceUnitID = urlencode($variable1);
$SourceInstitutionCode = urlencode($variable2);
$SourceCode = urlencode($variable3);
$Digir_Resource1 = urlencode($Digir_Resource);
$Digir_Source1 = urlencode($Digir_Source);
 
 
if($ID_Schema == 3)  //ACHTUNGXXX; hier noch unterscheiden zw. CatalogNoText und CatalogNo
{
$file = $Provider.$QueryPart1b.$Digir_Resource1.$QueryPart1_1.$Digir_Source1.$QueryPart1_2b."CatalogNumberText%3E".$SourceUnitID."%3C%2Fdarwin%3ACatalogNumberText".$QueryPart3.$SourceInstitutionCode.$QueryPart4.$SourceCode.$QueryPart5; } 

if($ID_Schema == 2) {
$file = $Provider."&query=".urlencode('<?xml version="1.0" encoding="UTF-8"?>
<request xmlns="http://www.biocase.org/schemas/protocol/1.3">
<header><type>search</type></header>
<search><requestFormat>http://www.tdwg.org/schemas/abcd/2.06</requestFormat>
<responseFormat start="0" limit="10">http://www.tdwg.org/schemas/abcd/2.06</responseFormat>
<filter><and><and><and><and><and><like path="/DataSets/DataSet/Units/Unit/UnitID">');
$file .= $SourceUnitID;
$file .= urlencode('</like><like path="/DataSets/DataSet/Units/Unit/SourceInstitutionID">');
$file .= $SourceInstitutionCode;
$file .= urlencode('</like></and><like path="/DataSets/DataSet/Units/Unit/SourceID">');
$file .= $SourceCode;
$file .= urlencode('</like></and></filter><count>false</count></search></request>'); }

//echo $file;
  $dom = new DOMDocument();
   $dom->Load($file);

if($ID_Schema == 1) {
  /**
  * calling specific script for saving data in ABCD1.2 format
  */
  include ("../input/Save_ABCD1.2.php");}
if($ID_Schema == 2) {
  /**
  * calling specific script for saving data in ABCD2.06 format
  */
  include ("../input/Save_ABCD2.06.php");}
if($ID_Schema == 3 or $ID_Schema == 6) {
  /**
  * calling specific script for saving data in DarwinCore format
  */
  include ("../input/Save_DarwinCore.php");}
if($ID_Schema == 4) {
  /**
  * calling specific script for saving data in ABCD2.05 format
  */
  include ("../input/Save_ABCD2.05.php");}

if($FK_Provider == "") {

include ("../input/Save_GBIF.php"); }
 
 if(isset($Identifications))
{
  
    /********************************************************************************************
    * first table to update is cachecollection                                                  *
    ********************************************************************************************/

  $sql4 = "UPDATE cachecollection SET
  UnitID_Specimen = '$sqlUnitID', 
  CollectionCode_Specimen = '$sqlSourceName', 
  InstitutionCode_Specimen = '$sqlSourceInstitutionCode', 
  ContinentOrOcean = '$sqlContinentOrOcean', 
  CountryName = '$sqlCountryName', 
  CountryISO2 = '$sqlISO2', 
  Collectors = '$sqlPersonName', 
  CollectionDate = '$sqlCollectionDate', 
  CollectionDateMin = '$sqlCollectionDateMin', 
  CollectionDateMax = '$sqlCollectionDateMax', 
  CollectorsNo = '$sqlCollectorsNo', 
  Locality = '$sqlLocality', 
  Longitude = '$sqlLongitude', 
  Latitude = '$sqlLatitude', 
  Altitude = '$sqlAltitude', 
  CollectionInfo_Other = '$sqlGatheringOther', 
  FK_Dataset_Specimen = '$ID_Dataset', 
  GUID_Specimen = '$sqlUnitGUID', 
  Updated_Who = '$log' WHERE ID_Cache = '$ID_Cache'";

 $result4 = mysqli_query($GLOBALS["___mysqli_ston"], $sql4);
 
###############################################Error 4####################################################


if(!$result4)
     { 
  $msg = $sql4."\n";
  $msg .= "####Error 4####";
  if($debug == '1') echo $msg;
  trigger_error($msg, E_USER_ERROR);
  include ("../config/Errorreport.php"); 
  $error = "true"; } 
         
#########################################################################################################    

	$sqlselectIDTaxonIdentified = "SELECT * FROM cachetaxonidentified WHERE FK_Cache = '$ID_Cache'";
	$resultselectIDTaxonIdentified = mysqli_query($GLOBALS["___mysqli_ston"], $sqlselectIDTaxonIdentified);
	
	while($row = mysqli_fetch_object($resultselectIDTaxonIdentified)) { $ID_CacheTaxonIdentified = $row->ID_TaxonIdentified; 
	
	$sqldelete1 = "DELETE FROM cachehighertaxa WHERE FK_CacheTaxonIdentified = '$ID_CacheTaxonIdentified'";
	$resultdelete1 = mysqli_query($GLOBALS["___mysqli_ston"], $sqldelete1); }
	
	$sqldelete2 = "DELETE FROM cachetaxonidentified WHERE FK_Cache = '$ID_Cache'";
	$resultdelete2 = mysqli_query($GLOBALS["___mysqli_ston"], $sqldelete2);
	
	$sqldelete3 = "DELETE FROM cachemultimedia WHERE FK_Cache = '$ID_Cache'";
	$resultdelete3 = mysqli_query($GLOBALS["___mysqli_ston"], $sqldelete3);

  foreach ($Identifications as $IndexIdentification => $Identification) {
  
    /********************************************************************************************
    * for each identification tag entering one row in cachetaxonidentified                      *
    ********************************************************************************************/


  $Genus = $sqlGenus[$IndexIdentification];
  $Subgenus = $sqlSubgenus[$IndexIdentification];
  $FirstEpithet = $sqlFirstEpithet[$IndexIdentification];
  $SecondEpithet = $sqlSecondEpithet[$IndexIdentification];
  $Rank = $sqlRank[$IndexIdentification];
  $HybridFlag = $sqlHybridFlag[$IndexIdentification];
  $NameAuthorYear = $sqlNameAuthorYearString[$IndexIdentification];
  $Name_All = $sqlName_All[$IndexIdentification];
  $PreferredFlag = $sqlPreferredIdentificationFlag[$IndexIdentification];
  //if($PreferredFlag == '0') { $PreferredFlag = '0');
  //if($PreferredFlag = '' and $PreferredFlag != '0')
  //{ $PreferredFlag = '1';  }
  
  $sql5 = "INSERT INTO cachetaxonidentified (FK_Cache, Genus, Subgenus, FirstEpithet, SecondEpithet, Rank, HybridFlag, NameAuthorYear, Other, PreferredFlag, Created_Who) VALUES ('$ID_Cache','$Genus','$Subgenus','$FirstEpithet','$SecondEpithet','$Rank','$HybridFlag','$NameAuthorYear','$Name_All','$PreferredFlag','$log')";
  $result5 = mysqli_query($GLOBALS["___mysqli_ston"], $sql5);

  $IDTableCacheTaxonIdentified=((is_null($___mysqli_res = mysqli_insert_id($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res);
  
#################################################Error 5################################################  
  if(!$result5)
         { $msg = $sql5."\n";
           $msg .= "####Error 5####";
		   if($debug == '1') echo $msg;
           trigger_error($msg, E_USER_ERROR);
           include ("../config/Errorreport.php"); 
           $error = "true"; } 
         
########################################################################################################         

      foreach ($HigherTaxa as $index => $HigherTaxon) { // more than one HigherTaxon per Identification possible
      
    /********************************************************************************************
    * for each identification tag and higher taxon tag entering one row in cachehighertaxa      *
    ********************************************************************************************/      
       
         $TaxonHigher = $sqlHigherTaxon[$index];
         $RankHigher = $sqlHigherTaxonRank[$index];

      $sql6 = "INSERT INTO cachehighertaxa (FK_CacheTaxonIdentified, HigherTaxon, TaxonRank, Created_Who) VALUES ('$IDTableCacheTaxonIdentified','$TaxonHigher','$RankHigher','$log')";
      $result6 = mysqli_query($GLOBALS["___mysqli_ston"], $sql6);

#################################################Error 6################################################
if(!$result6)
         { $msg = $sql6."\n";
           $msg .= "####Error 6####";
		   if($debug == '1') echo $msg;
           trigger_error($msg, E_USER_ERROR);
           include ("../config/Errorreport.php"); 
           $error = "true"; } 
         
########################################################################################################         
  }
 }
 
if(isset($sqlFileURI))
{ 
foreach ($sqlFileURI as $MultiMediaObject)
  {
    /*********************************************************************************************
    * for each multimedia tag entering one row in cachemultimedia                                *
    *********************************************************************************************/ 
  $sql7 = "INSERT INTO cachemultimedia (FK_Cache, Multimedia, Created_Who) VALUES ('$ID_Cache','$MultiMediaObject','$log')";
  $result7 = mysqli_query($GLOBALS["___mysqli_ston"], $sql7);
  
#######################################Error 7###############################################################

if(!$result7)
{ $msg = $sql7."\n";
  $msg .= "####Error 7####";
  if($debug == '1') echo $msg;
  trigger_error($msg, E_USER_ERROR);
  include ("../config/Errorreport.php");   
  $error = "true"; }
  
#############################################################################################################    
} 
if(empty($sqlFileURI)) {
foreach ($sqlProductURI as $MultiMediaObject)
  {
   
  $sql8= "INSERT INTO cachemultimedia (FK_Cache, Multimedia, Created_Who) VALUES ('$ID_Cache','$MultiMediaObject','$log')";
  $result8 = mysqli_query($GLOBALS["___mysqli_ston"], $sql8);
  
#######################################Error 8###############################################################

if(!$result8)
{ $msg = $sql8."\n";
  $msg .= "####Error 8####";
  if($debug == '1') echo $msg;
  trigger_error($msg, E_USER_ERROR);
  include ("../config/Errorreport.php");   
  $error = "true"; }
  
#############################################################################################################    
} } }


if($result4)
{ 

echo "<span class='fine'>Specimen record has been updated successfully: <br />Specimen Number: </span><span class='error'>".$sqlUnitID."</span><span class='fine'> Institution Code: </span><span class='error'>".$sqlSourceInstitutionCode."</span><span class='fine'> Collection Code: </span><span class='error'>".$sqlSourceName."</span><span class='fine'> Taxon Name: </span><span class='error'>".$NameAuthorYear."</span><br />"; }   
  }
  
else { echo "xxxto do"; }


 
 
 
 
 
 
 
 
} // if($formSubmitNewRecord)


} // if user not a guest

?>