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

include_once ("../include/mcglobal.inc.php");
include_once ("../include/auth.inc.php");
include_once ("../include/ranking.inc.php");
include_once ("../include/pnpoly.inc.php");


// Check HTTP-Parameters
getSecHttpVars("1",array("f_act", "customerId", "cscIdRoot", "cscIdActual", "f_cr_sid", "useRemoteDB"));


// Check for authentication access and granted rights
$usrAccessArray["hq"] = "1";
authCheckForAccess($hq_id, $usr_id, $emp_id, "1", $customerId, $cscIdRoot, $cscIdActual);
authCheckEmployeeRights($emp_id, "4", "1");

// ******************************************************
// Very special treatment for access to remote database
include_once ("../include/bwv.inc.php");
$remoteDBisActive = false;
if (BWV2_checkEmpRemoteDBAccess($useRemoteDB, $emp_id)) :
   $remoteDBisActive = BWV2_setRemoteDBAccessParameter();
endif;
// ******************************************************

/*
FLOW:
- General definitions
- Get courier-id from http-request
- Search MSISDN from courier-id
- Generate request
- Send request
- Parse response
- Search x,y-coordinates in cells to be valid
- Compute longitude and latitude (transformation)
- Get zipcode from coordinates
- Update zipcode of the courier
- Write to log-file|log-db (employee, datetime, courier-id, msisdn, [zipcode, x_y_of_cell])
- Output zipcode
*/


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

// Proxy und Port fuer HTTPS
$proxy = "";
$port = ":443";    // Remember ":" in HTTP-Header ... $server:$port

// Server innerhalb der Nachricht
// $server = '10.10.1.244';   // E-Plus
// $server = "193.254.134.115";    // D1 - develop
$server = "193.254.161.68";     // D1 - live (https://crisp.t-mobile.de/cgi-bin/vasp.sh)

// Access to a special remote file
$file = "cgi-bin/vasp.sh";

// Request id
// $requestID = "1";
$requestID = rand(1,30000);

// User and password
// $vaspID = "600";
// $password = "mi6t890";
$vaspID = "65";
$password = "Alpha_2405";

// Service ID
$serviceId = "160";

// Maximum of age of locating info
$maxAgeOfLocatingInfoInSeconds = "300";

// Minimum of the granularity
$minOfGranularityInMeter = "99999";

// Client Certificate and Private Key
// $clientcertkey = '-cert ./client-cert-tc/cert.pem -key ./client-cert-tc/key.pem';
$clientcertkey = '-cert cacert.pem -key privkey.pem';

// Path to openssl
// $openssl = 'F:/Install/Security/OpenSSL/openssl';
$openssl = 'openssl';

// Port of openssl
$opensslPort = "9213";

// Only for output
$status_message = "";

// Logging enabled
$loggingEnabled = FALSE;

// Echo enabled
$echoEnabled = FALSE;


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

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

function openSSL_connect($opensslPort, $completeReq) {
   $response = "";
   $fp = fsockopen ("127.0.0.1", $opensslPort, $errno, $errstr, 10);
   if (!$fp) {
       $response = "$errstr ($errno)<br>\n";
   } else {
       fputs ($fp, $completeReq);
       fflush($fp);
       
       // Read header
       $httpHeader = "";
       $httpBodyLength = 0;
       if (!feof($fp)) :
          $line = trim(fgets ($fp,1024));
          $httpHeader .= trim(fgets ($fp,1024));
          while (!feof($fp) && $line != "") {
       	     $line = trim(fgets ($fp,1024));
       	     $httpHeader .= $line;
       	     if (!(strpos($line, "Content-length: ") === FALSE)) :
       	        $httpBodyLength = trim(substr($line, 16));
       	     endif;
          }
       endif;
       if ($httpBodyLength > 0) :
          $response .= fgets ($fp, $httpBodyLength + 1);
       endif;
       
       // while (!feof($fp)) {
       //    $response .= fgets ($fp,1024);
       // }
       
       fclose ($fp);
   }
   return $response;
}


// *********************************
// * Search MSISDN from courier-id *
// *********************************

// Get courier-id from the courier-sid (e.g. SIDs: 1013, 1019, etc.)
$cr_id = getFieldValueFromId("courier","cr_sid",$f_cr_sid,"cr_id");
$msisdn = getFieldValueFromId("courier","cr_id",$cr_id,"cr_mobile_pda");


