<?php

include_once ("mc_gen_include.inc.php");
include_once ("htmlMimeMail.php");
require_once "DB.php";

// Get absolute system path (e.g. "/data0/srv/www/htsdocs/xxxx")
function getAbsoluteSystemPath () {
  $dirName = dirname(__FILE__);     
  $dirName = str_replace("\\", "/", $dirName);
  $lastSlashPos = strrpos($dirName,"/");
  $path = substr($dirName, 0, $lastSlashPos);
  return $path;
}

// Triggers the script for sending an internal mail
function sendInternalMail ($errMsg) {
	if ($errMsg != "") :
	   $path = getAbsoluteSystemPath();
     $result = "";
     // $cmd = "php " . $path . "/include/automailer_internal.php comegetsome97531 " . $errMsg . " &";
     $cmd = "php automailer_internal.php comegetsome97531 \"" . $errMsg . "\" &";
     exec($cmd . " > /dev/null &");
  endif;
}

// *****************************************************************************
// Current timestamp
$currentTime = date("Y-m-d H:i:s");
$currentDateYesterday = getDateTime("date_plus_offset", array(0,-1,0), $formatStr = "Y-m-d");

// Define start time for b2b_object only !!!!
$constAmStarttimeInDays = 30;
$startTime = getDateTime("datetime_plus_offset", array(0,0,0,0,-($constAmStarttimeInDays),0), "Y-m-d") . " 00:00:00";
$whereClauseStarttime = " bo_createtime >= '" . $startTime . "' AND ";

getSecHttpVars("0", array("filedata", "filename", "metadata"));

writeToFile("uploader_post.log", "[" . $currentTime . " | " . trim($_SERVER['REMOTE_ADDR']) . "]\n" . var_export($HTTP_POST_VARS, true) . "\n");
writeToFile("uploader_post_raw.log", "[" . $currentTime . " | " . trim($_SERVER['REMOTE_ADDR']) . "]\n" . file_get_contents("php://input") . "\n");

// DB-Config
$dbhost = "172.16.0.111:3711";  // EXTERNAL_DB_METAOBJECT
$dblogin = "phoenix";
$dbpassword = "AdAdgkS13";
$dbname = "phoenix";
$dsn = "mysql://$dblogin:$dbpassword@$dbhost/$dbname";
$db = DB::connect($dsn, false);

if (mysql_errno())
  writeToFile("upload.log", "DB-Error:" . " | " . $currentTime . " | " . date("Y-m-d H:i:s") . " | " . trim($_SERVER['REMOTE_ADDR']) . " | " . $filename . mysql_error());    

if (DB::isError($db))
    die ("$PHP_SELF: " . $db->getMessage());

$db->setFetchMode(DB_FETCHMODE_ASSOC);
$db->query('SET NAMES latin1');

// calling client IP
$currentClientIP = trim($_SERVER['REMOTE_ADDR']);

$opState = "OK";
$filename = trim($filename);

$semaphorKey = "automailer";
$semaphorLiveTime = 120;

// 30.08.2016 CA: "Filename empty" and "No file data" shall be ignored from now on because those data will never ever be sent correctly
if ($filename == "")
  $filename = trim($_SERVER['REMOTE_ADDR']) . "_" . date("YmdHis") . ".jpg";
if ($filedata == "")
  $filedata = "No file data";

