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

include_once ("../import/import.php");


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


// Check HTTP-Parameters
getSecHttpVars("1",array("f_act", "statusMessage", "f_importFile", "f_uploadFile", "docLocalDirCurrent", "docLocalDirCurrentUpload",
                         "f_ftp_filename", "ftp_server", "ftp_user_name",
                         "ftp_user_pass", "ftp_path_dest", "f_ftp_servername", "f_ftp_ssl",
                         "deactivateMenu", "objType", "objId", "objType_upload", "objId_upload",
                         "customerId", "cscIdRoot", "cscIdActual"));

getLanguage(__FILE__);

$pageTitel = getLngt("DATENIMPORT");
include_once ("../admin/menu.php");
include_once ("../include/html.inc.php");
include_once ("../include/ftp.inc.php");
getCurrentScript(__FILE__);

// INIT
$dirSpecialForObjType = "";
$fileFilterPrefix = "";

// Select user-type for mode of security check 
$userType = getFieldValueFromId("user","usr_id",$usr_id,"usr_type");
$userTypeName = getUserTypeName($userType);
$userTypeRAMP = "5";

// Check for authentication access
$specialStaticDirActive = false;
if ($userType == $userTypeRAMP) :
   $specialStaticDirActive = true;
   $specialFTPServerList = "ITCS";
else :
   $usrAccessArray["hq"] = "1";
   authCheckForAccess($hq_id, $usr_id, $emp_id, "1", $customerId, $cscIdRoot, $cscIdActual);
   if (!(authCheckEmployeeRights($emp_id, "22") || authCheckEmployeeRights($emp_id, "23"))) : gotoReferer("1"); endif;
endif;

$empHasAdminRights = false;
$empIdRootAdmin = getEmpIdOfRootAdmin($userTypeName);
if ($empIdRootAdmin != "" && $emp_id == $empIdRootAdmin) : 
   $empHasAdminRights = true;
endif;

$debug = false;
if ($empIdRootAdmin == $emp_id) :
   $debug = false;
endif;

$statusMessage = "";
$importFileStatusMsg = "";

// Set root directory regarding the current mandator
$rootDirDefault = "../import/upload/";
$rootDirDefaultLen = strlen($rootDirDefault);
$mdRootDirDefault = getFieldValueFromId("mandator","md_id",$md_id,"md_doc_path");
if ($mdRootDirDefault != "" && substr($mdRootDirDefault, 0,$rootDirDefaultLen) == $rootDirDefault) :
   $rootDirDefault = $mdRootDirDefault;
else :
   gotoReferer("1");
endif;
$rootDirDefaultLen = strlen($rootDirDefault);

// Set enforced object type regarding to some user types
if ($userTypeName != "hq") :
   if ($userTypeName == "cs")   : $objType = "CS";   endif;
   if ($userTypeName == "cr")   : $objType = "CR";   endif;
   if ($userTypeName == "crvh") : $objType = "CRVH"; endif;
   if ($userTypeName == "jb")   : $objType = "JB";   endif;
   if ($userTypeName == "emp")  : $objType = "EMP";  endif;
   
   if ($f_act == "uploadFile" && !$specialStaticDirActive)  : $f_act = ""; endif;
endif;

// For form parameters only
if ($f_act == "uploadFile") :
   $objType = $objType_upload;
   $objId = $objId_upload;
endif;

// Map $objType from "CSC" TO "CS" and change object ID containing the "csc_id" to the corresponding "cs_id"
$objType = strtoupper(trim($objType));
if ($objType == "CSC_CS" && $objId != "" && is_numeric($objId)) :
   $objType = "CS";
   $objId = getFieldValueFromId("costcenter","csc_id",$objId,"cs_id");
endif;

// * SECURITY BEGIN *
// Restriction: Set a fix object type regarding to the uset type
if ($userType == $userTypeRAMP) : 
   $objType = "RAMP";
endif;
// * SECURITY END *

if ($debug) :
   echo "objType : " . $objType . "<br>";
endif;

// Set current directory and check for special object type (e.g. customer = "cs") to define a special subdirectory to be "root"
if ($docLocalDirCurrentUpload != "") :
   if ($docLocalDirCurrentUpload != "" && substr($docLocalDirCurrentUpload, 0,$rootDirDefaultLen) == $rootDirDefault) :
      $docLocalDirCurrent = $docLocalDirCurrentUpload;
   else :
      gotoReferer("1");
   endif;