// Remove blanks in MSISDN and check beginning with "49" 
// (IMPORTANT: No check for other chars because checked in javascript !!!)
$msisdn = ereg_replace (" ", "", $msisdn);
$msisdn = str_replace("+", "", $msisdn);
if (!ereg("^" . COUNTRY_FON_PREFIX, $msisdn)) : 
   if (ereg("^0", $msisdn)) :
      $msisdn = substr($msisdn, 1);
   endif;
   $msisdn = COUNTRY_FON_PREFIX . $msisdn;
endif;

// Test-MSISDN D1:
// $msisdn = "491703900198";


// ********************
// * Generate request *
// ********************

/*
TEMPLATES:

Connection Setup
request:
<MESSAGE_TYPE=1><REQUEST_ID=1><VASP_ID=500><PASSWORD=testtest>
response:
<MESSAGE_TYPE=2><REQUEST_ID=1><SESSION_HANDLE=2876><STATUS=0><GMT_DIFFERENCE=2>

Location (n-mal)
request:
<MESSAGE_TYPE=10><REQUEST_ID=1><SESSION_HANDLE=2876><SERVICE_ID=160><MAX_INFO_AGE=6000><MIN_GRANULARITY=2000><MOBILE_ID_TYPE=0><MOBILE_ID=4917112345467><TEXT=48656C6C6F><REQUEST_TIME=20010719102200><GMT_DIFFERENCE=2>
response:
<MESSAGE_TYPE=11><REQUEST_ID=1><SESSION_HANDLE=2876><TIMESTAMP=20010719102321><GEO_REF_SYSTEM=0><POSITION_FORMAT=2><MOBILE_ID_TYPE=0><<MOBILE_ID=491711234567><MOBILE_POSITION=<POSITION_FORMAT=CIRCLE;CENTER=555555,133333;RADIUS=646>><MOBILE_AGE_OF_INFO=-2744><MOBILE_STATUS=0>>

Connection Release
request:
<MESSAGE_TYPE=3><REQUEST_ID=1><SESSION_HANDLE=2876>
response:
<MESSAGE_TYPE=4><REQUEST_ID=1><SESSION_HANDLE=2876><STATUS=0>

error response:
<MESSAGE_TYPE=13><REQUEST_ID=1><SESSION_HANDLE=2876><STATUS=40>
*/


// Define header request
$requestheaderOrg = "POST /" . $file . " HTTP/1.1\r\n" .
"Host: $server$port\r\n" .
"Content-Type: text/plain\r\n" .
"Content-length: LENGTH\r\n\r\n";


// Connection request
$requestConnectionSetup = "<MESSAGE_TYPE=1><REQUEST_ID=" . $requestID . "><VASP_ID=" . $vaspID . "><PASSWORD=" . $password . ">";

$laenge = strlen($requestConnectionSetup);

$requestheader = $requestheaderOrg;
$requestheader = str_replace ("LENGTH", $laenge, $requestheader);
if ($echoEnabled) : echo $requestheader . $requestConnectionSetup . "\n\n\n"; endif;

$response = openSSL_connect($opensslPort, $requestheader.$requestConnectionSetup."\r\n");
if ($echoEnabled) : echo $response . "\n\n\n"; endif;

if (!(strpos($response, "<MESSAGE_TYPE=13>") === FALSE)) :

   // Error occurred, no connection ...
   $status_message = "Die Verbindung konnte nicht hergestellt werden!";   