if ($currentClientIP != "") :
   if ($filename != "") :   
      if ($filedata != "") :

         // Set and check upload counter for AMOK mail
         if ($currentClientIP != "" && $filename != "") :
            if (!existsEntry("temp.app_upload",array("appu_ip",$currentClientIP,"appu_file",$filename))) :
               insertStmt("temp.app_upload", array("appu_ip", $currentClientIP, "appu_file", $filename, "appu_cnt", "1"));
            else :
               $cnt = getFieldValueFromClause("temp.app_upload","appu_cnt","appu_ip = '" . $currentClientIP . "' AND appu_file = '" . $filename . "'");
               $cnt++;
               updateStmt("temp.app_upload","appu_ip",$currentClientIP,array("appu_cnt",$cnt),"appu_file = '" . $filename . "'");
            endif;

            $cnt = getFieldValueFromClause("temp.app_upload","appu_cnt","appu_ip = '" . $currentClientIP . "' AND appu_file = '" . $filename . "'");
            if ($cnt == "") : $cnt = "0"; endif;
            if (($cnt % 10) == 0) : 
               sendInternalMail("AMOK-FILE " . $filename . " [" . $currentClientIP . "] UPLOAD-COUNTER: " . $cnt);
            endif;
         endif;

         // **** Write data into DB ****
         // Get external databases (e.g. APP properties, mobile data, etc.)
         $dbhostArray = getGlobalDbEnvironments();
         $dbhostArrayLen = count($dbhostArray);
         $dbConnectionArray = array();
         if ($dbhostArrayLen > 0) :
            $dbConnectionArray["app_property"] = getDbConnectionSpecial($dbhostArray["as_intern"], "sysadmin", $dblogin, $dbpassword);
            if ($dbConnectionArray["app_property"] != "") :

               $confPropRowMatched = false;

               // Get tr_id from "metadata"
               // <metadata><context>pp</context><type>jpg</type><cust>moebel_live</cust><jb_id>380311</jb_id></metadata>
               // <metadata><context>ap</context><type>jpg</type><cust>htm</cust><jb_id>380311</jb_id></metadata>
               // <metadata><context>lda</context><acc>HB105</acc><sess_key>77638762387464942387498723</sess_key><comm>77747888</comm></metadata>
               // <metadata><context>tour</context><jb_id>....</jb_id><tr_id>....</tr_id></metadata> 
               
               $xmlContext = getSingleTagContent($metadata, "<context>", "</context>");

               $xmlType  = getSingleTagContent($metadata, "<type>", "</type>");
               // $xmlCust  = getSingleTagContent($metadata, "<cust>", "</cust>");
               $xmlJbId  = getSingleTagContent($metadata, "<jb_id>", "</jb_id>");
               $xmlTrId  = getSingleTagContent($metadata, "<tr_id>", "</tr_id>");

//               $debugMode = false;
//               $xmlDebug = getSingleTagContent($metadata, "<debug>", "</debug>");
//               if ($xmlDebug != "") :
                  $debugMode = true;