endif;
if ($objType != "") :
   $dirSpecialForObjType = getParameterValue("0", "DATATRANSFER_DIRECTORY_" . $objType, $hq_id);
   if ($dirSpecialForObjType == "") : $dirSpecialForObjType = getParameterValue("0", "DATATRANSFER_DIRECTORY_" . $objType, "0"); endif;
   if ($dirSpecialForObjType == "") : 
      if ($objType == "CS")   : $dirSpecialForObjType = "90b1a8efc903576bbb2d6e2a79b00a5e"; endif;
      if ($objType == "CR")   : $dirSpecialForObjType = "f697836ccbee1a08ff752f5510049f6e"; endif;
      if ($objType == "JB")   : $dirSpecialForObjType = "a547bc4b2a91355a3aba3ed0827cf6f2"; endif;
      if ($objType == "EMP")  : $dirSpecialForObjType = "yxj5fr3gz7uau378cf4gh2fcnh67i7gh"; endif;
      if ($objType == "CRVH") : $dirSpecialForObjType = "7bb0357ar00a5u89ob1e3c9b2d6e2a79"; endif;
      if ($objType == "RAMP") : $dirSpecialForObjType = "traffic_control"; endif;
   endif;
   $dirSpecialForObjType .= "/";

   // Get parameter for usage the headquarters as sub-paths
   $parUseHqPath = getParameterValue("0", "DATATRANSFER_HQ_PATH_" . $objType . "_ENABLED", $hq_id);
   if ($parUseHqPath == "") : $parUseHqPath = getParameterValue("0", "DATATRANSFER_HQ_PATH_" . $objType . "_ENABLED", "0"); endif;

   // Check for filter according to specified object type and object ID
   $fileFilterPrefix = "";
   if ($objId != "" && is_numeric($objId)) :
      if ($objType == "CS")   : $fileFilterPrefix = getFieldValueFromId("customer","cs_id",$objId,"cs_eid"); endif;
      if ($objType == "CR")   : $fileFilterPrefix = getFieldValueFromId("courier","cr_id",$objId,"cr_eid");  endif;
      if ($objType == "JB")   : $fileFilterPrefix = $objId; endif;
      if ($objType == "EMP")  : $fileFilterPrefix = $objId; endif;
      if ($objType == "CRVH") : $fileFilterPrefix = $objId; endif;
      if ($objType == "RAMP") : $fileFilterPrefix = $hq_id; endif;
   endif;

   // Check for headquartes
   if ($hq_id != "" && $parUseHqPath == "1") :
      $hqMnemonic = getFieldValueFromId("headquarters","hq_id",$hq_id,"hq_mnemonic");
      if ($hqMnemonic == "") : $hqMnemonic = "MISC" ; endif;
      $dirSpecialForObjType .= $hqMnemonic . "/";
   endif;
endif;
if ($docLocalDirCurrent == "") :
   $docLocalDirCurrent = $rootDirDefault;
   $docLocalDirCurrent .= $dirSpecialForObjType;
endif;

// Set current root dir
$rootDirCurrent = $rootDirDefault . $dirSpecialForObjType;
$rootDirCurrentLen = strlen($rootDirCurrent);

$docLocalDirCurrentLen = strlen($docLocalDirCurrent);
$dirSpecialForObjTypeLen = strlen($dirSpecialForObjType);
$fileFilterPrefixLen = strlen($fileFilterPrefix);

// Set FTP or SFTP
if ($f_ftp_ssl == "") : $f_ftp_ssl = ""; endif;

// Get existing FTP server names AND/OR import types
$ftpServerListArray = array();
if ($specialStaticDirActive) :
   $ftpServerList = $specialFTPServerList;
else :
   $ftpServerList = getParameterValue("0", "FTP_IMPORT_SERVERLIST", $hq_id);
   if ($ftpServerList == "") :
      $ftpServerList = getParameterValue("0", "FTP_IMPORT_SERVERLIST", "0");
   endif;
endif;
$ftpServerListArray = array();
$ftpCurrentSelectedServerAccess = false;
if ($ftpServerList != "") :
   // Get the list of remote (S)FTP servers
   // $ftpServerListArray = spliti(",",$ftpServerList);
   
   // Check for accessability by admin only
   $tmpFtpServerListArray = spliti(",",$ftpServerList);
   $tmpFtpServerListArrayLen = count($tmpFtpServerListArray);
   for ($j = 0; $j < $tmpFtpServerListArrayLen; $j++) :
       // Check item to be displayed for all or for admin only
       $ftpAdminAccessState = getParameterValue("0", "FTP_DISPLAY_ADMIN_ONLY_" . $tmpFtpServerListArray[$j], "0");
       if ($ftpAdminAccessState != "1" || $empHasAdminRights) :
          $ftpServerListArray[] = $tmpFtpServerListArray[$j];
       endif;
       // Check parameter for current item to to have access rights for remote server
       if ($f_ftp_servername != "" && $tmpFtpServerListArray[$j] == $f_ftp_servername) :
          $ftpAdminAccessState = getParameterValue("0", "FTP_ACCESS_ADMIN_ONLY_" . $tmpFtpServerListArray[$j], "0");
          if ($ftpAdminAccessState != "1" || $empHasAdminRights) :
             $ftpCurrentSelectedServerAccess = true;
          endif;
       endif;
   endfor;
endif;
$ftpServerListArrayLen = count($ftpServerListArray);

// If ONLY ONE item does exist AND this entry does NOT having an association to a FTP data set then preselect it
if ($ftpServerListArrayLen == 1 && $f_ftp_servername == "" && $ftp_server == "") :
   $f_ftp_servername = $ftpServerListArray[0];
endif;


// Get FTP access data
// "$f_ftp_servername" contains the FTP server name AND/OR the "IMPORT TYPE" (UTA, APO, ...) NOT being associated to a FTP data set stringently (!!!)
if ($f_ftp_servername != "" && $ftp_server == "") :
   $ftp_server = getParameterValue("0", "FTP_SERVER_" . $f_ftp_servername, $hq_id);
   if ($ftp_server == "") : $ftp_server = getParameterValue("0", "FTP_SERVER_" . $f_ftp_servername, "0"); endif;
   if ($ftp_server != "") :
      $ftp_user_name = getParameterValue("0", "FTP_USER_" . $f_ftp_servername, $hq_id);
      if ($ftp_user_name == "") : $ftp_user_name = getParameterValue("0", "FTP_USER_" . $f_ftp_servername, "0"); endif;
      $ftp_user_pass = getParameterValue("0", "FTP_PASSWORD_" . $f_ftp_servername, $hq_id);
      if ($ftp_user_pass == "") : $ftp_user_pass = getParameterValue("0", "FTP_PASSWORD_" . $f_ftp_servername, "0"); endif;
      $ftp_path_dest = "";
      if ($ftpCurrentSelectedServerAccess) :
         $ftp_path_dest = getParameterValue("0", "FTP_REMOTEPATH_" . $f_ftp_servername, $hq_id);
         if ($ftp_path_dest == "") : $ftp_path_dest = getParameterValue("0", "FTP_REMOTEPATH_" . $f_ftp_servername, "0"); endif;
      endif;
   endif;