else :

   if ((strpos($response, "<MESSAGE_TYPE=2>") === FALSE)) :
   
      // Error occurred, no session handle delivered ...
      $status_message = "Es wurde kein Sessionhandle zurückgeliefert!";      
   else :
   
      // Get session handle from connection request
      $beginPos = strpos($response, "<SESSION_HANDLE=") + 16;
      $endPos = strpos($response, "><STATUS");
      $sessionHandle = substr($response, $beginPos, $endPos - $beginPos);
      if ($echoEnabled) : echo $sessionHandle . "\n\n\n"; endif;

      // Define locating request
      $requestID++;
      $requestLocating = "<MESSAGE_TYPE=10><REQUEST_ID=" . $requestID . ">" .
                         "<SESSION_HANDLE=" . $sessionHandle . ">" . 
                         "<SERVICE_ID=" . $serviceId . ">" .
                         "<MAX_INFO_AGE=" . $maxAgeOfLocatingInfoInSeconds . ">" .
                         "<MIN_GRANULARITY=" . $minOfGranularityInMeter . ">" .
                         "<MOBILE_ID_TYPE=0>" . 
                         "<MOBILE_ID=" . $msisdn . ">" .
                         "<REQUEST_TIME=" . getDateTime("year") . getDateTime("month") . getDateTime("day") . getDateTime("hour") . getDateTime("minute") . getDateTime("second") . ">" .
                         "<GMT_DIFFERENCE=2>";

      $laenge = strlen($requestLocating);
      $requestheader = $requestheaderOrg;
      $requestheader = str_replace ("LENGTH", $laenge, $requestheader);
      if ($echoEnabled) : echo $requestheader.$requestLocating . "\n\n\n"; endif;

      // Locating request
      $response = openSSL_connect($opensslPort, $requestheader.$requestLocating."\r\n");
      if ($echoEnabled) : echo $response . "\n\n\n"; endif;

      if (!(strpos($response, "<MESSAGE_TYPE=13>") === FALSE)) :

         $status_message = "Bei der Lokalisierung trat ein Fehler auf!";
      else :

         if ((strpos($response, "<MESSAGE_TYPE=11>") === FALSE)) :

            $status_message = "Die Lokalisierung war nicht möglich!";
         else :

            // GET LOCATING INFOS OF THE RESPONSE
           
            // Get session handle from connection request
            $beginPos = strpos($response, "<POSITION_FORMAT=CIRCLE;CENTER=") + 31;
            $endPos = strpos($response, ";RADIUS");
            $coordPair = substr($response, $beginPos, $endPos - $beginPos);
            if ($echoEnabled) : echo "CoordPair: " . $coordPair . "<br>"; endif;

            $beginPos = strpos($response, "RADIUS=") + 7;
            $endPos = strpos($response, ";>><MOBILE_AGE");
            $radius = substr($response, $beginPos, $endPos - $beginPos);
            if ($echoEnabled) : echo "Radius: " . $radius . "<br>"; endif;

            $coordPairArray = spliti(",",$coordPair);

            // Transform data
            // Example: $coordPair = "555555,133333"
            //          $coordPairArray[0] = "555555" | $coordPairArray[0] = "133333"
            //          $x_coord_array[0] = "55" (Stellen 0 und 1) | $x_coord_array[1] = "55" (Stellen 2 und 3) | $x_coord_array[2] = "55" (Stellen 4 und 5)
            //          $y_coord_array[0] = "13" (Stellen 0 und 1) | $y_coord_array[1] = "33" (Stellen 2 und 3) | $y_coord_array[2] = "33" (Stellen 4 und 5)

            $x_coord_array = array();
            $x_coord_array[0] = substr($coordPairArray[0], 0, 2);
            $x_coord_array[1] = substr($coordPairArray[0], 2, 2);
            $x_coord_array[2] = substr($coordPairArray[0], 4);
            
            $y_coord_array = array();
            $y_coord_array[0] = substr($coordPairArray[1], 0, 2);
            $y_coord_array[1] = substr($coordPairArray[1], 2, 2);
            $y_coord_array[2] = substr($coordPairArray[1], 4);


            // ***************************************************
            // * Compute longitude and latitude (transformation) *
            // ***************************************************        

            $longitude = $y_coord_array[ 0 ] + $y_coord_array[ 1 ] /60 + $y_coord_array[ 2 ] / 3600;
            $latitude = $x_coord_array[ 0 ] + $x_coord_array[ 1 ] / 60 + $x_coord_array[ 2 ] / 3600;


            // ********************************
            // * Get zipcode from coordinates *
            // ********************************
      
            if (LOCATING_MODE == "0") :
            
               $zipcode = findZipcodeArea($longitude, $latitude);
            else :
            
               // Get nearest coordinates
               $sqlquery = "SELECT srvp.srvp_id, srvp.srvp_plz, srvp.srvp_latitude, srvp.srvp_longitude, "
                           .      "SQRT(POW(ABS(srvp.srvp_latitude - $latitude),2) + POW(ABS(srvp.srvp_longitude - $longitude),2)) AS nb"
                           . " FROM serviceplz AS srvp"
                           . " ORDER BY nb"
                           . " LIMIT 0,1";
      
               $result = $db->query($sqlquery);
               if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
               // all defined db-fields an titles shall become content of the following arrays
               while ($row = $result->fetch_assoc()):   
                  $f_srvp_plz		= $row["srvp_plz"];         // Zipcode to be displayed
               endwhile;
               $result->free();    
            
               $zipcode = $f_srvp_plz;
            endif;
                        
            $status_message = "<b>REALER Standort-PLZ des Kuriers: " . $zipcode . "</b>" . "   (" . $longitude . " / " . $latitude . ")<br><br>";
      

            // *********************************
            // * Update zipcode of the courier *
            // *********************************

            $updateRankingTime = TRUE;
      
            // Get current zipcode of the courier out of the table "courier" (cr_locationzipcode) to compare with locating zipcode
            $crLocationZipcode = getFieldValueFromId("courier","cr_id",$cr_id,"cr_locationzipcode");
      
            $status_message .= "<b>(Freimeldung des Kuriers: " . $crLocationZipcode . ")</b><br><br>";
      
            if ($zipcode != "" && $crLocationZipcode != "" && is_numeric($crLocationZipcode)) :
      
               // Check current zipcode with locating zipcode
               if ($zipcode == $crLocationZipcode) :
      
                  $updateRankingTime = FALSE;
               else :
                  // Check locating zipcode is in neighbourhood
                  // If true then ok => do not update ranking time
      
                  // Get the general mediation mode for the headquarter
                  $mediationMode = MODE_INTERMEDIATION;
                  if ($mediationMode == "") :
                     $mediationMode = getFieldValueFromId("headquarters", "hq_id", "$hq_id", "hq_invmode");
                  endif;
      
                  // Get all neighbours for the current zipcode(area)
                  if ($mediationMode == "1") :
                     $zicodeArray = getCourierByRanking($crLocationZipcode, "0000010000", "", "");
                     $zicodeArray = $zicodeArray[5];
                  else :
                     $areaIdArray = getCourierByRanking($crLocationZipcode, "0000010000", "", "");
                     $areaIdArray = $areaIdArray[5];

                     // Add ID of the main mediation area
                     $srvpIdZipcode = getFieldValueFromId("serviceplz","srvp_plz",$crLocationZipcode,"srvp_id");
                     // $srvpaIdMain = getFieldValueFromId("serviceplzareamapping","srvp_id",$srvpIdZipcode,"srvpa_id");
                     $srvpaIdMain = $db->getOne("SELECT srvpam.srvpa_id FROM serviceplzarea AS srvpa, serviceplzareamapping AS srvpam" .
                                                "  WHERE srvpam.srvp_id = '" . $srvpIdZipcode . "' AND srvpa.srvpa_id = srvpam.srvpa_id AND srvpa.hq_id = '" . $hq_id . "'");

                     if ($areaIdArray == "") : $areaIdArray = array(); endif;
                     array_push($areaIdArray, $srvpaIdMain);
                     
                     $areaIdArrayLen = count($areaIdArray);
      
                     $outputOfAllValidMainZipcodes = "<b>GÜLTIGE BEREICHE:</b><br>";
                     $outputOfAllValidMainZipcodes .= "_________________ <br><br>";
                     $outputOfAllValidMainZipcodes .= "<b>Hauptbereich:</b><br>";
                     
                     $outputOfAllValidNeighbourZipcodes = "";
                     
      
                     $zicodeArray = array();
                     for ($i = 0; $i < $areaIdArrayLen; $i++) :

                         if ($i < $areaIdArrayLen - 1) :
      		                  $outputOfAllValidNeighbourZipcodes .= "<b>Nachbarbereich " . ($i + 1) . "</b><br>";
      		               endif;

      		               $sqlquery = "SELECT srvp.srvp_plz"
      		                         . " FROM serviceplzareamapping AS srvpam, serviceplz AS srvp"
      		                         . " WHERE srvpam.srvp_id = srvp.srvp_id AND srvpam.srvpa_id = '" . $areaIdArray[$i] . "'";
                         
      		               $result = $db->query($sqlquery);
      		               if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
      		                                        
                            while ($row = $result->fetch_assoc()):
      		                  $zicodeArray[] = $row[srvp_plz];
                                     
                            if ($i < $areaIdArrayLen - 1) :
      		                     $outputOfAllValidNeighbourZipcodes .= $row[srvp_plz] . "<br>";
      		                  else :
      		                     $outputOfAllValidMainZipcodes .= $row[srvp_plz] . "<br>";
      		                  endif;
      		               endwhile;

      		               $result->free();

                         if ($i < $areaIdArrayLen - 1) :
      		                  $outputOfAllValidNeighbourZipcodes .= "----------------- <br><br>";
      		               else :
      		                  $outputOfAllValidMainZipcodes .= "----------------- <br><br>";
      		               endif;
                     endfor;
                     $outputOfAllValidZipcodes = $outputOfAllValidMainZipcodes . $outputOfAllValidNeighbourZipcodes;
                  endif;
      
                  $zicodeArrayLen = count($zicodeArray);
                  for ($i = 0; $i < $zicodeArrayLen; $i++) :
                      if ($zipcode == $zicodeArray[$i]) :
                         $updateRankingTime = FALSE;
                      endif;
                  endfor;
               endif;
      
               $currentTime = getDateTime("0");
               if ($updateRankingTime) :
                  updateStmt("courier", "cr_id", $cr_id, array("cr_locationzipcode", $zipcode, "cr_availabletime", $currentTime));
                  $status_message .= "Die Rankingposition ging verloren! <br><br>";
               else :
                  // updateStmt("courier", "cr_id", $cr_id, array("cr_locationzipcode", $zipcode));
                  $status_message .= "Die Rankingposition bleibt erhalten! <br><br>";
               endif;
            else :
               $currentTime = getDateTime("0");
            endif;
            
            // Update current position to courier with timestamp
            if ($longitude != "" && $latitude != "" && 
                substr($longitude , 0, 1) != "0" && substr($latitude , 0, 1) != "0" &&
                is_numeric($longitude) && is_numeric($latitude)) :
                
               updateStmt("courier", "cr_id", $cr_id, array("cr_gps_long", $longitude, "cr_gps_lat", $latitude, "cr_gps_time", $currentTime));
            endif;


            // ***********
            // * LOGGING *
            // ***********
            
            // Get usr_id of the current employee (session)
            $currentSessionUsrId = getFieldValueFromId("employee", "emp_id", $emp_id, "usr_id");
      
            // Loose Ranking yes/no
            $looseRanking = "NO";
            if ($updateRankingTime) : $looseRanking = "YES"; endif;
      
            // Write logdata into log database
            writeToLogDB("27",$hq_id,"0",$currentSessionUsrId,$cr_id,$f_cr_sid,"","LONG=".$longitude."|LAT=".$latitude."|ZIP_REAL=".$zipcode."|ZIP_FREE=".$crLocationZipcode."|NO=".$msisdn."|LRANK=".$looseRanking);


            // ********************
            // * Close connection *
            // ********************
            
            $requestID++;
            $requestConnectionRelease = "<MESSAGE_TYPE=3><REQUEST_ID=" . $requestID . "><SESSION_HANDLE=" . $sessionHandle . ">";
            
            $laenge = strlen($requestConnectionRelease);
            $requestheader = $requestheaderOrg;
            $requestheader = str_replace ("LENGTH", $laenge, $requestheader);
            if ($echoEnabled) : echo $requestheader.$requestConnectionRelease . "<br><br><br>"; endif;

            // Connect Release
            $response = openSSL_connect($opensslPort, $requestheader.$requestConnectionRelease."\r\n");
            
         endif;
      endif;
   endif;
endif;
?>


<html lang="de">

<head>
<title>ORTUNG</title>
<link rel="stylesheet" type="text/css" href="../css/phoenix.css"> 
</head>


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

  <form action="../locating/locating_tmobile.php" method="post">
  <input type="hidden" name="f_cr_sid" value="<?php echo $f_cr_sid ?>">
  <input type="hidden" name="useRemoteDB" value="<?php echo $useRemoteDB ?>">

  <div valign="center" align="center">  
    <table cellspacing="0" cellpadding="0" vspace="0" hspace="0">	  	  	  	  	  
	 <tr>
          <td align="center" valign="center">
            <b>Kurier-SID: <?php echo $f_cr_sid?></b><br><br>
            MSISDN: <?php echo $msisdn?><br><br>
            <br><br><br>
            <input type="submit" value="Wiederholen">
            <br><br>
	    <input type="button" value="Schließen" onClick="javascript:window.close();">
	    <br><br><br><br><br>
	    <?php echo $status_message ?>
	    <br><br><br><br><br>
	    <?php echo $outputOfAllValidZipcodes ?>	    
	  </td>
	</tr>
    </table>
  </div>

  </form>

</body>

</html>
