<?php
/*=======================================================================
 *
 * dpf.php
 *
 * Autor: Marc Vollmann
 *
 =======================================================================*/

$userType = "";
$userTypeName = "";

if (!isset($autoembargo)) :
   include_once ("../include/mcglobal.inc.php");
   // $noExecGlobDefs = "1";
   include_once ("../include/auth.inc.php");
   include_once ("../include/image.inc.php");
   // include_once ("../include/email.inc.php");

   // Check HTTP-Parameters
   getSecHttpVars("1",array("cmpId", "hqId", "eid", "usrName", "usrFirstname", "adStreet", "cmpHsno", "cmpDpfChecksum",
                            "adZipcode", "adCity", "adCountry", "statusMessage", "DPFTypeToBeChecked"));

   getLanguage(__FILE__);   
   $deactivateMenuStatic = "1";
   $pageTitel = getLngt("SANKTIONSLISTENABGLEICH");
   include_once ("../admin/menu.php");
   include_once ("../include/html.inc.php");
   getCurrentScript(__FILE__);
   
   $autoembargo = "0";

   // Select user-type for mode of security check 
   $userType = getFieldValueFromId("user","usr_id",$usr_id,"usr_type");
   $userTypeName = getUserTypeName($userType);
else :
   $GLOBALS['HTTP_SERVER_VARS']['HTTP_HOST'] = "assecutor.de";
endif;



// ***********************
// * General definitions *
// ***********************


$port = ":80";
$constPort = getParameterValue("0", "DPF_PORT", "0");
if ($constPort != "") : $port = $constPort; endif;

$server = "api.dominowatch.com";
$constServer = getParameterValue("0", "DPF_SERVER", "0");
if ($constServer != "") : $server = $constServer; endif;

// Request id
// $sourceid = rand(1,30000);
$sourceid = $eid;
if ($sourceid == "") :
   $sourceid = getParameterValue("0", "EXPORT_CONST_01", $hqId);
   if ($sourceid == "") :
      $sourceid = getParameterValue("0", "MASTER_PREFIX", "0");
      if ($sourceid == "") :
         $sourceid = getDateTime("6");
      endif;
   endif;
endif;


// User and password
$username = "api_assecutor_01";
$constuserID = getParameterValue("0", "DPF_USER_ID", "0");
if ($constuserID != "") : $username = $constuserID; endif;

$password = "";
$constPassword = getParameterValue("0", "DPF_USER_PASSWD", "0");
if ($constPassword != "") : $password = $constPassword; endif;

// Search modes
// 1: zum Stöbern im Content, 2: auch Ähnlichkeiten, 3: möglichst nur echte Treffer
$matchtype = "2";
$constMatchtype = getParameterValue("0", "DPF_MATCHTYPE", "0");
if ($constMatchtype != "") : $matchtype = $constMatchtype; endif;
// 1: nur Namen, 2: nur Strasse, 3: Namen und Strasse, 4: komplett alle Felder  	
$checktype = "1";
$constChecktype = getParameterValue("0", "DPF_CHECKTYPE", "0");
if ($constChecktype != "") : $checktype = $constChecktype; endif;

// Set state for comparison
$doCheckCurrentDataset = true;
$newDpfChecksum = md5($usrFirstname . $usrName . $adStreet . $cmpHsno . $adZipcode . $adCity);
if ($newDpfChecksum == $cmpDpfChecksum) :
   $doCheckCurrentDataset = false;
endif;

// User data to be checked
$name = utf8_encode($usrFirstname . " " . $usrName);
$street = utf8_encode($adStreet . " " . $cmpHsno);
$city = utf8_encode($adCity);
$zip = utf8_encode($adZipcode);
$country = "";

// Logging enabled
$loggingEnabled = TRUE;
$logFile = "../log/DPF_LOG";

// Echo enabled
$echoEnabled = TRUE;



// *************
// * Functions *
// *************

function writeLocatingLog($file, $value) {
   global $loggingEnabled;
   if ($loggingEnabled) :
      writeToFile($file, $value);
   endif;
}