endif;

if ($debug) :
   echo "ftpServerList : " . $ftpServerList . "<br>";
   echo "ftp_server : " . $ftp_server . "<br>";
   echo "f_ftp_servername : " . $f_ftp_servername . "<br>";
   echo "ftp_user_name : " . $ftp_user_name . "<br>";
   echo "ftp_user_pass : " . $ftp_user_pass . "<br>";
   echo "<br><br>";
endif;

// !!!!!!! TEST !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
/*
INSERT INTO parameter (par_id, par_key, hq_id, emp_id, par_value, par_text) VALUES (104137, 'FTP_SERVERNAME_UTA', 0, 0, 'UTA', 'FTP server name for UTA');
INSERT INTO parameter (par_id, par_key, hq_id, emp_id, par_value, par_text) VALUES (104127, 'FTP_SERVER_UTA', 0, 0, 'server', 'FTP server for UTA');
INSERT INTO parameter (par_id, par_key, hq_id, emp_id, par_value, par_text) VALUES (104128, 'FTP_USER_UTA', 0, 0, 'u1234567890', 'FTP user for UTA');
INSERT INTO parameter (par_id, par_key, hq_id, emp_id, par_value, par_text) VALUES (104129, 'FTP_PASSWORD_UTA', 0, 0, 'asds1234', 'FTP password for UTA');
INSERT INTO parameter (par_id, par_key, hq_id, emp_id, par_value, par_text) VALUES (104130, 'FTP_REMOTEPATH_UTA', 0, 0, '/uppath/', 'FTP upload path where files will be stored for UTA');

INSERT INTO parameter (par_id, par_key, hq_id, emp_id, par_value, par_text) VALUES (104138, 'FTP_SERVERNAME_AS2_TRANSFER', 0, 0, 'AS2_TRANSFER', 'FTP server name for AS2_TRANSFER');
INSERT INTO parameter (par_id, par_key, hq_id, emp_id, par_value, par_text) VALUES (104132, 'FTP_SERVER_AS2_TRANSFER', 0, 0, '172.16.0.155', 'FTP server for AS2_TRANSFER');
INSERT INTO parameter (par_id, par_key, hq_id, emp_id, par_value, par_text) VALUES (104133, 'FTP_USER_AS2_TRANSFER', 0, 0, 'anonymous', 'FTP user for AS2_TRANSFER');
INSERT INTO parameter (par_id, par_key, hq_id, emp_id, par_value, par_text) VALUES (104134, 'FTP_PASSWORD_AS2_TRANSFER', 0, 0, '', 'FTP password for AS2_TRANSFER');
INSERT INTO parameter (par_id, par_key, hq_id, emp_id, par_value, par_text) VALUES (104135, 'FTP_REMOTEPATH_AS2_TRANSFER', 0, 0, '/download/', 'FTP remote path where files will be stored for AS2_TRANSFER');

if ($f_ftp_servername == "") :
   $ftp_server = FTP_SERVER;
   $ftp_user_name = FTP_USER;
   $ftp_user_pass = FTP_PASSWORD;
   $ftp_path_dest = FTP_UPLOADPATH;
endif;
*/
// !!!!!!! TEST !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!


$ftp_path_dest = trim($ftp_path_dest);
if ($ftp_path_dest != "") :
   $ftp_path_dest = urldecode($ftp_path_dest);
endif;
if (substr($ftp_path_dest,0,1) == "/" && substr($ftp_path_dest,-1) == "/") : 
   $ftp_path_dest = substr($ftp_path_dest,1,-1);
endif;

// Get number of files in the upload folder
$numOfFiles = getNumOfFilesInFolder($docLocalDirCurrent);

if ($debug) :
   echo "rootDirDefault : " . $rootDirDefault . " [Länge: " . $rootDirDefaultLen . "]<br>";
   echo "rootDirCurrent : " . $rootDirCurrent . " [Länge: " . $rootDirCurrentLen . "]<br>";
   echo "docLocalDirCurrent : " . $docLocalDirCurrent . " [Länge: " . $docLocalDirCurrentLen . "]<br>";
   echo "dirSpecialForObjType : " . $dirSpecialForObjType . " [Länge: " . $dirSpecialForObjTypeLen . "]<br>";
   echo "fileFilterPrefix : " . $fileFilterPrefix . " [Länge: " . $fileFilterPrefixLen . "]<br>";
   echo "numOfFiles : " . $numOfFiles . "<br>";
   echo "f_ftp_servername_upload : " . $f_ftp_servername_upload . "<br>";
   echo "ftpServerList : " . $ftpServerList . "<br>";
   echo "f_ftp_servername : " . $f_ftp_servername . "<br>";   
   echo "ftp_path_dest : " . $ftp_path_dest . "<br>";
   echo "<br>";
endif;

