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

include_once ("../include/mcglobal.inc.php");
include_once ('../include/email/htmlMimeMail.php');


// Execution-Time for script
set_time_limit(0);

$currentTime = getDateTime("0");

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

$GLOBALS['HTTP_SERVER_VARS']['HTTP_HOST'] = "assecutor.de";


// ***********************
// * 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;

// 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";
   } 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;
}


// Get jobs for autoembargo
function getDPFData() {
  global $db, $logFile, $currentTime;

  // Try to connect request server because of performance
  global $db2;
  getDb2Connection();

  $retArray = array();

  // Get all couriers with having jobs since $startTime
  $jobExportTimeInDays = 30;
  $startTime = getDateTime("datetime_plus_offset", array(0,0,0,0,-($jobExportTimeInDays),0), "Y-m-d") . " 00:00:00";
  $endTime = $currentTime;

  $sqlquery = "SELECT DISTINCT"
               . "   cmp.cmp_id, cmp.cmp_type, cmp.cmp_comp, cmp.cmp_comp2, cmp.cmp_iln, cmp.cmp_tax_idno,"
               . "   cmp.cmp_bank, cmp.cmp_bankno, cmp.cmp_bankacc, cmp.cmp_authenticated, cmp.cmp_visible,"
               . "   cmp.cmp_match, cmp.cmp_cashmode, cmp.cmp_hsno, cmp.cmp_dpf_checksum,"
               . "   cr.hq_id, cr.cr_id, cr.cr_eid, cr.hq_id,"
               . "   usr.usr_name, usr.usr_firstname, usr.usr_email, usr.usr_phone,"
               . "   usr.usr_phone2, usr.usr_fax, ad.ad_street, ad.ad_zipcode, ad.ad_city"
               . " FROM job AS jb, courier AS cr, company AS cmp, user AS usr, address AS ad"
               . " WHERE jb.jb_export_time >= '" . $startTime . "'   AND"
               . "       jb.jb_export_time <= '" . $endTime . "'   AND"
               . "       jb.cr_id = cr.cr_id    AND"
               . "       cmp.cmp_id = cr.cmp_id AND"
               . "       cmp.ad_id = ad.ad_id   AND"
               . "       cr.usr_id = usr.usr_id"
               . " ORDER BY cmp.cmp_comp";
// echo $sqlquery . "<br>";
  $result = $db2->query($sqlquery);

  if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
  while ($row = $result->fetch_assoc()):
        $retArray[] = array($row["cmp_id"], $row["cmp_comp"], $row["cmp_comp2"], $row["cmp_iln"], $row["cmp_tax_idno"], 
                            $row["usr_name"], $row["usr_firstname"], $row["usr_email"], $row["usr_phone"], 
                            $row["ad_street"], $row["cmp_hsno"], $row["ad_zipcode"], $row["ad_city"], $row["hq_id"], 
                            $row["cr_eid"], $row["cmp_dpf_checksum"], $row["cmp_authenticated"], $row["cmp_visible"]);
  endwhile;
  $result->free();

  return $retArray;
}  

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


// ********************************
// *** Send mails automatically ***
// ********************************

$constDPFCourierEnabled = getParameterValue("0", "DPF_CR_ENABLED", "0");  // "Meta-Global" <=> hq_id = 0
if ($constDPFCourierEnabled == '1') :

   // Get data of the couriers to be checked
   $dataArray = getDPFData();
// print_r($dataArray);
   // Loop all entries
   $lenDataArray = count($dataArray);

   // Mark all rows selected for embargo check
   // Do this here to avoid multiple rows
   /*
   for ($i = 0; $i < $lenDataArray; $i++) :
       updateStmt("company", "cmp_id", $dataArray[$i][0], array("cmp_dpf_state", "99"), "");
   endfor;
   */

   for ($i = 0; $i < $lenDataArray; $i++) :

       // Current data to be checked
       $cmpId = $dataArray[$i][0];
       $cmpComp = $dataArray[$i][1];
       $cmpComp2 = $dataArray[$i][2];
       $cmpILN = $dataArray[$i][3];
       $cmpTaxIdno = $dataArray[$i][4];
       $usrName = $dataArray[$i][5];
       $usrFirstname = $dataArray[$i][6];
       $usrEmail = $dataArray[$i][7];
       $usrPhone = $dataArray[$i][8];
       $adStreet = $dataArray[$i][9];
       $cmpHsno = $dataArray[$i][10];
       $adZipcode = $dataArray[$i][11];
       $adCity = $dataArray[$i][12];
       $hqId = $dataArray[$i][13];
       $eid = $dataArray[$i][14];
       $cmpDpfChecksum = $dataArray[$i][15];
       $cmpAuthenticated = $dataArray[$i][16];
       $cmpVisible = $dataArray[$i][17];

       // Define type to be checked (needed in the following INCLUDE)
       $autoembargo = "1";
       $cmpDpfChecksum = "xxxx";  // Init checksum => Send ALL couriers to DPF provider
       $DPFTypeToBeChecked = "cr";

       echo "[" . $i . ".] => " . $cmpId;
 
       if ($cmpId != "") :

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


           // 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;

           // Handling according to the result   
           $statusMessage = "";
           if ($dfpErrCode == "0") :   
              if ($dfpMatchlevel == "0") :      
                 $statusMessage = getLngt("OK!");
                 updateStmt("company","cmp_id",$cmpId,array("cmp_dpf_state", "10", "cmp_dpf_datetime", $currentTime, "cmp_dpf_checksum", $newDpfChecksum));
              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;
                 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;
           echo " => " . $statusMessage;
       else :
           echo " NOP!";
       endif;
       
       $cmpId = "";
       
       echo "<br>";

   endfor;  // Loop all rows
endif;
?>
