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

include_once ("../include/mcglobal.inc.php");
// include_once ("../include/auth.inc.php");
// include_once ("../include/inc_calendar.inc.php");
// include_once ("../groupware/calendar.php");
// include_once ("../statistic/statistic_sql.inc.php");
// include_once ("../include/email/htmlMimeMail.php");
include_once ("../include/inc_parseXML.inc.php");
include_once ("../include/inc_APP.inc.php");
include_once ("../include/inc_WEB.inc.php");
// include_once ("../include/inc_customer.inc.php");

getLanguage(__FILE__);

getCurrentScript(__FILE__);



// ***********************
// *** Initialisations ***
// ***********************



// $messageReqRawData = file_get_contents('php://input');
getSecHttpVars("1", array("data"));
$messageReq = $data;
// $messageReq = mcDecode($messageReq);

$currentTime = getDateTime("0");
$currentClientIP = trim($_SERVER['REMOTE_ADDR']);
writeToFile("../log/mobile.log", $currentTime . " | " . $currentClientIP);
// writeToFile("../log/mobile.log", $messageReqRawData);
writeToFile("../log/mobile.log", $messageReq);
writeToFile("../log/mobile.log", "-------------------------------------------------------------------------------------------");

// Check for POST raw data
$functionName   = getSingleTagContent($messageReq, "<id>", "</id>");
$moId           = getSingleTagContent($messageReq, "<moid>", "</moid>");
$cmpComp        = getSingleTagContent($messageReq, "<company>", "</company>");
$userName       = getSingleTagContent($messageReq, "<username>", "</username>");
$userFirstname  = getSingleTagContent($messageReq, "<userfirstname>", "</userfirstname>");
$userEmail      = getSingleTagContent($messageReq, "<useremail>", "</useremail>");
$userMobile     = getSingleTagContent($messageReq, "<usermobile>", "</usermobile>");
$userAccount    = getSingleTagContent($messageReq, "<account>", "</account>");
$userPassword   = getSingleTagContent($messageReq, "<password>", "</password>");
$userSession    = getSingleTagContent($messageReq, "<session>", "</session>");
$appKey         = getSingleTagContent($messageReq, "<app_key>", "</app_key>");
$appId          = getSingleTagContent($messageReq, "<app_id>", "</app_id>");
$usrId          = getSingleTagContent($messageReq, "<usrid>", "</usrid>");
$hq_id          = getSingleTagContent($messageReq, "<hqid>", "</hqid>");

// ---------------------------------------------
// Proprietärer Kram !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
$ttEvent        = getSingleTagContent($messageReq, "<tt_event>", "</tt_event>");
$ttTimestamp    = getSingleTagContent($messageReq, "<tt_timestamp>", "</tt_timestamp>");
$gpsLong        = getSingleTagContent($messageReq, "<gps_long>", "</gps_long>");
$gpsLat         = getSingleTagContent($messageReq, "<gps_lat>", "</gps_lat>");
// ---------------------------------------------

// Decode
$search = mcDecode($search);
$userName = mcDecode($userName);
$userPassword = mcDecode($userPassword);
$appKey = mcDecode($appKey);

/*
$functionName = "appRegister";
$appKey = "AAAAAAAAAA";
$appId = "1";
*/
/*
$functionName = "login";
$moId = "6";
$usrId = "18086";
$appKey = "AAAAAAAAAA";
$appId = "1";
*/

/*
$functionName = "setTimekeepingEvent";
$userSession = "495f2fdc997fe9da827107e64218434d";
$moId = "6";
$usrId = "18086";
$ttEvent = "1";
$ttTimestamp = "2014-01-01 10:00:00";
$gpsLong = "53.000001";
$gpsLat = "9.000001";
*/


// ---------------------------------------------
// *****************
// * TIME TRACKING *
// *****************

function setTimetrackingEvent ($moId, $usrId, $ttEvent, $ttTimestamp, $gpsLong, $gpsLat, $description) {
	global $dbname, $dblogin, $dbpassword;

  // Get operational IP and port from $moId
  if ($moId != "" && $usrId != "" && $ttEvent != "") :

     // Get operational database instance via metaobject
     $moValue = getOperationalDatabase($moId);

     if ($moValue != "") :
        if ($ttTimestamp == "") : $ttTimestamp = getDateTime("0"); endif;

        // Set operational database and insert event
        $db_op_conn = getDbConnectionSpecial($moValue, $dbname, $dblogin, $dbpassword);

        $sqlStmt = "INSERT INTO phoenix_group.timetracking (tt_datetime,tt_id,usr_id,tt_gps_long,tt_gps_lat,tt_description)" .
                          " VALUES ('" . $ttTimestamp . "','" . $ttEvent . "','" . $usrId . "','" . $gpsLong . "','" . $gpsLat . "','" . $description . "')";

        $res = $db_op_conn->query($sqlStmt);
        if (DB::isError($res)) : die ("$PHP_SELF: " . $res->getMessage()); endif;
        
        $retArray = array("0");
     else:
        $retArray = array("802","<err_no>802</err_no>\n","<err_desc>" . getLngt("Operational database cannot be connected!") . "</err_desc>\n");
     endif;
  else:
     $retArray = array("801","<err_no>801</err_no>\n","<err_desc>" . getLngt("Request has emty items!") . "</err_desc>\n");
  endif;
  return $retArray;
}