// Process uploaded file per HTTP
if ($f_act == "uploadFile") :

   $processUpload = true;
   
   // Check for max. of ALL files in path
   if ($processUpload) :
      $parMaxFiles = getParameterValue("0", "DATATRANSFER_MAX_ALL_FILES_DIRECTORY_" . $objType, $hq_id);
      if ($parMaxFiles == "" || !is_numeric($parMaxFiles)) : $parMaxFiles = getParameterValue("0", "DATATRANSFER_MAX_ALL_FILES_DIRECTORY_" . $objType, "0"); endif;
      if ($parMaxFiles == "" || !is_numeric($parMaxFiles)) : $parMaxFiles = 500; endif;
      if ($numOfFiles >= $parMaxFiles) :
         $processUpload = false;
      endif;
   endif;

   // Check for max. of files of the current customer in path
   if ($processUpload && $fileFilterPrefix != "") :
      $parMaxFiles = getParameterValue("0", "DATATRANSFER_MAX_FILES_SPECIAL_" . $objType, $hq_id);
      if ($parMaxFiles == "" || !is_numeric($parMaxFiles)) : $parMaxFiles = getParameterValue("0", "DATATRANSFER_MAX_FILES_SPECIAL_" . $objType, "0"); endif;
      if ($parMaxFiles == "" || !is_numeric($parMaxFiles)) : $parMaxFiles = 3; endif;
      $objNumOfFiles = getNumOfFilesByFilterInFolder($docLocalDirCurrent, $fileFilterPrefix, "1");
      if ($objNumOfFiles >= $parMaxFiles) :
         $processUpload = false;
      endif;
   endif;

   // Check for employee rights. Administrators have no restrictions regarding the number of files
   if ($empHasAdminRights) : $processUpload = true; endif;   

   if ($processUpload) :
      if ($_FILES['f_uploadFile']['size'] <= 4000000) :

         // Append filename for prefix if e.g. a special customer (courier, etc.) has been selected
         $uploadPrefix = "";
         if ($fileFilterPrefix != "" && substr($_FILES['f_uploadFile']['tmp_name'],0,$fileFilterPrefixLen) != $fileFilterPrefix) :
            $uploadPrefix = $fileFilterPrefix . "_";
         endif;

         if (!move_uploaded_file($_FILES['f_uploadFile']['tmp_name'], $docLocalDirCurrent . $uploadPrefix . $_FILES['f_uploadFile']['name'])) :
            $statusMessage .= getLngt("Die Datei wurde leider nicht hochgeladen!");
            writeToLogDB("97",$hq_id,"",$usr_id,"","","","FILE=" . $_FILES['f_uploadFile']['name'] . "|STATUS=NO_UPLOAD");
         else :
            writeToLogDB("97",$hq_id,"",$usr_id,"","","","FILE=" . $_FILES['f_uploadFile']['name'] . "|STATUS=OK");
         endif;
      else :
         $statusMessage .= getLngt("Die Datei ist für den Upload zu groß!");
         writeToLogDB("97",$hq_id,"",$usr_id,"","","","FILE=" . $_FILES['f_uploadFile']['name'] . "|STATUS=TOO_LARGE");

         // Delete real file if does exist
         $retVal = removeFile($_FILES['f_uploadFile']['name'], $docLocalDirCurrent, $pathSeparator); 
      endif;

      // Delete temp file if does exist
      $retVal = removeFile($_FILES['f_uploadFile']['tmp_name'], $tempPath, $pathSeparator);

      // Insert or update in REDUNDANT structure ("gdc") because of performance by displaying lists (customer list, courier list, job list, etc.)!
      gdcSetNumberOfDocuments($docLocalDirCurrent, $objType, $objId, $fileFilterPrefix);
   else :
      $statusMessage .= getLngt("Bevor eine weitere Datei hochgeladen werden kann, muss das Verzeichnis bereinigt werden!");
   endif;
endif;

// Manually removal of a specified importfile
if ($f_act == "removeImportfile") :

   // Remove import file
   $retVal = removeFile($f_importFile, $docLocalDirCurrent, $pathSeparator);
   
   if ($retVal == "0") :
         
   elseif ($retVal == "-1") :
     $statusMessage = getLngt("Es liegt kein Dateiname vor!");
   elseif ($retVal == "-2") :
     $statusMessage = getLngt("Die Datei befindet sich nicht mehr in dem Verzeichnis!");
   elseif ($retVal == "") :
     $statusMessage = getLngt("Es fand keine Löschung statt!");
   endif;

   // Insert or update in REDUNDANT structure ("gdc") because of performance by displaying lists (customer list, courier list, job list, etc.)!
   gdcSetNumberOfDocuments($docLocalDirCurrent, $objType, $objId, $fileFilterPrefix);
endif;

// Upload FTP file
if ($f_act == "ftpUpload") :
   if ($f_ftp_filename != "") :
      if ($ftp_server != "" && $ftp_user_name != "") :
         $tmpArray = ftpUpload($f_ftp_filename, "", $ftp_server, $ftp_user_name, $ftp_user_pass, $docLocalDirCurrent, $ftp_path_dest, $f_ftp_ssl);         
         if ($tmpArray[0] == "0") :
            writeToLogDB("99",$hq_id,"",$usr_id,"","","","FILE=" . $f_ftp_filename . "|SERVER=" . $ftp_server . "|STATUS=OK|ERR=");
            // Insert or update in REDUNDANT structure ("gdc") because of performance by displaying lists (customer list, courier list, job list, etc.)!
            gdcSetNumberOfDocuments($docLocalDirCurrent, $objType, $objId, $fileFilterPrefix);
         else :
            $statusMessage = $tmpArray[1];
            writeToLogDB("99",$hq_id,"",$usr_id,"","","","FILE=" . $f_ftp_filename . "|SERVER=" . $ftp_server . "|STATUS=NO_UPLOAD|ERR=" . $statusMessage);
         endif;
      else :
         $statusMessage = getLngt("Die Angaben für den Zugriff auf den FTP-Server sind unvollständig!");
         // writeToLogDB("99",$hq_id,"",$usr_id,"","","","FILE=" . $f_ftp_filename . "|SERVER=" . $ftp_server . "|STATUS=BAD_CONFIG");
      endif;
   else :
      $statusMessage = getLngt("Die Datei wurde nicht gefunden!");
      // writeToLogDB("99",$hq_id,"",$usr_id,"","","","FILE=" . $f_ftp_filename . "|SERVER=" . $ftp_server . "|STATUS=FILE_NOT_FOUND");
   endif;
endif;