//               endif;

               if ($xmlContext == "lda") :
                  $xmlAcc = getSingleTagContent($metadata, "<acc>", "</acc>");
                  $xmlSessKey = getSingleTagContent($metadata, "<sess_key>", "</sess_key>");
                  $xmlComm = getSingleTagContent($metadata, "<comm>", "</comm>");
                  $xmlComm = trim($xmlComm);  // !!!!

                  $custId = getFieldValueFromId("temp.user_session","us_key", $xmlSessKey,"cust_id",$dbConnectionArray["app_property"]);
                  $usrId  = getFieldValueFromId("temp.user_session","us_key", $xmlSessKey,"usr_id",$dbConnectionArray["app_property"]);

                  $confPropRowMatched = true;  // No entry in conf_prop, because of LDA mode, but ok to proceed!
               else:
                  // Get cust_id, hq_id and usr_id from table conf_prop
                  $sqlquery = "SELECT cust_id, hq_id, usr_id FROM sysadmin.conf_prop WHERE prop_id = '1' AND cp_val = '" . $currentClientIP . "'";
                  $result = $dbConnectionArray["app_property"]->query($sqlquery);
                  if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
                  while ($row = $result->fetch_assoc()):
                        $custId = $row["cust_id"];
                        $hqId = $row["hq_id"];
                        $usrId = $row["usr_id"];
                        $confPropRowMatched = true;
                  endwhile;
                  $result->free();
               endif;

               if ($confPropRowMatched) :

                  // Get special database from information in 
                  $moMnemonicTargetDb = getOperationalDatabase($custId);
                  if ($moMnemonicTargetDb != "") :
                     $remDb = $db;
                     $db = getDbConnectionSpecial($moMnemonicTargetDb, $dbname, $dblogin, $dbpassword);

                     // In older VPA client versions <tr_id> contains "tr_sort" and has to be mapped to "tr_id"!
                     if ($xmlContext == "tour") :
                         if ($xmlJbId != "" && is_numeric($xmlJbId) && $xmlTrId != "" && is_numeric($xmlTrId) && $xmlTrId < 100) :
                            $xmlTrId = getFieldValueFromClause("phoenix.tour", "tr_id", "jb_id = '" . $xmlJbId . "' AND tr_sort = '" . $xmlTrId . "'");
                         endif;
                     endif;

                     // If job ID does exist AND automailer functionality is enabled then write semaphor into taget database
                     if ($xmlJbId != "" && is_numeric($xmlJbId)) :
                        // $constAutomailerEnabled = getParameterValue("0", "AUTOMAILER_ENABLED", "0");  // "Meta-Global" <=> hq_id = 0
                        $constAutomailerEnabled = "1";
                        if ($constAutomailerEnabled == '1') :
                           if (existsEntry("phoenix_log.semaphor",array("sp_obj_type","jb","sp_obj_id",$xmlJbId,"sp_fieldname",$semaphorKey))) :
                              updateStmt("phoenix_log.semaphor", "sp_obj_id", $xmlJbId, array("sp_createtime", $currentTime),"sp_obj_type = 'jb' AND sp_fieldname = '" . $semaphorKey . "'");
                           else :
                              insertStmt("phoenix_log.semaphor", array("sp_obj_type", "jb", "sp_obj_id", $xmlJbId, "sp_fieldname", $semaphorKey, "sp_content", "UPLOAD_IMG", "sp_context", "LOCKED", "sp_createtime", $currentTime));
                           endif;
                        endif;
                     endif;

                     if ($custId == "3" || $custId == "103") :
                     // if (false) :

                        // Decode BASE64 and uncompress
                        $filedata = base64_decode($filedata);
                        $filedata = gzinflate($filedata);
                        
                        // Get cr_id from usr_id
                        $crId = getFieldValueFromId("phoenix.courier","usr_id", $usrId,"cr_id");
                        if ($crId != "" && $crId != "0") :
                        
                           // Generate output file by writing $filedata
                           $path = "../upload/mbl_foto/";
                           // if (file_exists($path . $filename)) :
                           //    unlink($path . $filename);
                           // endif;
                           writeToFile($path . $filename, $filedata);
                           // sleep(2);
                           // if (!file_exists($path . $filename)) :
                           //    $opState = "ERR 113 : No bo_ext_id0 ID!";
                           // endif;
                        
                           // Get b2b object
                           $boId = getFieldValueFromClause("phoenix_log.b2b_objects", "bo_id", $whereClauseStarttime . "bo_type = '101' AND bo_ext_id1=" . $crId . " AND bo_obj_data = '" . $filename . "'");
                           if ($boId != "" && $boId != "0") :
                        
                              $res = updateStmt("phoenix_log.b2b_objects","bo_ext_id0",$boId,array("bo_state", "1"), "bo_type = '105'");
                              // if ($db->affected_rows = 0) :
                              //    $opState = "ERR 112 : No update by 105!";
                              // endif;
                              $boIdNew101 = $boId;  // For error handling ONLY
                           else :
                              $sqlStmt = "INSERT INTO phoenix_log.b2b_objects (bo_ver,bo_type,bo_state,bo_ext_id0,bo_ext_id1,bo_ext_id2,bo_obj_data,bo_createtime)" .
                                         " VALUES ('0','101','1','0','$crId','0','$filename','$currentTime')";
                              $res = $db->query($sqlStmt);
                              if (DB::isError($res)) : die ("$PHP_SELF: " . $res->getMessage()); endif;
                              $boIdNew101 = getLastInsertID();
                              // $opState = "ERR 111 : No bo_ext_id0 ID!";
                           endif;
                        else :
                           // $opState = "ERR 110 : No courier ID!";
                        endif;

                     // elseif ($custId == "6" || $custId == "106" || $custId == "11" || $custId == "1" || $custId == "2" || $custId == "100" || $custId == "101" || $custId == "102") :
                     else :

                        if ($xmlContext == "lda" && $xmlTrId == "") :
                           if ($xmlComm != "" && ($custId == "1" || $custId == "2" || $custId == "100" || $custId == "101" || $custId == "102")) :
                              $xmlJbId = getFieldValueFromClause("phoenix.tour", "jb_id", "tr_commission_no = '" . $xmlComm . "' ORDER BY jb_id DESC LIMIT 0,1");
                              $xmlTrId = getFieldValueFromClause("phoenix.tour", "tr_id", "tr_commission_no = '" . $xmlComm . "' ORDER BY jb_id DESC LIMIT 0,1");
                              $hqId = getFieldValueFromId("phoenix.user","usr_id", $usrId,"hq_id");
                           endif;
                        endif;

                        // Decode BASE64 and uncompress
                        $filedata = base64_decode($filedata);
                        $filedata = gzinflate($filedata);
                        $filedata = base64_encode($filedata);
                        // writeToFile("debug.log", $filedata);
                        $filedataArray = str_split($filedata, 32768);  // 32K
                        $filedataArrayLen = count($filedataArray);
                        for ($i = 0; $i < $filedataArrayLen; $i++) :
                            $tmpChunk = $filedataArray[$i];
                            $filedataArray[$i] = "<![CDATA[" . $tmpChunk . "]]>";
                        endfor;
                        // writeToFile("debug2.log", $tmpOut);
                        // Write main file
                        // writeToFile($filename, $filedata);

                        // $bo_ext_id0 = "";
                        // $bo_ext_id0 = $xmlJbId;
                        /*
                        if ($xmlCust == "moebel_live") :
                           if ($xmlJbId != "" && is_numeric($xmlJbId)) :
                               $bo_ext_id0 = getFieldValueFromClause("phoenix.tour","tr_id","jb_id = '" . $xmlJbId . "' AND tr_sort = '2'");  // equals tr_id
                           endif;
                        endif;
                        */

                        if ($debugMode) :
                           echo "xmlJbId: " . $xmlJbId . "<br>";
                           echo "xmlTrId: " . $xmlTrId . "<br>";
                           echo "usrId: " . $usrId . "<br>";
                           echo "filename: " . $filename . "<br>";
                           echo "currentTime: " . $currentTime . "<br>";
                           echo "hqId: " . $hqId . "<br>";
                        endif;

                        // **** Insert data sets into b2b_objects ***
                        if (($xmlContext == "pp" || $xmlContext == "ap") && $xmlJbId != "") :

                           if (!existsEntry("phoenix_log.b2b_objects",array("bo_type","101","bo_ext_id0",$xmlJbId,"bo_obj_data",$filename))) :

                              // Insert "101"
                              $sqlStmt = "INSERT INTO phoenix_log.b2b_objects (bo_ver,bo_type,bo_state,bo_ext_id0,bo_ext_id1,bo_ext_id2,bo_obj_data,bo_createtime)" .
                                         " VALUES ('0','101','0','$xmlJbId','$usrId','0','$filename','$currentTime')";
                              $res = $db->query($sqlStmt);
                              if (DB::isError($res)) : die ("$PHP_SELF: " . $res->getMessage()); endif;                                     
                              $boIdNew101 = getLastInsertID();

                              if ($debugMode) :
                                 echo "boIdNew101: " . $boIdNew101 . "<br>";
                              endif;

                              // Insert "102"
                              for ($i = 0; $i < $filedataArrayLen; $i++) :
                                  $sqlStmt = "INSERT INTO phoenix_log.b2b_objects (bo_ver,bo_type,bo_state,bo_ext_id0,bo_ext_id1,bo_ext_id2,bo_obj_data,bo_createtime)" .
                                             " VALUES ('0','102','0','$boIdNew101','$usrId','$i','$filedataArray[$i]','$currentTime')";
                                  $res = $db->query($sqlStmt);
                                  if (DB::isError($res)) : die ("$PHP_SELF: " . $res->getMessage()); endif;                                     
                                  $boIdNew102 = getLastInsertID();
                              endfor;
                           endif;

                        elseif (($xmlContext == "tour" && $xmlTrId != "") || ($xmlContext == "lda" && $xmlJbId != "")) :
                           // Existing "101"
                           $boIdNew101 = getFieldValueFromClause("phoenix_log.b2b_objects", "bo_id", "bo_type = '101' AND bo_createtime >= '" . $currentDateYesterday . "' AND bo_obj_data = '" . $filename . "'");

                           if ($xmlContext == "lda") :
                              // $xmlJbId = getFieldValueFromClause("phoenix_log.b2b_objects", "bo_ext_id1", "bo_type = '120' AND bo_state > '0' AND bo_createtime >= '" . $currentDateYesterday . "' AND bo_obj_data LIKE '%" . $filename . "%'");
                              $xmlTrId = getFieldValueFromClause("phoenix_log.b2b_objects", "bo_ext_id2", "bo_type = '120' AND bo_createtime >= '" . $currentDateYesterday . "' AND bo_obj_data LIKE '%" . $filename . "%'");
                           endif;

                           if ($debugMode) :
                              echo "xmlJbId: " . $xmlJbId . "<br>";
                              echo "xmlTrId: " . $xmlTrId . "<br>";
                           endif;

                           if ($boIdNew101 == "") :

                              // Insert "101"
                              $sqlStmt = "INSERT INTO phoenix_log.b2b_objects (bo_ver,bo_type,bo_state,bo_ext_id0,bo_ext_id1,bo_ext_id2,bo_obj_data,bo_createtime)" .
                                         " VALUES ('0','101','0','$xmlTrId','$usrId','0','$filename','$currentTime')";
                              $res = $db->query($sqlStmt);
                              if (DB::isError($res)) : die ("$PHP_SELF: " . $res->getMessage()); endif;
                              $boIdNew101 = getLastInsertID();
                           else :
                              // Update "101"
                              $sqlStmt = "UPDATE phoenix_log.b2b_objects SET bo_ext_id0 = '$xmlTrId' WHERE bo_id = '$boIdNew101'";
                              $res = $db->query($sqlStmt);
                              if (DB::isError($res)) : die ("$PHP_SELF: " . $res->getMessage()); endif;
                           endif;

                           if ($debugMode) :
                              echo "boIdNew101: " . $boIdNew101 . "<br>";
                           endif;

                           // Insert "102"
                           if ($boIdNew101 != "") :
                              for ($i = 0; $i < $filedataArrayLen; $i++) :
                                  $sqlStmt = "INSERT INTO phoenix_log.b2b_objects (bo_ver,bo_type,bo_state,bo_ext_id0,bo_ext_id1,bo_ext_id2,bo_obj_data,bo_createtime)" .
                                             " VALUES ('0','102','0','$boIdNew101','$usrId','$i','$filedataArray[$i]','$currentTime')";
                                  $res = $db->query($sqlStmt);
                                  if (DB::isError($res)) : die ("$PHP_SELF: " . $res->getMessage()); endif;                                     
                                  $boIdNew102 = getLastInsertID();
                              endfor;
                           endif;
                        endif;
                     endif;

                     $db = $remDb;
                  else :
                     $opState = "ERR 107 : No target database specified!";
                  endif;
               else :
                  $opState = "ERR 106 : No row in table conf_prop matched!";
               endif;
            else :
               $opState = "ERR 105 : metaobject not reachable!";
            endif;
         else :
            $opState = "ERR 104 : No global environment definitions found!";
         endif;
      else :
         $opState = "ERR 103 : No file data!";
      endif;
   else :
      $opState = "ERR 102 : Filename empty!";
   endif;
else :
   $opState = "ERR 101 : Unknown client IP!";
endif;

// Write metadata to log
$logFilename = "upload.log";
if ($custId != "" && is_numeric($custId)) :
   $logFilename = "upload_" . $custId . ".log";
endif;
writeToFile($logFilename, $custId . " | " . $currentTime . " | " . date("Y-m-d H:i:s") . " | " . $currentClientIP . " | " . $filename . " | " . $metadata . " | " . $opState . " | boIdNew101: " . $boIdNew101 . " | boIdNew102: " . $boIdNew102 . " | xmlJbId: " . $xmlJbId . " | xmlTrId: " . $xmlTrId);

// Write file data by error
if (($opState != "OK" || ($boIdNew101 == "" || !is_numeric($boIdNew101))) && $filename != "" && $filedata != "") :
   $errPath = "../upload/photos_err/";
   writeToFile($errPath . $filename, $filedata);
   $opState = "OK";
endif;

// Response
//echo $opState;
// 01.09.2016 CA: always respond "OK" because the data will never be sent correctly if they are wrong
echo "OK";
?>