// For compatibility only
function setTimekeepingEvent ($moId, $usrId, $ttEvent, $ttTimestamp, $gpsLong, $gpsLat, $description) {
  return setTimetrackingEvent ($moId, $usrId, $ttEvent, $ttTimestamp, $gpsLong, $gpsLat, $description);
}

function getLastTimetrackingEvent ($moId, $usrId) {
	global $dbname, $dblogin, $dbpassword;

  // Get operational IP and port from $moId
  if ($moId != "" && $usrId != "") :

     // Get operational database instance via metaobject
     $moValue = getOperationalDatabase($moId);

     if ($moValue != "") :

        // Set operational database and insert event
        $db_op_conn = getDbConnectionSpecial($moValue, $dbname, $dblogin, $dbpassword);

        $tmpSqlQuery = "SELECT tt_datetime, tt_id, tt_gps_long, tt_gps_lat, tt_description FROM phoenix_group.timetracking WHERE usr_id = '" . $usrId . "' ORDER BY tt_datetime DESC LIMIT 0,1";
        $result = $db_op_conn->query($tmpSqlQuery);
        while ($row = $result->fetch_assoc()):
              $retArray = array("0", $row["tt_datetime"], $row["tt_id"], $row["tt_gps_long"], $row["tt_gps_lat"], $row["tt_description"]);
        endwhile;
        $result->free();
     else:
        $retArray = array("802","<err_no>802</err_no>\n","<err_desc>" . getLngt("Operational database cannot be connected!") . "</err_desc>\n");
     endif;
  else:
     $retArray = array("801","<err_no>801</err_no>\n","<err_desc>" . getLngt("Request has emty items!") . "</err_desc>\n");
  endif;
  return $retArray;
}
// ---------------------------------------------



// ------------------------------------------------------------------------------------------------------     


// **************
// * XML Output *
// **************

$retVal = "";
$xmlOut = "";
$xmlNoErrOut .= "<err_no>0</err_no>\n<err_desc>OK</err_desc>\n";
$xmlErrOut .= "<err_no>100</err_no>\n<err_desc>Currently not implemented.</err_desc>\n";

if ($functionName == "appRegister" || $functionName == "webRegister" || $functionName == "login" || checkAccess($userSession, $moId, $usrId)) :

   if ($transactionHandle != "") :
      // $xmlOut .= "<transaction_no>" . $transaction_no . "</transaction_no>\n";
   endif;

   $xmlOut .= "<data>\n";

   if ($functionName != "") :
      if (function_exists($functionName)) :
   
         if ($functionName == "appRegister") :
            $retVal = call_user_func_array($functionName, array($appKey, $appId));   // Register APP and get mo_id, usr_id and hq_id for response
   
            if ($retVal[0] != "0") :
               $xmlOut .= $retVal[1] . $retVal[2];
            else :
               $xmlOut .= $xmlNoErrOut;
               $xmlOut .= "<moid>" . $retVal[2] . "</moid>\n";
               $xmlOut .= "<usrid>" . $retVal[1] . "</usrid>\n";
            endif;
            
         elseif ($functionName == "webRegister") :
            $retVal = call_user_func_array($functionName, array($cmpComp, $userName, $userFirstname, $userEmail, $userMobile, $userAccount, $userPassword));   // Register WEB, generate mandator

            if ($retVal[0] != "0") :
               $xmlOut .= $retVal[1] . $retVal[2];
            else :
               $xmlOut .= $xmlNoErrOut;
               $xmlOut .= "<moid>" . $retVal[2] . "</moid>\n";
               $xmlOut .= "<usrid>" . $retVal[1] . "</usrid>\n";
            endif;

         elseif ($functionName == "login") :
            $retVal = call_user_func_array($functionName, array($moId, $usrId, $appKey, $appId));   // Check requested user and APP data
   
            if ($retVal[0] != "0") :
               $xmlOut .= $retVal[1] . $retVal[2];
            else :
               $xmlOut .= $xmlNoErrOut;
   
               $xmlOut .= "<session>" . $retVal[4] . "</session>\n";
               $xmlOut .= "<moid>" . $retVal[3] . "</moid>\n";
               $xmlOut .= "<hqid>" . $retVal[2] . "</hqid>\n";
               $xmlOut .= "<hqname><![CDATA[" . mcEncode($retVal[7]) . "]]></hqname>\n";
               $xmlOut .= "<hqmnemonic>" . $retVal[8] . "</hqmnemonic>\n";
               $xmlOut .= "<usrid>" . $retVal[1] . "</usrid>\n";
               $xmlOut .= "<usrrealname><![CDATA[" . mcEncode($retVal[5]) . "]]></usrrealname>\n";
               $xmlOut .= "<usrrealfirstname><![CDATA[" . mcEncode($retVal[6]) . "]]></usrrealfirstname>\n";
            endif;