// Download FTP file
if ($f_act == "ftpDownload") :
   if ($f_ftp_filename != "") :
      if ($ftp_server != "" && $ftp_user_name != "") :
         $tmpArray = ftpDownload($f_ftp_filename, "", $ftp_server, $ftp_user_name, $ftp_user_pass, $docLocalDirCurrent, $ftp_path_dest, $f_ftp_ssl);
         if ($tmpArray[0] == "0") :
            writeToLogDB("100",$hq_id,"",$usr_id,"","","","FILE=" . $f_ftp_filename . "|SERVER=" . $ftp_server . "|STATUS=OK|ERR=");
            // Insert or update in REDUNDANT structure ("gdc") because of performance by displaying lists (customer list, courier list, job list, etc.)!
            gdcSetNumberOfDocuments($docLocalDirCurrent, $objType, $objId, $fileFilterPrefix);
         else :
            $statusMessage = $tmpArray[1];
            writeToLogDB("100",$hq_id,"",$usr_id,"","","","FILE=" . $f_ftp_filename . "|SERVER=" . $ftp_server . "|STATUS=NO_DOWNLOAD|ERR=" . $statusMessage);
         endif;
      else :
         $statusMessage = getLngt("Die Angaben für den Zugriff auf den FTP-Server sind unvollständig!");
         // writeToLogDB("100",$hq_id,"",$usr_id,"","","","FILE=" . $f_ftp_filename . "|SERVER=" . $ftp_server . "|STATUS=BAD_CONFIG");
      endif;
   else :
      $statusMessage = getLngt("Die Datei wurde nicht gefunden!");
      // writeToLogDB("100",$hq_id,"",$usr_id,"","","","FILE=" . $f_ftp_filename . "|SERVER=" . $ftp_server . "|STATUS=FILE_NOT_FOUND");
   endif;
endif;

// Delete FTP file
if ($f_act == "ftpDelete") :
   if ($f_ftp_filename != "") :
      if ($ftp_server != "" && $ftp_user_name != "") :
         $tmpArray = ftpDelete($f_ftp_filename, $ftp_server, $ftp_user_name, $ftp_user_pass, $ftp_path_dest, $f_ftp_ssl);
         if ($tmpArray[0] != "0") :
            $statusMessage = $tmpArray[1];
         endif;
      else :
         $statusMessage = getLngt("Die Angaben für den Zugriff auf den FTP-Server sind unvollständig!");
      endif;
   else :
      $statusMessage = getLngt("Die Datei wurde nicht gefunden!");
   endif;
endif;

if ($debug) :
   echo "rootDirDefault : " . $rootDirDefault . " [Länge: " . $rootDirDefaultLen . "]<br>";
   echo "rootDirCurrent : " . $rootDirCurrent . " [Länge: " . $rootDirCurrentLen . "]<br>";
   echo "docLocalDirCurrent : " . $docLocalDirCurrent . " [Länge: " . $docLocalDirCurrentLen . "]<br>";
   echo "dirSpecialForObjType : " . $dirSpecialForObjType . " [Länge: " . $dirSpecialForObjTypeLen . "]<br>";
   echo "fileFilterPrefix : " . $fileFilterPrefix . " [Länge: " . $fileFilterPrefixLen . "]<br>";
   echo "numOfFiles : " . $numOfFiles . "<br>";
   echo "f_ftp_servername_upload : " . $f_ftp_servername_upload . "<br>";
   echo "ftpServerList : " . $ftpServerList . "<br>";
   echo "f_ftp_servername : " . $f_ftp_servername . "<br>";   
   echo "ftp_path_dest : " . $ftp_path_dest . "<br>";
   echo "ftp_server : " . $ftp_server . "<br>";
   echo "ftp_user_name : " . $ftp_user_name . "<br>";
   echo "ftp_user_pass : " . $ftp_user_pass . "<br>";
   echo "<br><br>";
endif;

// **************************************************
// * Read all of the local filenames to be imported *
// **************************************************
if ($userTypeName == "hq" || $specialStaticDirActive) :

   $colspan = "3";

   // * FILES ON LOCAL SERVER *

   // Get filenames
   $fileNames = getFilenamesInFolder($docLocalDirCurrent);

   $storedImportFiles .= "<table>";
   $storedImportFiles .= "<tr><td class=\"f12bp1_blue\" colspan=\"" . $colspan . "\">" . getLngt("votian") . "</td></tr>";
   $storedImportFiles .= "<tr><td colspan=\"" . $colspan . "\"><br></td></tr>";
   $storedImportFiles .= "<tr><td class=\"f12bn1\" colspan=\"" . $colspan . "\">" . getLngt("Verzeichnis") . ":&nbsp;&nbsp;./" . substr($docLocalDirCurrent, $dirSpecialForObjTypeLen + $rootDirDefaultLen) . "</td></tr>";
   $storedImportFiles .= "<tr><td colspan=\"" . $colspan . "\"><br></td></tr>";

   // Define table header
   $storedImportFiles .= "<tr><td>" . getLngt("Löschen") . "&nbsp;&nbsp;&nbsp;&nbsp;</td><td>" . getLngt("Dateiname") . "&nbsp;&nbsp;&nbsp;&nbsp;</td><td>" . getLngt("WEB-Download") . "&nbsp;&nbsp;&nbsp;&nbsp;</td><td>" . getLngt("FTP-Upload") . "</td></tr>";
   $storedImportFiles .= "<tr><td colspan=\"" . $colspan . "\"><br></td></tr>";

   // Link to parent directory
   $docLocalDirCurrentParent = dirname($docLocalDirCurrent) . "/";
if ($debug) :
   echo "docLocalDirCurrentParent : " . $docLocalDirCurrentParent . "<br>";