function connectDPF($completeReq) {
	 global $server, $port;
   $response = "";
   $errno = "";
   $errstr = "";
   $fp = fsockopen ($server, substr($port, 1), @$errno, @$errstr, 10);
   if (!$fp) {
       $response = "$errstr ($errno)<br>\n";
       sendInternalMail("DPF :: SOCKET FAILED!");
   } else {
       fputs ($fp, $completeReq);
       if (fflush($fp)) :

          // Read header
          $httpHeader = "";
          $httpBodyLength = 0;
          if (!feof($fp)) :
             $line = trim(fgets ($fp,1024));
             $httpHeader .= trim($line);
             while (!feof($fp) && $line != "") {
          	     $line = trim(fgets ($fp,1024));
          	     $httpHeader .= $line;
          	     if (!(strpos($line, "Content-Length: ") === FALSE)) :
          	        $httpBodyLength = trim(substr($line, 16));
          	     endif;
             }
          endif;
          // writeLocatingLog($logFile, "::: " . $httpHeader . "\r\n");
          // writeLocatingLog($logFile, "::: " . $httpBodyLength . "\r\n");

          $count = 0;
          while (!feof($fp) && $count < $httpBodyLength) {
          	 $line = trim(fgets ($fp,2));
             $response .= $line;
             $count++;
          }
          // writeLocatingLog($logFile, ":# Loops: " . $count . "\r\n");          
          
       else :
          $response = "ERR: " . $errno . " " . $errstr;
       endif;
       
       fclose ($fp);
   }
   return $response;
}

// Generates the systax of a request according to the SAPPER specification
function generateRequestSapper($username, $password, $matchtype, $checktype, $name, $street, $city, $zip, $country, $sourceid) {

$requestHeader = "";
$requestBody = "";
if ($username != "" && $password != "" && $matchtype != "" && $checktype != "" && $sourceid != "") :

   // Define header request
   $requestHeader .= "POST /dominorealtime.asmx HTTP/1.1\r\n";
   $requestHeader .= "Host: api.dominowatch.com\r\n";
   $requestHeader .= "Content-Type: text/xml; charset=utf-8\r\n";
   $requestHeader .= "Content-Length: LENGTH\r\n";
   $requestHeader .= "SOAPAction: \"http://api.dominowatch.com/DominoMatchResult\"\r\n\r\n";

   // Connection request
   $requestBody .= "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
   $requestBody .= "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">";
   $requestBody .= "  <soap:Body>";
   $requestBody .= "    <DominoMatchResult xmlns=\"http://api.dominowatch.com\">";
   $requestBody .= "      <dominoAuth>";
   $requestBody .= "        <Username>" . $username . "</Username>";
   $requestBody .= "        <Password>" . $password . "</Password>";
   $requestBody .= "      </dominoAuth>";
   $requestBody .= "      <matchSet>";
   $requestBody .= "        <matchtype>" . $matchtype . "</matchtype>";
   $requestBody .= "        <checktype>" . $checktype . "</checktype>";
   $requestBody .= "      </matchSet>";
   $requestBody .= "      <inputInfo>";
   $requestBody .= "        <name>" . $name . "</name>";
   $requestBody .= "        <street>" . $street . "</street>";
   $requestBody .= "        <city>" . $city . "</city>";
   $requestBody .= "        <zip>" . $zip . "</zip>";
   $requestBody .= "        <country>" . $country . "</country>";
   $requestBody .= "      </inputInfo>";
   $requestBody .= "      <userData>";
   $requestBody .= "        <sourceid>" . $sourceid . "</sourceid>";
   $requestBody .= "      </userData>";
   $requestBody .= "    </DominoMatchResult>";
   $requestBody .= "  </soap:Body>";
   $requestBody .= "</soap:Envelope>";
   
   // $requestBody = urlencode($requestBody);
   
   $requestBodyLen = strlen($requestBody);
   
   $requestHeader = str_replace ("LENGTH", $requestBodyLen, $requestHeader);
endif;

$request = $requestHeader . $requestBody;

return $request;
}