// -------------------------------------------
// To be put in external script or so.... !!!!

         elseif ($functionName == "setTimekeepingEvent" || $functionName == "setTimetrackingEvent") :
            $retVal = call_user_func_array($functionName, array($moId, $usrId, $ttEvent, $ttTimestamp, $gpsLong, $gpsLat, ""));   // Set timetracking event
   
            if ($retVal[0] != "0") :
               $xmlOut .= $retVal[1] . $retVal[2];
            else :
               $xmlOut .= $xmlNoErrOut;
   
               // $xmlOut .= "<session>" . $retVal[4] . "</session>\n";
            endif;

         elseif ($functionName == "getLastTimetrackingEvent") :
            $retVal = call_user_func_array($functionName, array($moId, $usrId));   // Get last timetracking event
   
            if ($retVal[0] != "0") :
               $xmlOut .= $retVal[1] . $retVal[2];
            else :
               $xmlOut .= $xmlNoErrOut;
   
               $xmlOut .= "<tt_datetime>" . $retVal[1] . "</tt_datetime>\n";
               $xmlOut .= "<tt_event>" . $retVal[2] . "</tt_event>\n";
               $xmlOut .= "<gps_long>" . $retVal[3] . "</gps_long>\n";
               $xmlOut .= "<gps_lat>" . $retVal[4] . "</gps_lat>\n";
               $xmlOut .= "<description><![CDATA[" . mcEncode($retVal[5]) . "]]></description>\n";
            endif;

         else :
            // Call corresponding script according to the APP ID
            // ....

            // $xmlOut .= "<err_no>103</err_no>\n";
            // $xmlOut .= "<err_desc>Function does not exist in API.</err_desc>\n";
         endif;
      else :
         $xmlOut .= "<err_no>102</err_no>\n";
         $xmlOut .= "<err_desc>Specified function does not exist.</err_desc>\n";
      endif;
   else :
      $xmlOut .= "<err_no>101</err_no>\n";
      $xmlOut .= "<err_desc>No function specified.</err_desc>\n";
   endif;

   $xmlOut .= "</data>\n";
else :
   $xmlOut .= $xmlErrOut;
endif;

echo $xmlOut;


/*
https://212.79.60.73/htm/mobile/accessMobileXML.php



[A] Registrierung und Mandantenanlage über das WEB

....
<id>webRegister</id>
<company>Firma</company>
<username>Nachname</username>
<userfirstname>Vorname</userfirstname>
<useremail>Mailadresse</useremail>
<usermobile>Mobilnummer</usermobile>
<account>Nachname</account>
<password>Passwort</password>
....



[B] Ablaufschritte für die Einzelregistrierung der APP:


1. Schritt:
Die Registrierungsanfrage der "frischen" oder manuell deaktivierten APP sendet den eingegebenen Registrierungscode an den Server.
Die APP-ID ist für die Zeiterfassungs-APP immer "1".
Das XML-Rahmenformat ist dasselbe wie bei der Vertriebs-APP.

Request-Bsp.
....
<id>appRegister</id>
<app_key>Rc34rFghZ78tx</app_key>   // Registrierungscode
<app_id>1</app_id>                 // ID der APP
....

Response-Bsp.
....
<err_no>0</err_no>   // Verifikation Registrierungscode ok, wenn = "0"
<moid>6</moid>       // Interne Nummer der Datenbank-Instanz, auf die der Server zugreifen muss (z.B "8")
<usrid>23</usrid>    // Eindeutige ID des Benutzers der korrespondierenden DB-Instanz
....


2. Schritt:

Nach der erfolgreichen Registrierung erfolgt ein sich anschließender Login-Prozess.

Request-Bsp.
....
<id>login</id>
<moid>6</moid>                     // Instanz der DB, auf die zugegriffen werden muss
<usrid>23</usrid>                  // Benutzer-ID
<app_key>Rc34rFghZ78tx</app_key>   // Registrierungscode (wird auch wieder mitgegeben zum Abgleich ob serverseitig zurückgesetzt)
<app_id>1</app_id>                 // ID der APP (wird mitgeführt wg. Check des Registrierungscodes)
....

Response-Bsp.
....
<err_no>0</err_no>   // Login ok, wenn = "0"
<session>....hash....</session>
<moid>6</moid>
<hqid>....</hqid>
<hqname><![CDATA[....]]></hqname>
<hqmnemonic>....</hqmnemonic>
<usrid>23</usrid>
<usrrealname><![CDATA[....]]></usrrealname>
<usrrealfirstname><![CDATA[....]]></usrrealfirstname>
....


3. Schritt:

Request für operative Daten. Senden des Events mit Koordinaten

Request-Bsp.
....
<id>setTimekeepingEvent</id>
<session>....hash....</session>
<moid>6</moid>
<usrid>23</usrid>
<tk_event>1</tk_event>          // "1" = User fängt (wieder) zu arbeiten an | "2" = Pause oder Feierabend
<gps_long>9.9876</gps_long>     // Notation mit "."
<gps_lat>53.123</gps_lat>       // Notation mit "."
....

Response-Bsp.
....
<err_no>0</err_no>   // Operation ok, wenn = "0"
....

*/
?>