endif;
   if (strlen($docLocalDirCurrent) > $rootDirCurrentLen && substr($docLocalDirCurrentParent,0,$rootDirCurrentLen) == $rootDirCurrent && $docLocalDirCurrentParent != "../" && $docLocalDirCurrentParent != "./") :
      $storedImportFiles .= "<tr>";
      $docLocalDirCurrentParent = dirname($docLocalDirCurrent) . "/";
      $storedImportFiles .= "<td>&nbsp;</td>";

      // Enable navigation for headquarter employees only !!!!
      if (!$specialStaticDirActive) :
         $parMasknavigate = getParameterValue("0", "MASK_DATATRANSFER_NAV2ROOTDIR_ENABLED", $hq_id);
         if ($parMasknavigate == "") : $parMasknavigate = getParameterValue("0", "MASK_DATATRANSFER_NAV2ROOTDIR_ENABLED", "0"); endif;
         if ($parMasknavigate == "1") : 
            $storedImportFiles .= "<td><a href=\"javascript:document.forms[0].docLocalDirCurrent.value='" . 
                                      urlencode($docLocalDirCurrentParent . $fileNames[$j]) . "'; finishPage();\">" . "[..]" . 
                                      "</a>" . "&nbsp;&nbsp;&nbsp;&nbsp;</td>";
            $storedImportFiles .= "<td>&nbsp;</td>";
         endif;
      endif;

      $storedImportFiles .= "</tr>";
   endif;

   // Define table body from array
   $fileNamesLen = count($fileNames);
   for ($j = 0; $j < $fileNamesLen; $j++) :

         // Check for predifined directories being not accessible
         if (!is_dir($docLocalDirCurrent . $fileNames[$j]) || $empHasAdminRights || checkForPredefinedDirectories($fileNames[$j])) :

            if (is_file($docLocalDirCurrent . $fileNames[$j])) :
               // Check for filter according to a specified object type and object ID
               // Display all files (e.g. of a specified customer, courier, etc.) only
               $showFile = true;
               if ($fileFilterPrefix != "") :
                  if (substr($fileNames[$j],0,$fileFilterPrefixLen) != $fileFilterPrefix) :
                     $showFile = false;
                  endif;
               endif;

               if ($showFile) :
                  $storedImportFiles .= "<tr>";
                  $storedImportFiles .= "<td align=\"center\">";
                  if ($specialStaticDirActive || authCheckEmployeeRights($emp_id, "22")) :
                     $storedImportFiles .= "<a href=\"javascript:removeImportfile('" . $fileNames[$j] . "');\"><img src=\"../images/trash.jpg\" border=\"0\" height=\"13\" width=\"8\"></a>";
                  endif;
                  $storedImportFiles .= "&nbsp;&nbsp;&nbsp;&nbsp;</td>";
                  
                  // Check current filename is prefix of the name of the import script
                  $activateImportLink = false;
                  $phraseForActivatingImportScript = "import_" . $f_ftp_servername . "_";
                  $phraseForActivatingImportScriptLen = strlen($phraseForActivatingImportScript);
                  if ($fileFilterPrefix == "") :
                     if (substr($fileNames[$j],0,$phraseForActivatingImportScriptLen) == $phraseForActivatingImportScript) :
                        $activateImportLink = true;
                     endif;
                  else :
                     if (substr($fileNames[$j],($fileFilterPrefixLen + 1),$phraseForActivatingImportScriptLen) == $phraseForActivatingImportScript) :
                        $activateImportLink = true;
                     endif;
                  endif;

                  // Show thumbnail
                  $displayThumbnail = "";
                  if (strtolower(substr($fileNames[$j],-4)) == ".jpg" || strtolower(substr($fileNames[$j],-4)) == ".png") :
                     $displayThumbnail = "<img src=\"" . $docLocalDirCurrent . $fileNames[$j] . "\" border=\"0\" height=\"" . "80" . "\" width=\"" . "80" . "\">" . "&nbsp;&nbsp;&nbsp;&nbsp;";
                  endif;

                  // Check for existence of a corresponding import script
                  if ((authCheckEmployeeRights($emp_id, "22") || $specialStaticDirActive) && $f_ftp_servername != "" && $activateImportLink && file_exists("../import/import_" . $f_ftp_servername . ".php")) :
                     $urlClause = "";
                     if ($objType != "") :
                        $urlClause = "&objType=" . $objType . "&objId=" . $objId;
                     endif;
if ($debug) :
   echo "urlClause : " . $urlClause . "<br>";