function getTagContent($strToParse, $tagBegin, $tagEnd) {
  $tagContent = "";
  $repeat = TRUE;
  while ($repeat && !(strpos($strToParse, $tagBegin) === FALSE) && !(strpos($strToParse, $tagEnd) === FALSE)) :
  
     $pos0 = strpos($strToParse, $tagBegin);                         // begin of tagBegin (first occurrence)
     $pos1 = strpos($strToParse, $tagBegin) + strlen($tagBegin);     // end of tagBegin   (first occurrence)
     $pos2 = strpos($strToParse, $tagEnd);                           // begin of tagEnd   (first occurrence)
     $pos3 = strpos($strToParse, $tagEnd) + strlen($tagEnd);         // end of tagEnd     (first occurrence)
     
     $repeat = FALSE;
     if ($pos2 - $pos1 > 0) :

        // Get the content of the tag
        $tagContent = substr($strToParse, $pos1, $pos2 - $pos1);
     endif;
  endwhile;
  return $tagContent;
}

// *************************************

$statusMessage = "";
$currentTime = getDateTime("0");

if ($doCheckCurrentDataset) :

   // Generate request
   $request = generateRequestSapper($username, $password, $matchtype, $checktype, $name, $street, $city, $zip, $country, $sourceid);
   writeLocatingLog($logFile, "--------------------------------------------------------------------------------------------------" . "\r\n");
   writeLocatingLog($logFile, $cmpDpfChecksum . " " . $newDpfChecksum . "\r\n");
   writeLocatingLog($logFile, $name . " " . $street . " " . $zip . " " . $city . "\r\n");
   writeLocatingLog($logFile, $request . "\r\n");
   
   // Get connection and response 
   $startTime = getDateTime("0");
   $response = connectDPF($request."\r\n");
   $endTime = getDateTime("0");
   writeLocatingLog($logFile, "Request time : " . $startTime . " - " . $endTime . "\r\n");
   writeLocatingLog($logFile, $response . "\r\n");
   // writeLocatingLog($logFile, "--------------------------------------------------------------------------------------------------" . "\r\n");
   
   // Parse the response and trigger actions
   $dfpErrCode = "0";
   $dfpErrText = "";
   $dfpExpdate = "";
   $dfpAcctype = "";
   $dfpRemtrans = "";
   $dfpVerid = "";
   $dfpTranid = "";
   $dfpMatchlevel = "";
   $dfpLogurl = "";
   
   if ($response == "") :
      // Response is empty   
      $dfpErrCode = "9999";
      $dfpErrText = "Keine Antwort vom DFP-Server!";
   else :
      $dfpErrCode = getTagContent($response, "<errcode>", "</errcode>");            // Error code
      $dfpErrText = getTagContent($response, "<errdescr>", "</errdescr>");          // Error description
      $dfpExpdate = getTagContent($response, "<expdate>", "</expdate>");            // Datum, wann das gebuchte Abonnement (Demo oder Produktiv / Standard) endet
      $dfpAcctype = getTagContent($response, "<acctype>", "</acctype>");            // 1: Demo; 2: Standard
      $dfpRemtrans = getTagContent($response, "<remtrans>", "</remtrans>");         // Bei der Demovariante wird hier die Anzahl restlich verfügbarer Transaktionen angezeigt
      $dfpVerid = getTagContent($response, "<verid>", "</verid>");                  // Die aktuelle Version der Boykottlisten
      $dfpTranid = getTagContent($response, "<tranid>", "</tranid>");               // Domino-Referenz Nr.
      $dfpMatchlevel = getTagContent($response, "<matchlevel>", "</matchlevel>");   // 0: keinen Treffer; 1: Treffer unter RedAlert; 2: Treffer ueber RedAlert
      $dfpLogurl = getTagContent($response, "<logurl>", "</logurl>");               // URL zur Report-Seite fuer die actuelle Abfrage
   endif;
   
   // Erases output buffer because of charset
   // ob_clean();
   // ob_start();
   // ob_end_clean();
   // ob_flush(); flush();
   // ob_end_flush();
   
   // Handling according to the result   
   if ($dfpErrCode == "0") :   
      if ($dfpMatchlevel == "0") :      
         $statusMessage = getLngt("Der Datensatz ist NICHT auffällig gemäß der Sanktionslistenprüfung!");
         // if ($cmpId != "" && is_numeric($cmpId) && $dfpAcctype == "2") :
            updateStmt("company","cmp_id",$cmpId,array("cmp_dpf_state", "10", "cmp_dpf_datetime", $currentTime, "cmp_dpf_checksum", $newDpfChecksum));
         // endif;
      elseif ($dfpMatchlevel == "1" || $dfpMatchlevel == "2") :
         if ($dfpMatchlevel == "1") :
            $statusMessage = getLngt("Der Datensatz ist AUFFÄLLIG gemäß der Sanktionslistenprüfung!");
         else :
            $statusMessage = getLngt("Der Datensatz ist STARK AUFFÄLLIG gemäß der Sanktionslistenprüfung!");
         endif;
         // if ($cmpId != "" && is_numeric($cmpId) && $dfpAcctype == "2") :
            updateStmt("company","cmp_id",$cmpId,array("cmp_dpf_state", $dfpMatchlevel, "cmp_dpf_datetime", $currentTime, "cmp_dpf_checksum", $newDpfChecksum, "cmp_authenticated", "0", "cmp_modify_status", "0"));
         // endif;
      endif;
   else :
      $statusMessage = getLngt("Die Antwort des Sanktionslisten-Servers weist den Fehler " . $dfpErrCode . " auf! " . "[" . $dfpErrText . "]");
   endif;