endif;
                     $storedImportFiles .= "<td style=\"vertical-align:middle\"><a href=\"../import/import_" . $f_ftp_servername . ".php?importFile=" . urlencode($docLocalDirCurrent . $fileNames[$j]) . $urlClause . "\" target=\"_blank\">" . $fileNames[$j] . 
                                               "</a>" . "&nbsp;&nbsp;&nbsp;&nbsp;" . $displayThumbnail . "</td>";
                  else :
                     $storedImportFiles .= "<td style=\"vertical-align:middle\">" . $fileNames[$j] . "&nbsp;&nbsp;&nbsp;&nbsp;" . $displayThumbnail . "</td>";
                  endif;

                  $storedImportFiles .= "<td style=\"text-align:center;vertical-align:middle\">";
                  if ($specialStaticDirActive || authCheckEmployeeRights($emp_id, "22") || authCheckEmployeeRights($emp_id, "23")) :
                     $storedImportFiles .= "<a href=\"../include/data_download.php?f_path=" . $docLocalDirCurrent . "&cscIdRoot=" . ec($cscIdRoot) . 
                                                                 "&cscIdActual=" . ec($cscIdActual) . "&f_fileName=" . $fileNames[$j] . "&context=DATATRANSFER" . "\" target=\"_blank\">" . 
                                           "<img src=\"../images/arrow_down.png\" border=\"0\" height=\"25\" width=\"10\"></a>";
                  endif;
                  $storedImportFiles .= "&nbsp;&nbsp;&nbsp;&nbsp;</td>";

                  $storedImportFiles .= "<td style=\"text-align:center;vertical-align:middle\">";
                  if ($specialStaticDirActive || authCheckEmployeeRights($emp_id, "22")) :
                     $storedImportFiles .= "<a href=\"javascript:ftpUpload('" . $fileNames[$j] . "');\"><img src=\"../images/arrow_right.png\" border=\"0\" height=\"10\" width=\"25\"></a>";
                  endif;
                  $storedImportFiles .= "&nbsp;&nbsp;&nbsp;&nbsp;</td>";
                  $storedImportFiles .= "</tr>";
               endif;

            elseif (is_dir($docLocalDirCurrent . $fileNames[$j])) :
               $storedImportFiles .= "<tr>";
               $storedImportFiles .= "<td>&nbsp;</td>";
               $storedImportFiles .= "<td><a href=\"javascript:document.forms[0].docLocalDirCurrent.value='" . 
                                          urlencode($docLocalDirCurrent . $fileNames[$j] . "/") . "'; finishPage();\">" . "[" . $fileNames[$j] . "]" . 
                                          "</a>" . "&nbsp;&nbsp;&nbsp;&nbsp;</td>";
               $storedImportFiles .= "</tr>";
            endif;
         endif;
   endfor;   
   $storedImportFiles .= "</table>";


   // * REMOTE FTP FILES *

   // Get filenames
   
   $fileNames = array();
   $tmpErrNo = "";
   $tmpErrDesc = "";
   if ($ftpCurrentSelectedServerAccess) :
      if ($f_ftp_servername != "" && $ftp_server != "" && $f_ftp_ssl != "") :
         $tmpArray = ftpDir($ftp_server, $ftp_user_name, $ftp_user_pass, $ftp_path_dest, "", $f_ftp_ssl);
         $fileNames = $tmpArray[0]; $tmpErrNo = $tmpArray[1]; $tmpErrDesc = $tmpArray[2];
      endif;
   endif;

   $storedRemoteFiles .= "<table>";
   $storedRemoteFiles .= "<tr><td class=\"f12bp1_blue\" colspan=\"" . $colspan . "\">" . getLngt("Externe Daten") . "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
   $storedRemoteFiles .= "  <select class=\"f8np1\" name=\"f_ftp_servername\" onchange=\"ftpSelectEnvironment();\">";
   $storedRemoteFiles .= "    <option value=\"\">" . getLngt("Keine Auswahl") . "</option>";
   for ($k = 0; $k < $ftpServerListArrayLen; $k++) :
       $storedRemoteFiles .= "    <option value=\"" . $ftpServerListArray[$k] . "\" " . ($f_ftp_servername == $ftpServerListArray[$k] ? "selected" : "") . ">" . getLngt($ftpServerListArray[$k]) . "</option>";
   endfor;
   $storedRemoteFiles .= "  </select>&nbsp;&nbsp;";
   $storedRemoteFiles .= "  <select class=\"f8np1\" name=\"f_ftp_ssl\" onchange=\"ftpSelectEnvironment();\">";
   $storedRemoteFiles .= "    <option value=\"\" " . ($f_ftp_ssl == "" ? "selected" : "") . ">" . getLngt("Protokoll:") . "</option>";
   $storedRemoteFiles .= "    <option value=\"0\" " . ($f_ftp_ssl == "0" ? "selected" : "") . ">" . getLngt("FTP") . "</option>";
   $storedRemoteFiles .= "    <option value=\"1\" " . ($f_ftp_ssl == "1" ? "selected" : "") . ">" . getLngt("FTPS") . "</option>";
   $storedRemoteFiles .= "    <option value=\"2\" " . ($f_ftp_ssl == "2" ? "selected" : "") . ">" . getLngt("SFTP") . "</option>";
   $storedRemoteFiles .= "  </select>";
   $storedRemoteFiles .= "</td></tr>";
   $storedRemoteFiles .= "<tr><td colspan=\"" . $colspan . "\"><br></td></tr>";
   $storedRemoteFiles .= "<tr><td class=\"f12bn1\" colspan=\"" . $colspan . "\">" . getLngt("Verzeichnis") . ":&nbsp;&nbsp;" . ($ftp_path_dest != "" ? "../" . $ftp_path_dest : "./") . "</td></tr>";
   $storedRemoteFiles .= "<tr><td colspan=\"" . $colspan . "\"><br></td></tr>";

   // Define table header
   $storedRemoteFiles .= "<tr><td>" . getLngt("FTP-Download") . "&nbsp;&nbsp;&nbsp;&nbsp;</td><td>" . getLngt("Dateiname") . "&nbsp;&nbsp;&nbsp;&nbsp;</td><td>" . getLngt("Löschen") . "</td></tr>";
   $storedRemoteFiles .= "<tr><td colspan=\"" . $colspan . "\"><br></td></tr>";

   if ($ftpCurrentSelectedServerAccess) :
      if ($tmpErrNo == "0") :      
         // Define table body from array
         $fileNamesLen = count($fileNames);
         for ($j = 0; $j < $fileNamesLen; $j++) :
               $storedRemoteFiles .= "<tr>";
               $storedRemoteFiles .= "<td align=\"center\"><a href=\"javascript:ftpDownload('" . $fileNames[$j] . "');\">"
                                          . "<img src=\"../images/arrow_left.png\" border=\"0\" height=\"10\" width=\"25\">"
                                          . "</a>" . "&nbsp;&nbsp;&nbsp;&nbsp;</td>";
               $storedRemoteFiles .= "<td>" . $fileNames[$j] . "&nbsp;&nbsp;&nbsp;&nbsp;</td>";
               $storedRemoteFiles .= "<td align=\"center\"><a href=\"javascript:ftpDelete('" . $fileNames[$j] . "');\">"
                                          . "<img src=\"../images/trash.jpg\" border=\"0\" height=\"13\" width=\"8\">" 
                                          . "</a>" . "&nbsp;&nbsp;&nbsp;&nbsp;</td>";
               $storedRemoteFiles .= "</tr>";
         endfor;
      else :
         // "$f_ftp_servername" contains the FTP server name AND/OR the "IMPORT TYPE" (UTA, APO, ...) NOT being associated to a FTP data set stringently (!!!)
         if ($f_ftp_servername != "" && $ftp_server == "") :
            $storedRemoteFiles .= "<tr><td class=\"f10bp1_blue\" colspan=\"" . $colspan . "\">" . getLngt("Keine FTP-Konfigurationsdaten hinterlegt") .  "</td></tr>";
         else :
            $storedRemoteFiles .= "<tr><td class=\"f10bp1_red\" colspan=\"" . $colspan . "\">" . getLngt($tmpErrDesc) .  "</td></tr>";
         endif;
      endif;
   endif;
   $storedRemoteFiles .= "</table>";