else:
   $statusMessage = getLngt("Der Datensatz wurde nicht nachgeprüft, da keine relevanten Daten gemäß der Sanktionslistenprüfung modifiziert wurden!");
endif;

// INFORMATIONS:
// Possible states in DB-field "cmp.cmp_dpf_state":
//  1 = noticeable (state from SAPPER, etc.)
//  2 = heavy noticeable (state from SAPPER, etc.)
// 11 = noticeable, but authentication manually set ok
// 12 = heavy noticeable, but authentication manually set ok
?>


<?php if ($autoembargo == "0") : ?>
<html>

<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title><?php echo $pageTitel ?></title>
<link rel="stylesheet" type="text/css" href="../css/phoenix.css">
<style type="text/css">
  <?php include_once ("../css/navigation.css.php"); ?>
</style>

<?php include_once ("../include/js_framework.inc.php"); ?>

<script type="text/javascript">
<!--
// NAVIGATION
<?php echo $jsMenuOut; ?>


-->
</script>
</head>


<body onLoad="<?php echo $phpCurrentNavigationOnLoad ?>this.moveTo((screen.width * 0.5)-(document.body.offsetWidth * 0.5),(screen.height * 0.5)-(document.body.offsetHeight * 0.5));">

  <?php echo $phpMenuOut ?>
  <?php echo $phpReducedMenuOut ?>
  <?php echo $phpPageTitelOut ?>

  <?php echo htmlDivLineSpacer("30px"); ?>

  <div valign="center" align="center">
    <b><?php echo $statusMessage; ?></b>
  </div>
  
  <?php echo htmlDivLineSpacer("20px"); ?>
  
  <?php if ($doCheckCurrentDataset) : ?>
    <div valign="center" align="center">  
      <?php 
        echo "Server: " . $server . "<br>";
        // echo "CompID: " . $cmpId . "<br>";
        echo "Matchtype: " . $matchtype . "<br>";
        echo "Checktype: " . $checktype . "<br>";
        echo "<br>";
        echo "<br>";
        echo "PRÜFDATEN: <br>";
        echo $name . "<br>";
        echo $street . "<br>";
        echo $city . "<br>";
        echo $zip . "<br>";
        echo $country . "<br>";
        echo $sourceid . "<br>";
        echo "<br>";
        echo "<br>";
        echo "Err.Code: " . $dfpErrCode . "<br>";
        echo "Err.Text: " . $dfpErrText . "<br>";
        echo "ExpDate: " . $dfpExpdate . "<br>";
        echo "AccType: " . $dfpAcctype . "<br>";
        echo "RemTrans: " . $dfpRemtrans . "<br>";
        echo "VersionID: " . $dfpVerid . "<br>";
        echo "TranID: " . $dfpTranid . "<br>";
        echo "Matchlevel: " . $dfpMatchlevel . "<br>";
        echo "LogURL: " . $dfpLogurl . "<br>";
      ?>
    </div>
  <?php endif; ?>
      
</body>
      
</html>
<?php endif; ?>
      