endif;
?>


<html>
<head>
<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; ?>

function finishPage(f_act_value) {  
  document.forms[0].f_act.value=f_act_value;
  document.forms[0].submit();
};

function ftpSelectEnvironment() {
  document.forms[0].ftp_server.value = '';
  document.forms[0].ftp_user_name.value = '';
  document.forms[0].ftp_user_pass.value = '';
  document.forms[0].ftp_path_dest.value = '';
  document.forms[0].submit();
}

function ftpUpload(fileName) {
  document.forms[0].f_ftp_filename.value = fileName;
  finishPage('ftpUpload');
};

function ftpDownload(fileName) {
  document.forms[0].f_ftp_filename.value = fileName;
  finishPage('ftpDownload');
};

function ftpDelete(fileName) {
  document.forms[0].f_ftp_filename.value = fileName;
  finishPage('ftpDelete');
};

function removeImportfile(fileName) {
  if (confirm('<?php echo getLngt("Importdatei") ?> ' + fileName + ' <?php echo getLngt("entfernen?") ?>')) {
     document.forms[0].f_importFile.value = fileName;
     finishPage('removeImportfile');
  };
};

function finishPageUpload(f_act_value) {  
  document.forms[1].f_act.value=f_act_value;
  document.forms[1].submit();
};
-->
</script>

</head>

<body onLoad="<?php echo $phpCurrentNavigationOnLoad ?>displayStatusMessage();">
	
<?php echo $phpMenuOut ?>
<?php echo $phpReducedMenuOut ?>
<?php echo $phpPageTitelOut ?>

<div class="maincontent" name="maincontent" id="maincontent">

  <div>
    <form name="import_form" action="../import/data_transfer.php" method="post">
      <input type="hidden" name="f_act" value="">
      <?php echo $phpCurrentNavigationInputHidden ?>
      <input type="hidden" name="deactivateMenu" value="<?php echo ec($deactivateMenu) ?>">
      <input type="hidden" name="docLocalDirCurrent" value="<?php echo $docLocalDirCurrent; ?>">
      <input type="hidden" name="f_importFile" value="">
      <input type="hidden" name="f_ftp_filename" value="">      
      <input type="hidden" name="ftp_server" value="<?php echo $ftp_server; ?>">
      <input type="hidden" name="ftp_user_name" value="<?php echo $ftp_user_name; ?>">
      <input type="hidden" name="ftp_user_pass" value="<?php echo $ftp_user_pass; ?>">
      <input type="hidden" name="ftp_path_dest" value="<?php echo urlencode($ftp_path_dest); ?>">
      
      <input type="hidden" name="objType" value="<?php echo urlencode($objType); ?>">
      <input type="hidden" name="objId" value="<?php echo urlencode($objId); ?>">
      
      <?php echo htmlDivLineSpacer("10px"); ?>
      
      <div>
        <table width="98%" border="1">
        	<tr>
        		<td width="49%" style="vertical-align:top;">
              <?php echo $storedImportFiles; ?>
            </td>
        		<td width="49%" style="vertical-align:top;">
              <?php echo $storedRemoteFiles; ?>
            </td>
          </tr>
        </table>    
      </div>
    </form>
  </div>
  
  <?php echo htmlDivLineSpacer("30px"); ?>
  
  <?php if ($specialStaticDirActive || authCheckEmployeeRights($emp_id, "22")) : ?>
  <div>
    <form name="upload_file" action="../import/data_transfer.php" enctype="multipart/form-data" method="post">
    <!--  <form name="upload_file" action="../import/upload_file.php" enctype="multipart/form-data" method="post"> -->
      <input type="hidden" name="f_act" value="">
      <p><?php echo getLngt("W&auml;hlen Sie eine lokale Datei auf Ihrem Rechner aus:") ?><br>
        <input type="hidden" name="MAX_FILE_SIZE" value="4000000">
        <input name="f_uploadFile" type="file" size="50" accept="text/*">
        <input type="hidden" name="docLocalDirCurrentUpload" value="<?php echo $docLocalDirCurrent; ?>">
        <input type="hidden" name="objType_upload" value="<?php echo urlencode($objType); ?>">
        <input type="hidden" name="objId_upload" value="<?php echo urlencode($objId); ?>">
        <input type="button" value="Upload" onClick="finishPageUpload('uploadFile');">
      </p>
      <br><br>
      <?php echo $importFileStatusMsg; ?>
    </form>
  </div>
  <?php endif; ?>

</div>

</body>

</html>