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

include_once ("../include/mcglobal.inc.php");

ini_set('memory_limit', '256M');

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


$autoMode = false;
if (!isset($argv[1]) || $argv[1] == "") :
   $isCron = false;
   include_once ("../include/auth.inc.php");

   getSecHttpVars("1",array("f_act", "f_exp_category", "f_delimiter", "f_parname", "f_parstr_active", "f_parstr_nodelimiter", "f_parstr_substrmode", "f_headline",
                            "f_expp_id", "f_parname_export", "f_fileName", "f_parname_new", "f_fillUpChar", "f_exportFileToDelete",
                            "f_bolchars", "f_eolchars", "f_bofchars", "f_eofchars", "f_status_filter", "f_vht_filter",
                            "day_from", "month_from", "year_from", "day_to", "month_to", "year_to", "f_cs_eid_filter",
                            "cscIdRoot", "customerId", "cscIdActual", "adminInterfacePassword", "f_export_mode", "f_jbp_filter", 
                            "f_grpId", "f_csId", "changeModfyStateDisabled", "deactivateMenu", "httpMethod"));
   $autoMode = true;
   // Check for authentication access and granted rights
   $usrAccessArray["hq"] = "1"; $usrAccessArray["cs"] = "1";
   authCheckForAccess($hq_id, $usr_id, $emp_id, "1", $customerId, $cscIdRoot, $cscIdActual);
   $empHasAccess_06 = authCheckEmployeeRights($emp_id, "6");
   $empHasAccess_26 = authCheckEmployeeRights($emp_id, "26");
   $empHasAccess_05 = authCheckEmployeeRights($emp_id, "5");
else :
   error_reporting(E_ERROR | E_WARNING | E_PARSE);

   // Init parameters
   $f_act = ""; $f_exp_category = ""; $f_delimiter = ""; $f_parname = ""; $f_parstr_active = ""; $f_parstr_nodelimiter = ""; $f_parstr_substrmode = "";
   $f_expp_id = ""; $f_parname_export = ""; $f_fileName = ""; $f_parname_new = ""; $f_fillUpChar = ""; $f_exportFileToDelete = ""; 
   $f_bolchars = ""; $f_eolchars = ""; $f_bofchars = ""; $f_eofchars = ""; $f_status_filter = ""; $f_vht_filter = "";
   $day_from = ""; $month_from = ""; $year_from = ""; $day_to = ""; $month_to = ""; $year_to = ""; $f_cs_eid_filter = "";
   $cscIdRoot = ""; $customerId = ""; $cscIdActual = ""; $adminInterfacePassword = ""; $f_export_mode = ""; $f_jbp_filter = "";
   $f_grpId = ""; $f_csId = ""; $deactivateMenu = ""; $httpMethod = "";
   $hq_id = ""; $usr_id = ""; $specialJbPayment = ""; $jbpc_id = ""; $changeModfyStateDisabled = "";

   $isCron = true;
   if ($argv[1] == "acapella7890") : $autoMode = true; endif;
   if ($autoMode) :
      if (isset($argv[2]) && $argv[2] != "")   : $hq_id                    = $argv[2]; endif;
      if (isset($argv[3]) && $argv[3] != "")   : $usr_id                   = $argv[3]; endif;
      if (isset($argv[4]) && $argv[4] != "")   : $dummy_01                 = $argv[4]; endif;
      if (isset($argv[5]) && $argv[5] != "")   : $f_act                    = $argv[5]; endif;
      if (isset($argv[6]) && $argv[6] != "")   : $f_exp_category           = $argv[6]; endif;
      if (isset($argv[7]) && $argv[7] != "")   : $f_delimiter              = $argv[7]; endif;
      if (isset($argv[8]) && $argv[8] != "")   : $f_parname                = $argv[8]; endif;
      if (isset($argv[9]) && $argv[9] != "")   : $f_parname_export         = $argv[9]; endif;
      if (isset($argv[10]) && $argv[10] != "") : $f_fileName               = $argv[10]; endif;
      if (isset($argv[11]) && $argv[11] != "") : $day_to                   = $argv[11]; endif;
      if (isset($argv[12]) && $argv[12] != "") : $month_to                 = $argv[12]; endif;
      if (isset($argv[13]) && $argv[13] != "") : $year_to                  = $argv[13]; endif;
      if (isset($argv[14]) && $argv[14] != "") : $f_cs_eid_filter          = $argv[14]; endif;
      if (isset($argv[15]) && $argv[15] != "") : $day_from                 = $argv[15]; endif;
      if (isset($argv[16]) && $argv[16] != "") : $month_from               = $argv[16]; endif;
      if (isset($argv[17]) && $argv[17] != "") : $year_from                = $argv[17]; endif;
      if (isset($argv[18]) && $argv[18] != "") : $customerId               = $argv[18]; endif;
      if (isset($argv[19]) && $argv[19] != "") : $f_headline               = $argv[19]; endif;
      if (isset($argv[20]) && $argv[20] != "") : $f_jbp_filter             = $argv[20]; endif;
      if (isset($argv[21]) && $argv[21] != "") : $specialJbPayment         = $argv[21]; endif;
      if (isset($argv[22]) && $argv[22] != "") : $jbpc_id                  = $argv[22]; endif;
      if (isset($argv[23]) && $argv[23] != "") : $f_status_filter          = $argv[23]; endif;
      if (isset($argv[24]) && $argv[24] != "") : $f_export_mode            = $argv[24]; endif;
      if (isset($argv[25]) && $argv[25] != "") : $f_vht_filter             = $argv[25]; endif;
      if (isset($argv[26]) && $argv[26] != "") : $f_parstr_active          = $argv[26]; endif;
      if (isset($argv[27]) && $argv[27] != "") : $f_parstr_nodelimiter     = $argv[27]; endif;
      if (isset($argv[28]) && $argv[28] != "") : $f_parstr_substrmode      = $argv[28]; endif;
      if (isset($argv[29]) && $argv[29] != "") : $f_expp_id                = $argv[29]; endif;
      if (isset($argv[30]) && $argv[30] != "") : $f_parname_new            = $argv[30]; endif;
      if (isset($argv[31]) && $argv[31] != "") : $f_fillUpChar             = $argv[31]; endif;
      if (isset($argv[32]) && $argv[32] != "") : $f_exportFileToDelete     = $argv[32]; endif;
      if (isset($argv[33]) && $argv[33] != "") : $f_bolchars               = $argv[33]; endif;
      if (isset($argv[34]) && $argv[34] != "") : $f_eolchars               = $argv[34]; endif;
      if (isset($argv[35]) && $argv[35] != "") : $f_bofchars               = $argv[35]; endif;
      if (isset($argv[36]) && $argv[36] != "") : $f_eofchars               = $argv[36]; endif;
      if (isset($argv[37]) && $argv[37] != "") : $changeModfyStateDisabled = $argv[37]; endif;
   endif;

   // Check parameters to continue the execution
   if (!$autoMode) : die("ACCESS DENIED!"); endif;
   $hq_mnemonic = getFieldValueFromId("headquarters","hq_id",$hq_id,"hq_mnemonic");
   if ($hq_mnemonic == "") : die("PLEASE DEFINE HEADQUARTERS!"); endif;
   $usr_type = getFieldValueFromId("user","usr_id",$usr_id,"usr_type");
   if ($usr_type == "") : die("PLEASE DEFINE USER!"); endif;
   $userTypeName = "hq";
   if ($usr_type == "2") : 
      $userTypeName = "cs";
      $cscIdRoot = getFieldValueFromId("customer","cs_id",$customerId,"csc_id");
      $cscIdActual = $cscIdRoot;  // Automatic export by cron
   endif;

   // Define global parameters
   defineGlobalParameters($hq_id);
   
   $specialOutputFormat = "";
   $convertOutputArray = array();
   $summationFieldArray = array();
   $summationFieldArray2 = array();
   $deactivateMenu = "1";
   $empHasAccess_06 = true;
//   $userTypeName = "hq";
   if ($day_from == "") : $day_from = "01"; endif;
   if ($month_from == "") : $month_from = "01"; endif;
   if ($year_from == "") : $year_from = "2004"; endif;   

   // Define function for CRON because "auth.inc.php" is not included !!!!
   function authCheckEmployeeRights($emp_id, $menuModeId, $referer = "") {
     return TRUE;
   }

/*
echo "----------- \n";
echo "customerId: " . $customerId . "\n";
echo "cscIdRoot: " . $cscIdRoot . "\n";
echo "cscIdActual: " . $cscIdActual . "\n";
echo "----------- \n";
echo "usr_type: " . $usr_type . "\n";
echo "userTypeName: " . $userTypeName . "\n";
echo "----------- \n";
echo "hq_id: " . $hq_id . "\n";
echo "usr_id: " . $usr_id . "\n";
echo "dummy_01: " . $dummy_01 . "\n";
echo "f_act: " . $f_act . "\n";
echo "f_exp_category: " . $f_exp_category . "\n";
echo "f_delimiter: " . $f_delimiter . "\n";
echo "f_parname: " . $f_parname . "\n";
echo "f_parname_export: " . $f_parname_export . "\n";
echo "f_fileName: " . $f_fileName . "\n";
echo "day_to: " . $day_to . "\n";
echo "month_to: " . $month_to . "\n";
echo "year_to: " . $year_to . "\n";
echo "f_cs_eid_filter: " . $f_cs_eid_filter . "\n";
echo "day_from: " . $day_from . "\n";
echo "month_from: " . $month_from . "\n";
echo "year_from: " . $year_from . "\n";
echo "customerId: " . $customerId . "\n";
echo "f_jbp_filter: " . $f_jbp_filter . "\n";
echo "specialJbPayment: " . $specialJbPayment . "\n";
echo "jbpc_id: " . $jbpc_id . "\n";
echo "f_status_filter: " . $f_status_filter . "\n";
echo "f_export_mode: " . $f_export_mode . "\n";
echo "f_vht_filter: " . $f_vht_filter . "\n";
echo "changeModfyStateDisabled: " . $changeModfyStateDisabled . "\n";
echo "----------- \n";
*/
endif;

if ($userTypeName == "hq" && !($empHasAccess_06 || $empHasAccess_26)) : gotoReferer("1"); endif;

$pageTitel = "DATENEXPORT";
include_once ("../include/ftp.inc.php");
if (!$isCron) :
   include_once ("../admin/menu.php");
endif;
include_once ("../include/html.inc.php");
include_once ("../include/jb_detail_history.inc.php");

// Include special export functions for special customers
if ($userTypeName == "cs") :
   include ("../export/exportrequests_special.inc.php");
endif;

if (!$isCron) :
   if ($userTypeName == "cs" && $cscIdActual != "") :
      $tmpFields = getFieldsValueFromId("costcenter","csc_id",$cscIdActual,array("csc_path","csc_name"));
      $cscPathActual = $tmpFields[0];
      $cscNameActual = $tmpFields[1];   
   endif;
endif;

// Get enabled special function(s) for the current customer
$specialFunctionsArray = array();
if ($userTypeName == "cs") :
   $getIncludeFileNameSuffix = getParameterValue("0", "EXPORT_SPECIAL_FUNCTIONNAME_SUFFICES_CS_" . $customerId, "0");
   if ($getIncludeFileNameSuffix != "") : 
      $specialFunctionsArray = explode(",", $getIncludeFileNameSuffix);
   endif;
endif;
$specialFunctionsArrayLen = count($specialFunctionsArray);


// Wrapper to call one of the enabled special export functions for a customer
function specialExportInterface ($customerId, $funcNo = "1", $dbConnection = "") {
	global $db, $userTypeName;
	$retArray = array();
  if ($userTypeName == "cs" && $customerId != "" && is_numeric($customerId) && $customerId > "0") :
     if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;
     $functionName = "special_export_" . pad($funcNo,2);
     if (function_exists($functionName)) :
        $retArray = call_user_func_array($functionName, array($dbConnection));
     endif;
  endif;
  return $retArray;
}



// *******************
// * Initializations *
// *******************

// Initialize the http-values
if ($f_exp_category == "") : $f_exp_category = "0"; endif;      // Exportcategory (customer, courier, job, ...)
if ($userTypeName == "hq") :     // Execute only if headquarter exports !!!
   if ($f_delimiter == "") : $f_delimiter = "|"; endif;            // Delimiter
endif;
$f_delimiter = trim($f_delimiter);
if ($f_parname == "") : $f_parname = "DEFAULT"; endif;          // Name of the special parameter-configuration (unique for hq)
if ($f_expp_id == "") : $f_expp_id = "0"; endif;                // Id of the parameter
if ($f_fillUpChar == "") : $f_fillUpChar = " "; endif;          // Fill-up-sign of exporting-fields with bigger length
if ($f_bolchars == "") : $f_bolchars = ""; endif;               // Chars at the beginning of line
if ($f_eolchars == "") : $f_eolchars = ""; endif;               // Chars at the end of line (if "" then new line (line-feed))
if ($f_bofchars == "") : $f_bofchars = ""; endif;               // Chars at the end of file (if "" then no eof-sign)
if ($f_eofchars == "") : $f_eofchars = ""; endif;               // Chars at the end of file (if "" then no eof-sign)
if ($customerId == "") : $customerId = "0"; endif;              // Id of the customer
if ($changeModfyStateDisabled == "") : $changeModfyStateDisabled = ""; endif;  // "1" <=> Export call does NOT change "db row state" regarding modification state ["cmp_modify_status"] [Modification is enabled by default!]
$configPassword = "314%415";                                    // Password to administrate formulars, etc.
$abortExportProcess = false;                                    // Flag for executing export process
$postExportPar = "";                                            // Init for potential pre- and/or post-export
$jbIdReal = array();                                            // Use for setting export time if primary key "jb_id" will be changed in "convertRowToArray()" in "inc_dbfields2array.inc.php"
mcIsSet($specialJbPayment);

// Get global mode of usage
$globalParUseRelatedCustomer = getParameterValue("0", "GLOBAL_USE_RELATED_CUSTOMER", "0");

// Get global export path
$globalExportPath = getParameterValue("0", "EXPORT_PATH", "0");
if ($globalExportPath == "") : $globalExportPath = getParameterValue("0", "EXPORT_PATH", "0"); endif;
if ($globalExportPath == "") : $globalExportPath = "../export/download/"; endif;

// Preset for special customer by default
if ($f_grpId == "") : $f_grpId = getParameterValue($emp_id, "MASK_DISPOSITION_INIT_GROUP", $hq_id); endif;
if ($f_csId == "") : $f_csId = getParameterValue($emp_id, "MASK_DISPOSITION_INIT_CS", $hq_id); endif;

// Flag for export headline
mcIsSet($f_headline);
if ($f_headline != "1") : $f_headline = "0"; endif;

// Check existence of special EID
$f_cs_eid_filter = trim($f_cs_eid_filter);                      // Export filter => ONLY data of the customer with the specified EID
if ($f_cs_eid_filter != "") :
   if (!existsEntry("customer",array("cs_eid",$f_cs_eid_filter,"hq_id",$hq_id))) :
      $abortExportProcess = true;  // NO export of any data!
      $tmpStatusMessage = "Der spezifizierte Kunde konnte nicht gefunden werden! Ein Export erfolgte NICHT!";
   endif;
   
   // Start pre processing for a special related customer
   if (!$isCron) :
      if ($f_export_mode == "special" && $empHasAccess_05) :
         $preExportCsIdRelated = getFieldValueFromId("customer","cs_eid",$f_cs_eid_filter,"cs_id");  // Get "cs_id" from "cs_eid"
         $path = getAbsoluteSystemPath();
         $cmd = "php " . $path . "/export/pre_export.php " . $preExportCsIdRelated . " &";
         $cmdOutput = null;
         exec($cmd, $cmdOutput);
         list($f_fileName,$f_exp_category,$f_parname,$f_parname_export,$specialJbPayment,$postExportPar) = $cmdOutput;
         if ($f_fileName == "" || $f_exp_category == "" || !is_numeric($f_exp_category) || $f_parname == "" || $f_parname_export == "" || $specialJbPayment == "" || !is_numeric($specialJbPayment)) :
            $abortExportProcess = true;  // NO export of any data!
         endif;
      endif;
   endif;
endif;

if ($f_status_filter == "") :                                   // Status-filter (new row, modified row, ...)
   $f_status_filter = "0";
   if ($f_exp_category == "0" || $f_exp_category == "1" || $f_exp_category == "2" || $f_exp_category == "3") :
       $f_status_filter = "3";
   endif;
endif;

if ($f_vht_filter == "") : $f_vht_filter = array(); endif;      // Filter for vehicle of the courier for exporting ALL or ONLY the specified vehicle types

// Filter for payment modes
if ($f_jbp_filter == "") : $f_jbp_filter = ""; endif;
if (!$abortExportProcess && $f_exp_category == "9") :
   // A special customer has to be selected
   if ($f_cs_eid_filter != "") :
      $jbpCsId = getFieldValueFromId("customer","cs_eid",$f_cs_eid_filter,"cs_id");  // Get "cs_id" from "cs_eid"
      if ($jbpCsId != "" && is_numeric($jbpCsId)) :
         $f_jbp_filter = trim($f_jbp_filter);
         if ($f_jbp_filter != "") : $f_jbp_filter = pad($f_jbp_filter, 2); endif;
         if ($f_jbp_filter != "") :
            $cat09_paymentTypesRequested = getObjectBasedParameterValue("EXPORT_CAT_09_JBPMODES_" . $f_jbp_filter . "_CS", $jbpCsId, $hq_id);
            if ($cat09_paymentTypesRequested == "") : 
                // Get group ID of the current customer
                $tmpGroupString = getFieldValueFromId("customer","cs_id",$jbpCsId,"cs_group");
                $tmpGrpIdOfCsCurrArray = spliti(",", $tmpGroupString);
                $tmpGrpIdOfCsCurrArrayLen = count($tmpGrpIdOfCsCurrArray);
                if ($tmpGrpIdOfCsCurrArrayLen > 0) :
                   $tmpGrpIdOfCsCurr = $tmpGrpIdOfCsCurrArray[1];  // .... because of leading comma sign
                endif;
                if ($tmpGrpIdOfCsCurr != "") :
                   $cat09_paymentTypesRequested = getObjectBasedParameterValue("EXPORT_CAT_09_JBPMODES_" . $f_jbp_filter . "_GRP", $tmpGrpIdOfCsCurr, $hq_id);
                   if ($cat09_paymentTypesRequested == "") :
                      $abortExportProcess = true;  // NO export of any data!
                      $tmpStatusMessage = "Es muss ein Eintrag für die Zahlarten existieren!";
                   endif;
                endif;
             endif;
         else :
            $abortExportProcess = true;  // NO export of any data!
            $tmpStatusMessage = "Es muss ein Eintrag für die Zahlarten existieren!";
         endif;
      endif;
   else :
      $abortExportProcess = true;  // NO export of any data!
      $tmpStatusMessage = "Für den Einnahmenexport muss ein Eintrag für einen speziellen Kunden existieren!";
   endif;
endif;

// Filter for courier business volume export
if (!$abortExportProcess && $f_exp_category == "8") :
   // A special customer has to be selected
   if ($f_cs_eid_filter == "") :
      $abortExportProcess = true;  // NO export of any data!
      $tmpStatusMessage = "Es muss ein Eintrag für einen speziellen Kunden existieren!";
   endif;
endif;

// Check for executing export
if ($abortExportProcess) :
    // NO export of any data!
    if ($f_act == "export" || substr($f_act,0,15) == "special_export_") :
       $f_act = "";
       $statusMessage = $tmpStatusMessage;
    endif;
endif;


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

$frameName = "maincontent";
if ($userTypeName == "cs") : $frameName = "frame_content"; endif;  // name of the frame

// name of the exportfile (with current date, category and text "export")
// $currCategoryName = getFieldValueFromId("exportcategory","expc_id",$f_exp_category,"expc_name");   // category-name for filename
if ($f_fileName == "") : $f_fileName = getDateTime("1") . "_export"; endif;
if (trim($f_parname_new) != "") : $f_parname = $f_parname_new; endif;    // new name of the special parameter-configuration

// If called by GET method then decode URL parameters
if ($httpMethod == "get") :
   $f_parname = urldecode($f_parname);
   $f_parname_new = urldecode($f_parname_new);
   $f_parname_export = urldecode($f_parname_export);
endif;

// Initialize other values
$idArray = array();		  			// IDs of the category-fields (table exportcategoryfields)
$fieldArray = array();				// Fieldnames (e.g. "cmp.cmp_comp", "usr.usr_email", etc.)
$titleArray = array();				// Titles (e.g. "Company", "Email", etc.)
$supersetFieldString = "";
$dbFieldTypeArray = defineOutputFormats();

// Get table names (currently only for make jobs persistent in "jb_history_data")
getDBNames($dbhistory);

// Check range of date. All fields have to be set
if ($day_from == "" || $month_from == "" || $year_from == "" || 
    $day_to == "" || $month_to == "" || $year_to == "") :
    
    // Initialize date-ranges to the current date
    $fromDateRange = getDateTime("3") . " 00:00:00";
    $toDateRange = getDateTime("3") . " 23:59:59";
    
    $day_from = getDateTime("day");
    $month_from = getDateTime("month");
    $year_from = getDateTime("year");
    $day_to = getDateTime("day");
    $month_to = getDateTime("month");
    $year_to = getDateTime("year");
else :
    $fromDateRange = $year_from . "-" . pad($month_from,2) . "-" . pad($day_from,2) . " 00:00:00";
    $toDateRange = $year_to . "-" . pad($month_to,2) . "-" . pad($day_to,2) . " 23:59:59";
endif;


// *************
// * FUNCTIONS *
// *************

// Sets the export status by initialization and sets the current export date
function setExportValues() {
  global $db, $userTypeName, $f_exp_category, $f_status_filter, $rowArray, $hq_id, $f_act, $usr_id;
  global $dbhistory, $dbh_jb, $dbh_tr, $dbh_trs, $dbh_cdt, $dbh_jbc, $dbh_jbp;
  global $jobentry, $tourentry, $jobcosts, $courierentry, $employeeentry;
  global $isCron, $postExportPar, $jbIdReal, $changeModfyStateDisabled;
  $retBool = FALSE;  

  // Execute if headquarter export only AND check for NOT changing the modification state of the db row !!!
  if ($userTypeName == "hq" && $changeModfyStateDisabled != "1") :

     if ((($f_exp_category == "1" || $f_exp_category == "2" || $f_exp_category == "3") && $f_status_filter != "0") ||
          ($f_exp_category == "4" || $f_exp_category == "5" || $f_exp_category == "6" || $f_exp_category == "7" || $f_exp_category == "8" || $f_exp_category == "9")) :

        // Get the current time
        $currentTime = getDateTime("0");

        // Number of rows exported
        $rowArrayLen = count($rowArray);
  
        // Initialize array to store IDs of rows to be exported for the export log
        $arrayOfExportedIds = array();  

        TA("B");

        // Customers or couriers
        if ($f_exp_category == "1" || $f_exp_category == "2") :
           // Update rows
           for ($j = 0; $j < $rowArrayLen; $j++) :
               $sqlquery = "UPDATE company SET cmp_export_time = '" . $currentTime . "', cmp_modify_status = '0' WHERE cmp_id = '" . $rowArray[$j]["cmp_id"] . "'";
               $result = $db->query($sqlquery);
               if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
               $arrayOfExportedIds[] = $rowArray[$j]["cmp_id"];
           endfor;
        endif;

        // Courier vehicles
        if ($f_exp_category == "3") :
           for ($j = 0; $j < $rowArrayLen; $j++) :
               // Check for update or removement
               if ($rowArray[$j]["crvh_modify_status"] == ROW_EDIT_STATUS_DELETE || $rowArray[$j]["crvh_modify_status"] == "3") :
                  // delete couriervehicle
                  $whereClause = "crvh_id = '" . $rowArray[$j]["crvh_id"] . "'";
                  deleteStmt("couriervehicle",$whereClause);
               else :                        
                  $sqlquery = "UPDATE couriervehicle SET crvh_export_time = '" . $currentTime . "', crvh_modify_status = '0' WHERE crvh_id = '" . $rowArray[$j]["crvh_id"] . "'";
                  $result = $db->query($sqlquery);
                  if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
                  $arrayOfExportedIds[] = $rowArray[$j]["crvh_id"];
               endif;
           endfor;
        endif;
   
        // Jobs
        if ($f_exp_category == "4" || $f_exp_category == "5" || $f_exp_category == "6") :
           // Update rows
           for ($j = 0; $j < $rowArrayLen; $j++) :
               if (count($jbIdReal) > 0 && is_numeric($jbIdReal[$rowArray[$j]["jb_id"]])) :
                  $rowArray[$j]["jb_id"] = $jbIdReal[$rowArray[$j]["jb_id"]];  // Get back the real jb_id
               endif;
               $sqlquery = "UPDATE job SET jb_export_time = '" . $currentTime . "' WHERE jb_id = '" . $rowArray[$j]["jb_id"] . "'";
               $result = $db->query($sqlquery);
               if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
               $arrayOfExportedIds[] = $rowArray[$j]["jb_id"];

               // Write logdata into log database
               writeToLogDB("164",$hq_id,$rowArray[$j]["jb_id"],$usr_id,"","","","EXPORT_TIME=" . $currentTime);
           endfor;
        endif;
   
        if ($f_exp_category == "7") :
           // Values paid by the endcustomer
           for ($j = 0; $j < $rowArrayLen; $j++) :
               $sqlquery = "UPDATE jobpayment SET jbp_export_time = '" . $currentTime . "' WHERE jb_id = '" . $rowArray[$j]["jb_id"] . "' AND (ISNULL(jbp_export_time) OR (jbp_export_time = '0000-00-00 00:00:00'))";
               $result = $db->query($sqlquery);
               if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
               $arrayOfExportedIds[] = $rowArray[$j]["jb_id"];
           endfor;
        endif;
   
        if ($f_exp_category == "8") :
           // Update rows [ATTENTION: Presently the same procedure as for categories 5 and 6]
           for ($j = 0; $j < $rowArrayLen; $j++) :
               if (count($jbIdReal) > 0 && is_numeric($jbIdReal[$rowArray[$j]["jb_id"]])) :
                  $rowArray[$j]["jb_id"] = $jbIdReal[$rowArray[$j]["jb_id"]];  // Get back the real jb_id
               endif;
               $sqlquery = "UPDATE job SET jb_export_time = '" . $currentTime . "' WHERE jb_id = '" . $rowArray[$j]["jb_id"] . "'";
               $result = $db->query($sqlquery);
               if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
               $arrayOfExportedIds[] = $rowArray[$j]["jb_id"];
           endfor;
        endif;
   
        if ($f_exp_category == "9") :
           // Values paid by the endcustomer
           for ($j = 0; $j < $rowArrayLen; $j++) :
               // Set export timestamp for all associated entries in "jobpayment"
               updateStmt("jobpayment", "", "", array("jbp_export_time", $currentTime), "jbpc_id = '" . $rowArray[$j]["jbpc_id"] . "'");
               // Set export timestamp for 
               $sqlquery = "UPDATE jobpaymentcollection SET jbpc_export_time = '" . $currentTime . "' WHERE jbpc_id = '" . $rowArray[$j]["jbpc_id"] . "' AND (ISNULL(jbpc_export_time) OR (jbpc_export_time = '0000-00-00 00:00:00'))";
               $result = $db->query($sqlquery);
               if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
               $arrayOfExportedIds[] = $rowArray[$j]["jbpc_id"];
           endfor;
        endif;
  
        // Insert all IDs of the exported rows into the export log
        if (count($arrayOfExportedIds) > 0) :
           $stringOfExportedIds = implode(",", $arrayOfExportedIds);
           insertStmt("exportlog", array("expc_id", $f_exp_category, "exl_rows", $stringOfExportedIds, "exl_exporttime", $currentTime, "usr_id", $usr_id));
           $exl_id_new = getLastInsertID(); 
        endif;  
  
        TA("C");
        TA("E");


        // Write historic job data
        if ($f_exp_category == "4" || $f_exp_category == "5" || $f_exp_category == "6") :
           $arrayOfExportedIdsLen = count($arrayOfExportedIds);
           if ($arrayOfExportedIdsLen > 0) :

              $f_act_rem = $f_act;
              $f_act = "";

              // Call script to write "job2"
              $call_counter = "1";
              $path = getAbsoluteSystemPath();
              $mcDebugExportErrLogFile = $path . "/log/job2exec_" . $hq_id . "_err.stdout+err";
              $cmd = "php " . $path . "/export/export4job2.php acapella7890 " . $hq_id . " " . $usr_id . " " . $exl_id_new . " " . $call_counter . " > " . $mcDebugExportErrLogFile . " 2>&1 &";
              system($cmd);
              /*
              $cmd = "php ../export/export4job2.php acapella7890 " . $hq_id . " " . $usr_id . " " . $exl_id_new . " " . $call_counter . " > " . $mcDebugExportErrLogFile . " 2>&1 &";
              $cmdOutput = null;
              exec($cmd, $cmdOutput);
              */

/*
// $mcDebugExportLogFile = "../log/job2exec.log";
$mcDebugExportLogFile = "../log/job2exec_" . $hq_id . ".log";
writeToFile($mcDebugExportLogFile, "----------------------------------------------------------------------------------------------");
writeToFile($mcDebugExportLogFile, "#JobsExported: " . $arrayOfExportedIdsLen);
              for ($x = 0; $x < $arrayOfExportedIdsLen; $x++) :

                  $job_id = $arrayOfExportedIds[$x];
                  $tmpDelimiter = "-;-";
writeToFile($mcDebugExportLogFile, $job_id);
                  // [1.] Store view of the headquarters and store raw data of the job (also headquarters view)
                  $jobentry = ""; $tourentry = ""; $jobcosts = ""; $courierentry = ""; $employeeentry = "";
                  $userTypeName = "hq";
                  $tmpJobDataArray = getJobSnapshot($job_id, "1");
                  $currentJobRawData = $tmpJobDataArray[0];
                  $currentJobParameterState = $tmpJobDataArray[1];
                  $currentJobRawData = str_replace('\'', '\\\'', $currentJobRawData);
                  $jbHistoryData = $currentJobParameterState . $tmpDelimiter . $jobentry . $tmpDelimiter . $tourentry
                                 . $tmpDelimiter . $jobcosts . $tmpDelimiter . $courierentry . $tmpDelimiter . $employeeentry;
                  $jbHistoryData = str_replace('\'', '\\\'', $jbHistoryData);

                  // $sqlquery = "UPDATE job SET jb_history_data = '" . $jbHistoryData . "' WHERE jb_id = '" . $job_id . "'";
                  // $result = $db->query($sqlquery);
                  // if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
                  
                  $currentJobRawData = escapeMysqlForBinary(compress($currentJobRawData));
                  $jbHistoryData = escapeMysqlForBinary(compress($jbHistoryData));
                  
                  if (existsEntry("job2",array("jb_id",$job_id))) :
                      updateStmt("job2", "jb_id", $job_id, array("jb2_history_rawdata", $currentJobRawData));
                  else:
                      insertStmt("job2", array("jb_id", $job_id, "jb2_history_rawdata", $currentJobRawData));
                  endif;
                  if (existsEntry("job2",array("jb_id",$job_id))) :
                      updateStmt("job2", "jb_id", $job_id, array("jb2_history_hq", $jbHistoryData));
                  else:
                      insertStmt("job2", array("jb_id", $job_id, "jb2_history_hq", $jbHistoryData));
                  endif;                  
writeToFile($mcDebugExportLogFile, "::[1] OK");
                  // [2.] Store view of a mail
                  $jobentry = ""; $tourentry = ""; $jobcosts = ""; $courierentry = ""; $employeeentry = "";
                  $userTypeName = "hq";

                  $f_act = "export";
                  $currentJobParameterState = getJobSnapshot($job_id);
                  $f_act = "";
                  $jbHistoryData = $currentJobParameterState . $tmpDelimiter . $jobentry . $tmpDelimiter . $tourentry
                                 . $tmpDelimiter . $jobcosts . $tmpDelimiter . $courierentry . $tmpDelimiter . $employeeentry;
                  $jbHistoryData = str_replace('\'', '\\\'', $jbHistoryData);

                  $jbHistoryData = escapeMysqlForBinary(compress($jbHistoryData));

                  if (existsEntry("job2",array("jb_id",$job_id))) :
                      updateStmt("job2", "jb_id", $job_id, array("jb2_history_mail", $jbHistoryData));
                  else:
                      insertStmt("job2", array("jb_id", $job_id, "jb2_history_mail", $jbHistoryData));
                  endif;                  
writeToFile($mcDebugExportLogFile, "::[2] OK");
                  // [3.] Store view of the customer
                  $jobentry = ""; $tourentry = ""; $jobcosts = ""; $courierentry = ""; $employeeentry = "";
                  $userTypeName = "cs";
                  $currentJobParameterState = getJobSnapshot($job_id);
                  $jbHistoryData = $currentJobParameterState . $tmpDelimiter . $jobentry . $tmpDelimiter . $tourentry
                                 . $tmpDelimiter . $jobcosts . $tmpDelimiter . $courierentry . $tmpDelimiter . $employeeentry;
                  $jbHistoryData = str_replace('\'', '\\\'', $jbHistoryData);                  

                  $jbHistoryData = escapeMysqlForBinary(compress($jbHistoryData));   
   
                  if (existsEntry("job2",array("jb_id",$job_id))) :
                      updateStmt("job2", "jb_id", $job_id, array("jb2_history_cs", $jbHistoryData));
                  else:
                      insertStmt("job2", array("jb_id", $job_id, "jb2_history_cs", $jbHistoryData));
                  endif;
writeToFile($mcDebugExportLogFile, "::[3] OK");
              endfor;
*/
              $userTypeName = "hq";  // VERY IMPORTANT TO RESET !!!
              $f_act == $f_act_rem;
           endif;
        endif;


        // Call post export script with export log ID
        if (!$isCron) :
           if ($exl_id_new != "") :
	            $path = getAbsoluteSystemPath();
              $cmd = "php " . $path . "/export/post_export.php " . $exl_id_new . " " . $postExportPar . " &";
              exec($cmd . " > /dev/null &");
           endif;
        endif;
     endif;    
  endif;  // $userTypeName == "hq"
  
  return $retBool;
}

// Function is a fucking hardcoded treatment for Stadtbote and Hansetrans ... ToDo !!!!!!!!!!!!!!!
function specialFieldTreatment($rowString) {
  global $f_exp_category;
  if ($rowString != "") :
      if ($f_exp_category == "1" && substr($rowString,0,1) == ROW_EDIT_STATUS_MODIFY) :
          // $tmpStartPos = strpos($rowString, "|9F|J|");
          // $rowString = substr_replace($rowString, "|/|/|/|", $tmpStartPos, 17);
          $tmpStartPos = strpos($rowString, "|9F|J|");
          $rowString = substr_replace($rowString, "|/|/|/|/|", $tmpStartPos - 3, 20);
          // $tmpStartPos = strpos($rowString, "|003|ZA10|X|");
          $tmpStartPos = strpos($rowString, "|003|Z");
          // $rowString = substr_replace($rowString, "|/|/|/|/|/|/|/|/|/|/|/|/|/|/|/|", $tmpStartPos, 108);
          $rowString = substr_replace($rowString, "|/|/|/|/|/|/|/|/|/|/|/|/|/|", $tmpStartPos + 9, 99);
// |003|ZA10|X|Kunde seit: 12.02.25          |0001| |               |                  | |000001|91|91|1|91|01|     <=>   108 Zeichen
      endif;
      if ($f_exp_category == "4" || $f_exp_category == "5" || $f_exp_category == "6" || $f_exp_category == "7" || $f_exp_category == "8" || $f_exp_category == "9") :
         $rowString = str_replace ("|                                                                      ", "|", $rowString);
      endif;
  endif;
  return $rowString;
}

// Wipes some chars like lf, cr, etc.
function strWipeEolSigns($aStr) {
  // $aStr = str_replace('\'', '\\\'', $aStr);
  // $aStr = str_replace("\"", '\\"', $aStr);
  $aStr = str_replace("\n", '', $aStr);
  $aStr = str_replace("\r", '', $aStr);
  return $aStr;
}

// Splits the parameter-string according to the template in "exportcategoryfields (expcf)"
function splitParstr($parStr, $idArray, $titleArray) {
  $customArray = array();
  if ($parStr != "" && $idArray != "") :
     $customArray["id"] = $idArray;    
     $tmp = spliti("-;-",$parStr);
     $lenTmp = count($tmp);
     for ($i = 0; $i < $lenTmp; $i++) {
         $tmp2 = spliti("-,-",$tmp[$i]);

         // search for the value ("$tmp2[0]" = "expcf_id") in "$idArray" and get the key (index)
         $j = array_search($tmp2[0], $idArray);
         if (!($j === FALSE)) :
            $customArray["active"][$j]      = "1";
            $customArray["title"][$j]       = $titleArray[$j];
            $customArray["length"][$j]      = $tmp2[1];
            $customArray["direction"][$j]   = $tmp2[2];
            $customArray["sort"][$j]        = $tmp2[3];
            $customArray["dummy"][$j]       = $tmp2[4];
            $customArray["nodelimiter"][$j] = $tmp2[5];
            $customArray["fillupsign"][$j]  = $tmp2[6];
            $customArray["format"][$j]      = $tmp2[7];
            $customArray["active_if"][$j]   = $tmp2[8];
            $customArray["substr_from"][$j] = $tmp2[9];
            $customArray["substr_to"][$j]   = $tmp2[10];
            $customArray["substr_mode"][$j] = $tmp2[11];
         endif;
     }
  endif;
  return $customArray;
}

// Get the parameter-string of the currrent headquarter/customer
function getParameterData($userTypeName,$hq_id,$cs_id,$f_exp_category,$f_parname) {
   global $db;
   
   $whereClause = " cs_id = '0' AND ";
   if ($userTypeName == "cs") : $whereClause = " cs_id = $cs_id AND "; endif;   // only for login as customer

   $sqlquery = "SELECT expp_id, expp_parstr, expp_bolchars, expp_eolchars, expp_bofchars, expp_eofchars, expp_headline"
               . " FROM exportparameters"
               . " WHERE hq_id = '" . $hq_id . "' AND" . $whereClause
               . "       expc_id = '$f_exp_category' AND"
               . "       expp_name = '" . $f_parname . "'";

   $result = $db->query($sqlquery);
   if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
   // all defined db-fields and titles shall become content of the following arrays
   mcIsSet($f_expp_id); mcIsSet($f_expp_parstr); mcIsSet($f_bolchars); mcIsSet($f_eolchars); mcIsSet($f_bofchars); mcIsSet($f_eofchars); mcIsSet($f_headline);
   while ($row = $result->fetch_assoc()):   
         $f_expp_id     = $row["expp_id"];
         $f_expp_parstr = $row["expp_parstr"];
         $f_bolchars    = $row["expp_bolchars"];
         $f_eolchars    = $row["expp_eolchars"];
         $f_bofchars    = $row["expp_bofchars"];
         $f_eofchars    = $row["expp_eofchars"];
         $f_headline    = $row["expp_headline"];
   endwhile;
   $result->free();
   return array($f_expp_id,$f_expp_parstr,$f_bolchars,$f_eolchars,$f_bofchars,$f_eofchars,$f_headline);
}

// Parses the string for tags according a default scheme and executes the individual functionality
function tagParser($strToParse, $rowNum = -1) {
  global $fieldArray, $rowArray;
  if ($strToParse != "") :
     
     // check existence of tag-begin and tag-end as substring in $strToParse
     
     // content of db-fields
     $tagBegin = "<dbfield>";
     $tagEnd = "</dbfield>";
     $repeat = TRUE;
     while ($repeat && !(strpos($strToParse, $tagBegin) === FALSE) && !(strpos($strToParse, $tagEnd) === FALSE)) :

        $pos0 = strpos($strToParse, $tagBegin);                         // begin of tagBegin (first occurrence)
        $pos1 = strpos($strToParse, $tagBegin) + strlen($tagBegin);     // end of tagBegin   (first occurrence)
        $pos2 = strpos($strToParse, $tagEnd);                           // begin of tagEnd   (first occurrence)
        $pos3 = strpos($strToParse, $tagEnd) + strlen($tagEnd);         // end of tagEnd     (first occurrence)
        
        $repeat = FALSE;
        if ($pos2 - $pos1 > 0) :
           // first get the content of the tag (<=> sort-number of the db-field) for inserting the content of the db-field
           $idOfDbField = substr($strToParse, $pos1, $pos2 - $pos1);

           if (is_numeric($idOfDbField) && $rowNum > -1) :

              // get the content of the specified db-field
              $tagContent = $rowArray[$rowNum][substr($fieldArray[$idOfDbField], strrpos($fieldArray[$idOfDbField],".") + 1)];

              // Wipes lf, cr, etc.
              $tagContent = strWipeEolSigns($tagContent);

              // replace original content with string-content
              $strToParse = substr_replace($strToParse, $tagContent, $pos0, $pos3 - $pos0);              

              $repeat = TRUE;
           endif;
        endif;
     endwhile;
     
     // content of db-fields
     $tagBegin = "<dbfieldsub>";
     $tagEnd = "</dbfieldsub>";
     $repeat = TRUE;
     while ($repeat && !(strpos($strToParse, $tagBegin) === FALSE) && !(strpos($strToParse, $tagEnd) === FALSE)) :

        $pos0 = strpos($strToParse, $tagBegin);                         // begin of tagBegin (first occurrence)
        $pos1 = strpos($strToParse, $tagBegin) + strlen($tagBegin);     // end of tagBegin   (first occurrence)
        $pos2 = strpos($strToParse, $tagEnd);                           // begin of tagEnd   (first occurrence)
        $pos3 = strpos($strToParse, $tagEnd) + strlen($tagEnd);         // end of tagEnd     (first occurrence)
        
        $repeat = FALSE;
        if ($pos2 - $pos1 > 0) :
           // first get the content of the tag (<=> sort-number of the db-field) for inserting the content of the db-field
           $innerValue = substr($strToParse, $pos1, $pos2 - $pos1);
           $innerValueArray = spliti(",",$innerValue);
           $idOfDbField = $innerValueArray[0];
           $startSubStringPos = $innerValueArray[1];
           $endSubStringPos = $innerValueArray[2];
           $padLength = $innerValueArray[3];                      

           if (is_numeric($idOfDbField) && $rowNum > -1 && is_numeric($startSubStringPos) && is_numeric($endSubStringPos)) :

              // get the content of the specified db-field
              $tagContent = $rowArray[$rowNum][substr($fieldArray[$idOfDbField], strrpos($fieldArray[$idOfDbField],".") + 1)];
              
              // Wipes lf, cr, etc.
              $tagContent = strWipeEolSigns($tagContent);

              // Get specified subtring              
              $tagContent = substr($tagContent, $startSubStringPos, ($endSubStringPos - $startSubStringPos));
              
              // "Pad" if needed
              if ($padLength != "" && is_numeric($padLength)) :
                 $tagContent = pad($tagContent, $padLength, " ", "right");
              endif;

              // replace original content with string-content
              $strToParse = substr_replace($strToParse, $tagContent, $pos0, $pos3 - $pos0);

              $repeat = TRUE;
           endif;
        endif;
     endwhile;     
     
     // formats a date-string according some default-formats
     $tagBegin = "<date,";
     $tagEnd = "</date>";
     $repeat = TRUE;
     while ($repeat && !(strpos($strToParse, $tagBegin) === FALSE) && !(strpos($strToParse, $tagEnd) === FALSE)) :

        $pos0 = strpos($strToParse, $tagBegin);                         // begin of tagBegin (first occurrence)
        $pos1 = strpos($strToParse, $tagBegin) + strlen($tagBegin);     // end of tagBegin   (first occurrence)
        $pos2 = strpos($strToParse, $tagEnd);                           // begin of tagEnd   (first occurrence)
        $pos3 = strpos($strToParse, $tagEnd) + strlen($tagEnd);         // end of tagEnd     (first occurrence)
        
        $repeat = FALSE;        
        if ($pos2 - $pos1 > 0) :
           // first get the number of the date-format
           $numOfFormat = "";
           while (substr($strToParse, $pos1, 1) != ">") :
                 $numOfFormat .= substr($strToParse, $pos1, 1);
                 $pos1++;
           endwhile;
           $pos1++;   // next char after ">" <=> first char of the content of the tag 
                      
           if (is_numeric($numOfFormat)) :

              // get the content of the tag
              if ($pos2 - $pos1 > 0) :
                 $tagContent = substr($strToParse, $pos1, $pos2 - $pos1);
                 
                 // format the content
                 $tagContent = formatOutput($tagContent, "datetime", $numOfFormat);
                 
                 // replace original content with string-content
                 $strToParse = substr_replace($strToParse, $tagContent, $pos0, $pos3 - $pos0);                 
                 $repeat = TRUE;
              endif;
           endif;
        endif;
     endwhile;     
     
     // iterations
     $tagBegin = "<iter,";
     $tagEnd = "</iter>";
     $repeat = TRUE;
     while ($repeat && !(strpos($strToParse, $tagBegin) === FALSE) && !(strpos($strToParse, $tagEnd) === FALSE)) :

        $pos0 = strpos($strToParse, $tagBegin);                         // begin of tagBegin (first occurrence)
        $pos1 = strpos($strToParse, $tagBegin) + strlen($tagBegin);     // end of tagBegin   (first occurrence)
        $pos2 = strpos($strToParse, $tagEnd);                           // begin of tagEnd   (first occurrence)
        $pos3 = strpos($strToParse, $tagEnd) + strlen($tagEnd);         // end of tagEnd     (first occurrence)
        
        $repeat = FALSE;        
        if ($pos2 - $pos1 > 0) :
           // first get the number of iteration to replicate the content of the tag
           $numOfIterations = "";
           while (substr($strToParse, $pos1, 1) != ">") :
                 $numOfIterations .= substr($strToParse, $pos1, 1);
                 $pos1++;
           endwhile;
           $pos1++;   // next char after ">" <=> first char of the content of the tag 
                      
           if (is_numeric($numOfIterations)) :
        
              // get the content of the tag
              $tagContent = "";
              if ($pos2 - $pos1 > 0) :
                 $tagContentOrg = substr($strToParse, $pos1, $pos2 - $pos1);
                 
                 // replicate
                 for ($i = 0; $i < $numOfIterations; $i++) :
                     $tagContent .= $tagContentOrg;
                 endfor;
                 
                 // replace original content with string-content
                 $strToParse = substr_replace($strToParse, $tagContent, $pos0, $pos3 - $pos0);                 
                 $repeat = TRUE;
              endif;
           endif;
        endif;
     endwhile;
     
     // lfd with lpad "0"
     $tagBegin = "<lfd,";
     $tagEnd = "</lfd>";
     $repeat = TRUE;
     while ($repeat && !(strpos($strToParse, $tagBegin) === FALSE) && !(strpos($strToParse, $tagEnd) === FALSE)) :

        $pos0 = strpos($strToParse, $tagBegin);                         // begin of tagBegin (first occurrence)
        $pos1 = strpos($strToParse, $tagBegin) + strlen($tagBegin);     // end of tagBegin   (first occurrence)
        $pos2 = strpos($strToParse, $tagEnd);                           // begin of tagEnd   (first occurrence)
        $pos3 = strpos($strToParse, $tagEnd) + strlen($tagEnd);         // end of tagEnd     (first occurrence)
        
        $repeat = FALSE;        
        if ($pos2 - $pos1 > 0) :
           // first get number of the tag which contains the length to "padl" the lfd-number
           $padlLen = 0;
           while (substr($strToParse, $pos1, 1) != ">") :
                 $padlLen .= substr($strToParse, $pos1, 1);
                 $pos1++;
           endwhile;
           $pos1++;   // next char after ">" <=> first char of the content of the tag 
                      
           if (is_numeric($padlLen)) :
        
              // get the content of the tag
              $tagContent = "";
              if ($pos2 - $pos1 > 0) :
                 $tagContent = substr($strToParse, $pos1, $pos2 - $pos1);
              endif;

              // padl and concat
              $tagContent .= pad($rowNum, $padlLen, "0", "left");
                 
              $strToParse = substr_replace($strToParse, $tagContent, $pos0, $pos3 - $pos0);
              $repeat = TRUE;
           endif;
        endif;
     endwhile;     

  endif;
  return $strToParse;
}

// Checks the filter if is set for a db-field
function checkActiveIf($filter, $rowNum = -1) {
  global $fieldArray, $rowArray;
  $retBool = TRUE;
  if (trim($filter) != "") :
     $tmp = spliti("/",$filter);
     $lenTmp = count($tmp);
     for ($i = 0; $i < $lenTmp; $i++) {
         $tmp2 = spliti("=",$tmp[$i]);
         // check filter with the content of the specified db-field
         $dbFieldContent = "";
         if (is_numeric($tmp2[0]) && $rowNum > -1) :
            $dbFieldContent = $rowArray[$rowNum][substr($fieldArray[$tmp2[0]], strrpos($fieldArray[$tmp2[0]],".") + 1)];
            if ($dbFieldContent != trim($tmp2[1])) :
               $i = $lenTmp;
               $retBool = FALSE;               
            endif;
         else :
            $i = $lenTmp;
            $retBool = FALSE;
         endif;
     }     
  endif;
  return $retBool;
}


// **********************************************************************************************
// * Get the superset of all possible fields of the current category (not depending on any hq!) *
// **********************************************************************************************
include_once ("../include/inc_category_dbfields.inc.php");
// SELECT ... FROM exportcategoryfields ...
$idArrayLen = getCategoryDBFields($f_exp_category);



// *******************************
// * Save the configuration-data *
// *******************************
if ($f_act == "save") :

   if ($f_parstr_active != "" && $f_parname != "" && $f_exp_category != "0") :

      // Implode http-values to the parameter-string for storing      
      $parArray = array();
      for ($i = 0; $i < $idArrayLen; $i++) :
                            
           // concat the string because the checkbox is checked
           // if ($f_parstr_active == $idArray[$i]) :
           if ($f_parstr_active != "" && in_array ($idArray[$i], $f_parstr_active)) :

              // Get current input-type-text-field with price-/dicount-value
              list ($valueLen, $valueDir, $valueSort, $valueDummy, $valueFill, $valueFormat, $valueActiveIf, $valueSubstrFrom, $valueSubstrTo) = getHttpVars(array("f_parstr_len_". $idArray[$i], "f_parstr_dir_". $idArray[$i], "f_parstr_sort_". $idArray[$i], "f_parstr_dummy_". $idArray[$i], "f_parstr_fillupsign_". $idArray[$i], "f_parstr_format_". $idArray[$i], "f_parstr_activeif_". $idArray[$i], "f_parstr_substrfrom_". $idArray[$i], "f_parstr_substrto_". $idArray[$i]));
           
              if ($valueLen == "%") : $valueLen = ""; endif;
              if ($valueDir == "%") : $valueDir = ""; endif;
              if ($valueSort == "%") : $valueSort = ""; endif;
              if ($valueDummy == "%") : $valueDummy = ""; endif;
              // Check for setting the delimiter explicitly NOT
              $valueNoDelimiter = "0";
              if ($f_parstr_nodelimiter != "" && in_array ($idArray[$i], $f_parstr_nodelimiter)) : $valueNoDelimiter = "1"; endif;
              if ($valueFill == "") : $valueFill = " "; endif;
              if ($valueFormat == "%") : $valueFormat = ""; endif;
              $valueActiveIf = trim($valueActiveIf);
              if ($valueSubstrFrom == "%") : $valueSubstrFrom = " "; endif;
              if ($valueSubstrTo == "%") : $valueSubstrTo = " "; endif;
              $valueSubstrMode = "0";
              if ($f_parstr_substrmode != "" && in_array ($idArray[$i], $f_parstr_substrmode)) : $valueSubstrMode = "1"; endif;
           
              $parArray[] = $idArray[$i] . "-,-" . $valueLen . "-,-" . $valueDir . "-,-" . $valueSort . "-,-" . $valueDummy . "-,-" . $valueNoDelimiter . "-,-" . $valueFill . "-,-" . $valueFormat . "-,-" . $valueActiveIf . "-,-" . $valueSubstrFrom . "-,-" . $valueSubstrTo . "-,-" . $valueSubstrMode;
           endif;
      endfor;
      $parString = implode("-;-",$parArray);     // wrapping to the string

      // Check existence of this name
      if (existsEntry("exportparameters",array("expp_id",$f_expp_id,"hq_id",$hq_id,"expc_id",$f_exp_category,"expp_name",$f_parname))) :

          // Update exportparameters
          updateStmt("exportparameters", "expp_id", $f_expp_id, array("expp_parstr", $parString, "expp_bolchars", $f_bolchars, "expp_eolchars", $f_eolchars, "expp_bofchars", $f_bofchars, "expp_eofchars", $f_eofchars));
      else:
          // Insert exportparameters
          insertStmt("exportparameters", array("hq_id", $hq_id,"cs_id", $customerId, "expc_id", $f_exp_category, 
                                               "expp_name",$f_parname, "expp_parstr", $parString, "expp_bolchars", $f_bolchars, 
                                               "expp_eolchars", $f_eolchars, "expp_bofchars", $f_bofchars, "expp_eofchars", $f_eofchars));
      endif;
   
   endif;
endif;


// *****************************************************************************************
// * Special preparations before starting export process regarding to the current category *
// *****************************************************************************************
if ($f_act == "export") :

   if ($f_fileName != "") :

      // Check existence of this name
      if (!existsEntry("exportfiles",array("hq_id",$hq_id,"cs_id",$customerId,"expf_name",$f_fileName))) :

         // Detect entries in jobpayment to be exported and write "export lfd" (virtual job number)
         if ($f_exp_category == "9"):

            // A special customer has to be selected
            if ($jbpCsId == "" && $f_cs_eid_filter != "") :
               $jbpCsId = getFieldValueFromId("customer","cs_eid",$f_cs_eid_filter,"cs_id");  // Get "cs_id" from "cs_eid"
            endif;
     
            if ($jbpCsId != "" && is_numeric($jbpCsId)) :
     
               TA("B");
     
               $jbpCsArray = array($jbpCsId);
               $jbpCsArrayLen = count($jbpCsArray);
               for ($j = 0; $j < $jbpCsArrayLen; $j++) :
     
                   // Get group of the current related customer
                   $tmpGroups = getFieldValueFromId("customer","cs_id",$jbpCsArray[$j],"cs_group");      // Get "grp_id" from "cs_id"
                   $tmpGroups = spliti(",", $tmpGroups);
                   $jbpCsGrpId = $tmpGroups[1];
     
                   // Get payment modes requested by the user running the export
                   // PRESENTLY ALL(!) PAYMENT TYPES WILL BE INSERTED IN "jobpaymentcollection". THE EXPORT PROCESS TAKES THE REQUESTED PAYMENT TYPES ONLY !!!!
                   $jbpModeFilterWhereClause = "";
                   if ($cat09_paymentTypesRequested != "") : 
                       $jbpModeFilterWhereClause = " AND jbp.jbp_mode IN (" . $cat09_paymentTypesRequested . ") ";
                   endif;
     
                   // !!!!!!!!!! RELATIVE PROPRIETARY !!!!!!!!!!!!!!!!!!  :-(
                   // Get invoice texts according to the payment types requested
                   $jbpcInvTextArray = array();
                   $cat09_paymentTypesRequestedArray = spliti(",", $cat09_paymentTypesRequested);
                   $cat09_paymentTypesRequestedArrayLen = count($cat09_paymentTypesRequestedArray);
                   if ($cat09_paymentTypesRequestedArrayLen > 0) :
                      for ($c = 0; $c < $cat09_paymentTypesRequestedArrayLen; $c++) :
                          $jbpcInvTextArray[$cat09_paymentTypesRequestedArray[$c]] = getObjectBasedParameterValue("EXPORT_CAT_09_PAYMENTTYPE_" . $cat09_paymentTypesRequestedArray[$c] . "_CS", $jbpCsArray[$j], $hq_id);
                          if ($jbpcInvTextArray[$cat09_paymentTypesRequestedArray[$c]] == "") :
                             $jbpcInvTextArray[$cat09_paymentTypesRequestedArray[$c]] = getObjectBasedParameterValue("EXPORT_CAT_09_PAYMENTTYPE_" . $cat09_paymentTypesRequestedArray[$c] . "_GRP", $jbpCsGrpId, $hq_id);
                          endif;
                      endfor;
                   endif;
     
                   // Get all DISTINCT booking dates (from timestamp "jbp_bookingtime") of all rows
                   $jbpWhereClause = "jbp.jbp_bookingtime >= '" . $fromDateRange . "' AND jbp.jbp_bookingtime <= '" . $toDateRange . "' AND jbp.jbpc_id = '0' AND jbp.jbp_price != '0' AND (ISNULL(jbp.jbp_export_time) || jbp.jbp_export_time = '0000-00-00 00:00:00') " . $jbpModeFilterWhereClause . " AND jbp.csc_id = csc.csc_id AND csc.cs_id = cs.cs_id AND cs.cs_id = '" . $jbpCsArray[$j] . "'";
                   $jbpBookingDates = getColVectorFromDB2ArrayByClause("jobpayment AS jbp, costcenter AS csc, customer AS cs", "LEFT(jbp_bookingtime,10) AS jbp_bookingdate", $jbpWhereClause, "", "", "DISTINCT");
                   $jbpBookingDatesLen = count($jbpBookingDates);
     
// Proprietärer MÜLL wg. Scheiß-SAP und Zeitstress, aber zum Glück scheint nicht mehr notwendig !!!! :-(
$executeStandard = true;
$tmpSpecial  = array_search("11", $cat09_paymentTypesRequestedArray);  // Zahlart BC
$tmpSpecial2 = array_search("15", $cat09_paymentTypesRequestedArray);  // Zahlart SAMS
$tmpSpecial3 = array_search("16", $cat09_paymentTypesRequestedArray);  // Zahlart LCD happy flow
$tmpSpecial4 = array_search("17", $cat09_paymentTypesRequestedArray);  // Zahlart LCD sad flow
$tmpSpecial5 = array_search("18", $cat09_paymentTypesRequestedArray);  // Zahlart OS happy flow
$tmpSpecial6 = array_search("19", $cat09_paymentTypesRequestedArray);  // Zahlart OS sad flow
if (!($tmpSpecial === FALSE) || !($tmpSpecial2 === FALSE) || !($tmpSpecial3 === FALSE) || !($tmpSpecial4 === FALSE) || !($tmpSpecial5 === FALSE) || !($tmpSpecial6 === FALSE)) :
   $executeStandard = false;
endif;

if (!$executeStandard) :
                   // Split for "counter" and "installer"
                   // $tmpCurrentDate = getDateTime("3");
                   $tmpCurrentDate = substr($toDateRange, 0, 10);
                   $tmpExportDataExist = false;
                   $tmpPaymentDataNotOk = false;
     
                   // In fucking PROPRIETYRY case of SAMS (only) the export has to be split by jb_service
                   $tmpLoopIterationsByServiceSplit = 1;
                   $tmpServiceSplitWhereClauseArray = array("", "");
                   if (!($tmpSpecial2 === FALSE)) :
                      $tmpLoopIterationsByServiceSplit = 2;
                      $tmpServiceSplitWhereClauseArray = array(" AND (jb.jb_service & 2) = 0 ", " AND (jb.jb_service & 2) = 2 ");
                   endif;

                   for ($f = 0; $f < $tmpLoopIterationsByServiceSplit; $f++) :

                       // Get all rows in "jbp" to be exported. Take position from completed jobs only!
                       // $jbpWhereClause = "jbp.jbp_counter = '0' AND jbp.jbp_bookingtime >= '" . $fromDateRange . "' AND jbp.jbp_bookingtime <= '" . $toDateRange . "' AND jbp.jbpc_id = '0' AND jbp.jbp_price != '0' AND (ISNULL(jbp.jbp_export_time) || jbp.jbp_export_time = '0000-00-00 00:00:00') " . $jbpModeFilterWhereClause . " AND jbp.csc_id = csc.csc_id AND csc.cs_id = cs.cs_id AND cs.cs_id = '" . $jbpCsArray[$j] . "'";
                       $jbpWhereClause = "jbp.jbp_bookingtime >= '" . $fromDateRange . "' AND jbp.jbp_bookingtime <= '" . $toDateRange . "' AND jbp.jbpc_id = '0' AND jbp.jbp_price != '0' AND (ISNULL(jbp.jbp_export_time) || jbp.jbp_export_time = '0000-00-00 00:00:00') " . $jbpModeFilterWhereClause . " AND jbp.jb_id = jb.jb_id AND jb.jb_incomplete = '0' AND jb.jb_status = '2' " . $tmpServiceSplitWhereClauseArray[$f] . " AND jbp.csc_id = csc.csc_id AND csc.cs_id = cs.cs_id AND cs.cs_id = '" . $jbpCsArray[$j] . "'";
                       $jbpIDs = getColVectorFromDB2ArrayByClause("jobpayment AS jbp, costcenter AS csc, customer AS cs, job AS jb", "jbp.jbp_id", $jbpWhereClause, "", "jbp.jbp_id", "");

                       if (is_array($jbpIDs) && count($jbpIDs) > 0) :

                          // Get all payment types of all rows
                          $jbpPaymentTypes = getColVectorFromDB2ArrayByClause("jobpayment", "jbp_mode", "jbp_id IN (" . implode(',', $jbpIDs) . ")", "", "jbp_id", "DISTINCT");
                          $jbpPaymentTypesLen = count($jbpPaymentTypes);
                          if (is_array($jbpPaymentTypes) && $jbpPaymentTypesLen > 0) :

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

                                  // Insert new row in "jobpaymentcollection"
                                  insertStmt("jobpaymentcollection", array("cs_id", $jbpCsArray[$j], "jbpc_mode", $jbpPaymentTypes[$i], "jbpc_price", "0", "jbpc_bookingdate", $tmpCurrentDate));
                                  $jbpcIdNew = getLastInsertID();

                                  // Associate all rows with the collection number
                                  updateStmt("jobpayment", "", "", array("jbpc_id", $jbpcIdNew), "jbp_id IN (" . implode(',', $jbpIDs) . ") AND jbp_mode = '" . $jbpPaymentTypes[$i] . "'");

                                  // Get summation of "jbp_price" of relevant rows to update the new collection row
                                  $sumOfJbpPrice = getSumOfTable("jobpayment AS jbp", "jbp.jbp_price", "jbp.jbp_id IN (" . implode(',', $jbpIDs) . ") AND jbp.jbp_mode = '" . $jbpPaymentTypes[$i] . "' AND EXISTS (SELECT * FROM job AS jb WHERE jbp.jb_id = jb.jb_id)");

                                  // Update summation of "jbp_price" in "jobpaymentcollection"
                                  updateStmt("jobpaymentcollection", "jbpc_id", $jbpcIdNew, array("jbpc_price", $sumOfJbpPrice));

                                  // Update invoice text (RELATIVE PROPRIETARY)
                                  $jbpcInvoiceText = $jbpcInvTextArray[$jbpPaymentTypes[$i]];
                                  if (!($tmpSpecial2 === FALSE)) :
                                     if ($f == 0) :
                                        $jbpcInvoiceText = "Wir berechnen Ihnen für die SAMS-Lieferungen gemäß beiliegender|Anlage bis einschließlich";
                                     elseif ($f == 1) :
                                        $jbpcInvoiceText = "Wir berechnen Ihnen für die SAMS-Montagen gemäß beiliegender|Anlage bis einschließlich";
                                     endif;
                                  endif;
                                  updateStmt("jobpaymentcollection", "jbpc_id", $jbpcIdNew, array("jbpc_invtext", $jbpcInvoiceText));
                              endfor;
                              $tmpExportDataExist = true;
                          else :
                             $tmpPaymentDataNotOk = true;
                          endif;
                       endif;
                   endfor;

                   // Payment data not ok
                   if ($tmpPaymentDataNotOk) :
                      $statusMessage = "Es erfolgte KEIN Export! Die Zahlungsarten sind nicht in Ordnung! Bitte der Systemadministration melden!";
                      $f_act = "";  // Do NOT export because needed preparation failed
                   endif;

                   // No counter data 
                   if (!$tmpExportDataExist) :
                      $statusMessage = "Es erfolgte KEIN Export! Keine Daten zum Exportieren gefunden!";
                      $f_act = "";  // Do NOT export because needed preparation failed)
                   endif;
endif;
     
if ($executeStandard) :
                   for ($k = 0; $k < $jbpBookingDatesLen; $k++) :
     
                       // Split for "counter" and "installer"
                       $tmpNoexportData = array(false,false);
                       $tmpPaymentDataNotOk = array(false,false);
                       for ($c = 0; $c <= 1; $c++) :
     
                           // Get all rows in "jbp" to be exported
                           $jbpWhereClause = "jbp.jbp_counter = '" . $c . "' AND jbp.jbp_bookingtime >= '" . $fromDateRange . "' AND jbp.jbp_bookingtime <= '" . $toDateRange . "' AND LEFT(jbp.jbp_bookingtime,10) = '" . $jbpBookingDates[$k] . "' AND jbp.jbpc_id = '0' AND jbp.jbp_price != '0' AND (ISNULL(jbp.jbp_export_time) || jbp.jbp_export_time = '0000-00-00 00:00:00') " . $jbpModeFilterWhereClause . " AND jbp.csc_id = csc.csc_id AND csc.cs_id = cs.cs_id AND cs.cs_id = '" . $jbpCsArray[$j] . "'";
                           $jbpIDs = getColVectorFromDB2ArrayByClause("jobpayment AS jbp, costcenter AS csc, customer AS cs", "jbp.jbp_id", $jbpWhereClause, "", "jbp.jbp_id", "");
     
                           if (is_array($jbpIDs) && count($jbpIDs) > 0) :
                           
                              // Get all payment types of all rows
                              $jbpPaymentTypes = getColVectorFromDB2ArrayByClause("jobpayment", "jbp_mode", "jbp_id IN (" . implode(',', $jbpIDs) . ")", "", "jbp_id", "DISTINCT");
                              $jbpPaymentTypesLen = count($jbpPaymentTypes);
                              if (is_array($jbpPaymentTypes) && $jbpPaymentTypesLen > 0) :
                           
                                 for ($i = 0; $i < $jbpPaymentTypesLen; $i++) :
                           
                                      // Insert new row in "jobpaymentcollection"
                                      insertStmt("jobpaymentcollection", array("cs_id", $jbpCsArray[$j], "jbpc_mode", $jbpPaymentTypes[$i], "jbpc_price", "0", "jbpc_bookingdate", $jbpBookingDates[$k]));
                                      $jbpcIdNew = getLastInsertID();
                           
                                      // if ($jbpcIdNew != "") :
                           
                                         // Associate all rows with the collection number
                                         updateStmt("jobpayment", "", "", array("jbpc_id", $jbpcIdNew), "jbp_id IN (" . implode(',', $jbpIDs) . ") AND jbp_mode = '" . $jbpPaymentTypes[$i] . "'");
                           
                                         // Get summation of "jbp_price" of relevant rows to update the new collection row
                                         $sumOfJbpPrice = getSumOfTable("jobpayment AS jbp", "jbp.jbp_price", "jbp.jbp_id IN (" . implode(',', $jbpIDs) . ") AND jbp.jbp_mode = '" . $jbpPaymentTypes[$i] . "' AND EXISTS (SELECT * FROM job AS jb WHERE jbp.jb_id = jb.jb_id)");
                           
                                         // Update summation of "jbp_price" in "jobpaymentcollection"
                                         updateStmt("jobpaymentcollection", "jbpc_id", $jbpcIdNew, array("jbpc_price", $sumOfJbpPrice));
                           
                                         // Update invoice text (RELATIVE PROPRIETARY)
                                         updateStmt("jobpaymentcollection", "jbpc_id", $jbpcIdNew, array("jbpc_invtext", $jbpcInvTextArray[$jbpPaymentTypes[$i]]));
                                      // endif;
                                  endfor;
                              else :
                                 $tmpPaymentDataNotOk[$c] = true;
                              endif;
                           else :
                              $tmpNoexportData[$c] = true;
                           endif;
                       endfor;
     
                       // Payment data not ok
                       if ($tmpPaymentDataNotOk[0] && $tmpPaymentDataNotOk[1]) :
                          $statusMessage = "Es erfolgte KEIN Export! Die Zahlungsarten sind nicht in Ordnung! Bitte der Systemadministration melden!";
                          $f_act = "";  // Do NOT export because needed preparation failed
                       endif;
     
                       // No counter data 
                       if ($tmpNoexportData[0] && $tmpNoexportData[1]) :
                          $statusMessage = "Es erfolgte KEIN Export! Keine Daten zum Exportieren gefunden!";
                          $f_act = "";  // Do NOT export because needed preparation failed)
                       endif;
                   endfor;
endif;     
               endfor;
     
               TA("C");
               TA("E");
            else :
               $statusMessage = "Es erfolgte KEIN Export! Geben Sie bitte den konkreten Kunden ein!";
               $f_act = "";  // Do NOT export because needed preparation failed
            endif;
         endif;
      else:              
          $statusMessage = "Der Dateiname existiert schon! Bitte gleich noch einmal versuchen!";
          $f_act = "";
      endif;
   else :
      $statusMessage = "Es wurden kein Dateiname vergeben! Bitte gleich noch einmal versuchen!";
      $f_act = "";
   endif;
endif;

// *****************************
// * Export the requested data *
// *****************************
if ($f_act == "export") :

   // * Check for export semaphore. Use combined key of headquarters id and export category *
   $semaphorExport = false;
   // Check parameter for semaphore usage being disabled explicitly <=> no restriction, do continue export process
   $parExpSemaphoreUsageDisabled = getParameterValue("0", "EXPORT_SEMAPHORE_USAGE_DISABLED", $hq_id);
   if ($parExpSemaphoreUsageDisabled == "") : $parExpSemaphoreUsageDisabled = getParameterValue("0", "EXPORT_SEMAPHORE_USAGE_DISABLED", "0"); endif;
   if ($parExpSemaphoreUsageDisabled == "1") : $semaphorExport = true; endif;
   // Check for semaphore
   if (!$semaphorExport) :
      $semaphorKey = "export";
      $semaphoreCurrentTime = getDateTime("0");
      $semaphorLiveTime = getParameterValue("0", "EXPORT_SEMAPHORE_LIVE_TIME", $hq_id);
      if ($semaphorLiveTime == "" || !is_numeric($semaphorLiveTime)) : $semaphorLiveTime = getParameterValue("0", "EXPORT_SEMAPHORE_LIVE_TIME", "0"); endif;
      if ($semaphorLiveTime == "" || !is_numeric($semaphorLiveTime)) : $semaphorLiveTime = 90; endif;
      if (existsEntry("phoenix_log.semaphor",array("sp_obj_type","hq","sp_obj_id",$hq_id,"sp_fieldname",$semaphorKey,"sp_content",$f_exp_category))) :
         // Check semaphor to be removed
         $spCreatetime = getFieldValueFromClause("phoenix_log.semaphor", "sp_createtime", "sp_obj_type = 'hq' AND sp_obj_id = '" . $hq_id . "' AND sp_fieldname = '" . $semaphorKey . "' AND sp_content = '" . $f_exp_category . "'");
         $spSecDiff = strtotime($semaphoreCurrentTime) - strtotime($spCreatetime);
         if ($spSecDiff > $semaphorLiveTime) :
            deleteStmt("phoenix_log.semaphor","sp_obj_type = 'hq' AND sp_obj_id = '" . $hq_id . "' AND sp_fieldname = '" . $semaphorKey . "' AND sp_content = '" . $f_exp_category . "'");
            $semaphorExport = true;
         endif;
      endif;
      if (!existsEntry("phoenix_log.semaphor",array("sp_obj_type","hq","sp_obj_id",$hq_id,"sp_fieldname",$semaphorKey,"sp_content",$f_exp_category))) :
         insertStmt("phoenix_log.semaphor", array("sp_obj_type", "hq", "sp_obj_id", $hq_id, "sp_fieldname", $semaphorKey, "sp_content", $f_exp_category, "sp_context", "LOCKED", "sp_createtime", $semaphoreCurrentTime));
         $semaphorExport = true;
      endif;
   endif;

   if ($semaphorExport) :

      if ($f_fileName != "") :
      
         // Check existence of this name
         if (!existsEntry("exportfiles",array("hq_id",$hq_id,"cs_id",$customerId,"expf_name",$f_fileName))) :

            // get the parameter-string and the row_id of format with the specified f_parname_export for the headquarter/customer
            $tmp = getParameterData($userTypeName,$hq_id,$customerId,$f_exp_category,$f_parname_export);
            $f_expp_id = $tmp[0];
            $f_expp_parstr = $tmp[1];
            $f_bolchars = $tmp[2];
            $f_eolchars = $tmp[3];
            $f_bofchars = $tmp[4];
            $f_eofchars = $tmp[5];
            $f_expp_headline = $tmp[6];
      
            // create secret filename
            $f_secretFileName = md5($f_fileName);

            // split the parameter-string, generate a new customized array and compare with the general "idArray"      
            $customArray = splitParstr($f_expp_parstr, $idArray, $titleArray);
      
            // part of individual selections for the export-data
            include_once("../export/exportrequests.inc.php");

            if (count($rowArray) > 0) :

               if ($f_bofchars != "") :
                  writeToFile($globalExportPath . $f_secretFileName, $f_bofchars);   // write bof-chars
               endif;

               // Write headline
               if ($f_headline == "1") :
                  $exportHeadline = "";
                  // Check for specific headline regarding customer export
                  if ($userTypeName == "cs" && $customerId != "") :
                     $exportHeadline = getParameterValue("0", "EXPORT_CSV_HEADLINE_CS_" . $customerId, "0");
                  endif;
                  // Check for specific headline regarding headquarters export
                  if ($userTypeName == "hq") :
                     $exportHeadline = $f_expp_headline;
                  endif;
                  if ($exportHeadline == "") :
                     for ($j = 0; $j < $idArrayLen; $j++) :                  // because of individual sorting
                         for ($i = 0; $i < $idArrayLen; $i++) :
                             if ($customArray["sort"][$i] == $j) :           // first check all with "0", then "1", then "2", ...      
                                if ($customArray["active"][$i] == "1") :
                                   $exportHeadline .= $customArray["title"][$i];
                                   if ($customArray["nodelimiter"][$i] != "1") :
                                      $exportHeadline .= $f_delimiter;
                                   endif;
                                   $tmpTagParser = tagParser($customArray["dummy"][$i]);
                                   $numOfDelimiters = substr_count($tmpTagParser, $f_delimiter);
                                   if ($numOfDelimiters > 0) :
                                      for ($d = 0; $d < $numOfDelimiters; $d++) :
                                          $exportHeadline .= $f_delimiter;
                                      endfor;
                                   endif;
                                   break;
                                endif;
                             endif;
                         endfor;
                     endfor;
                  endif;
                  $exportHeadline = trim($exportHeadline);
                  if ($exportHeadline != "") :
                     writeToFile($globalExportPath . $f_secretFileName, $exportHeadline);   // write headline
                  endif;
               endif;

               $rowArrayLen = count($rowArray);
               for ($l = 0; $l < $rowArrayLen; $l++) :
                   
                     $rowFields = array();        // regular db-fields
                     $rowFieldsIndex = array();   // index
                     $count = 0;
                     
                     for ($j = 0; $j < $idArrayLen; $j++) :                  // because of individual sorting
                         for ($i = 0; $i < $idArrayLen; $i++) :

                             $customArray["sort"][$i] = mcArrMultiDimIsSet($customArray["sort"], $i);
                             if ($customArray["sort"][$i] == $j) :           // first check all with "0", then "1", then "2", ...
      
                                $customArray["active"][$i] = mcArrMultiDimIsSet($customArray["active"], $i);
                                if ($customArray["active"][$i] == "1") :
      
                                   if (checkActiveIf($customArray["active_if"][$i], $l)) :
      
                                      $valueToWrite = $rowArray[$l][substr($fieldArray[$i], strrpos($fieldArray[$i],".") + 1)];   // current content of the field
                                      
                                      // Wipes lf, cr, etc.
                                      $valueToWrite = strWipeEolSigns($valueToWrite);
      
                                      // check for formatting the output of the value depending on the type
                                      $customArray["format"][$i] = mcArrMultiDimIsSet($customArray["format"], $i);
                                      if ($customArray["format"][$i] != "%" && $customArray["format"][$i] != "") :
                                         $valueToWrite = formatOutput($valueToWrite, $dbFieldTypeArray[substr($fieldArray[$i], strrpos($fieldArray[$i],".") + 1)], $customArray["format"][$i]);
                                      endif;
                                      
                                      // check substring
                                      $subStr_from = $customArray["substr_from"][$i];
                                      $subStr_to = $customArray["substr_to"][$i];
                                      if (is_numeric($subStr_from) || is_numeric($subStr_to)) :
                                         if ($customArray["substr_mode"][$i] != "1") :
                                            // Real substr() mode
                                            if (!is_numeric($subStr_from)) : $subStr_from = 0; endif;
                                            if (!is_numeric($subStr_to)) : $subStr_to = strlen($valueToWrite); endif;
                                            $subStr_len = $subStr_to - $subStr_from + 1;
                                            $valueToWrite = trim(substr($valueToWrite, $subStr_from, $subStr_len));
                                         else :
                                            // Left()/Right() mode
                                            $tmpLeftStr = "";
                                            $tmpRightStr = "";
                                            if (is_numeric($subStr_from)) :
                                               $tmpLeftStr = trim(substr($valueToWrite, 0, $subStr_from));
                                            endif;
                                            if (is_numeric($subStr_to)) :
                                               $tmpRightStr = trim(substr($valueToWrite, -($subStr_to), $subStr_to));
                                            endif;
                                            $valueToWrite = $tmpLeftStr . $tmpRightStr;
                                         endif;
                                      endif;
      
                                      // check length: if parameter-length > real-length then fill up with fill-up-char (like space as default)
                                      if ($customArray["length"][$i] > strlen($valueToWrite)) :
      
                                         if ($customArray["direction"][$i] == "l") :
                                            $valueToWrite = pad($valueToWrite, $customArray["length"][$i], $customArray["fillupsign"][$i], "right");
                                         else :
                                            $valueToWrite = pad($valueToWrite, $customArray["length"][$i], $customArray["fillupsign"][$i], "left");
                                         endif;
                                      else :
                                            $valueToWrite = substr($valueToWrite, 0, $customArray["length"][$i]);
                                      endif;
                                   else :
                                   
                                      $valueToWrite = "";
                                      for ($z = 0; $z < $customArray["length"][$i]; $z++) :
                                          $valueToWrite .= " ";
                                      endfor;
                                   endif;
                                   
                                   $rowFields[$count] = $valueToWrite;
                                   $rowFieldsIndex[$count] = $i;
                                   
                                   $count++;
                                endif;
                             endif;
                         endfor;
                     endfor;
      
                     
                     // ****************************************
                     // * generate string-data for output-file *
                     // ****************************************
                     $rowFieldsLen = count($rowFields);
                     $rowString = tagParser($f_bolchars,$l);   // write bol-chars
                     
                     for ($i = 0; $i < $rowFieldsLen; $i++) :     // set/unset delimiter
      
                         // write delimiter if field "no delimiter" is NOT checked
                         if ($customArray["nodelimiter"][$rowFieldsIndex[$i]] != "1") :
                            $rowString .= $rowFields[$i] . $f_delimiter . tagParser($customArray["dummy"][$rowFieldsIndex[$i]],$l);
                         else :
                            if ($customArray["dummy"][$rowFieldsIndex[$i]] == "") :
      
                               $sumLength = $customArray["length"][$rowFieldsIndex[$i]];
                               $strToWrite = rtrim($rowFields[$i]) . " ";
                               $j = $i;
                               while ($customArray["nodelimiter"][$rowFieldsIndex[$j]] == "1") :
                                     
                                     $sumLength += $customArray["length"][$rowFieldsIndex[$j + 1]];
                                     $strToWrite .= rtrim($rowFields[$j + 1]) . " ";
                                     $j++;
                               endwhile;
                               
                               // check length
                               if ($sumLength > strlen($strToWrite)) :
                                  $strToWrite = pad($strToWrite, $sumLength, $f_fillUpChar, "right");
                               else :
                                  $strToWrite = substr($strToWrite, 0, $sumLength);
                               endif;                         
                               
                               $i = $j;  // new position in the for-loop
                               $rowString .= $strToWrite . $f_delimiter . tagParser($customArray["dummy"][$rowFieldsIndex[$i]],$l);
                            else :
                               $rowString .= trim(trim($rowFields[$i]) . tagParser($customArray["dummy"][$rowFieldsIndex[$i]],$l));
                            endif;
                         endif;
                     endfor;
      
                     $rowString = substr($rowString,0,strlen($rowString) - strlen($f_delimiter));   // delete last delimiter at end of line
                     $rowString .= tagParser($f_eolchars,$l);   // write eol-chars

                     // Special treatment of fields (e.g. set "/" for fields 16-30 and 34-36 if export modified customer)
                     $rowString = specialFieldTreatment($rowString);
      
                     writeToFile($globalExportPath . $f_secretFileName, $rowString);   // write to file with the specified name
               endfor;   // rowArray
      
               if ($f_eofchars != "") :
                  writeToFile($globalExportPath . $f_secretFileName, $f_eofchars);   // write eof-chars
               endif;
      
               // insert file-reference into the exportfiles
               insertStmt("exportfiles", array("hq_id", $hq_id,"cs_id", $customerId, "expf_name", $f_fileName, "expf_cryptname",$f_secretFileName));
      
               $statusMessage = "Die Daten wurden exportiert!";
      
               // Encryption of the file if enabled
               if (ENCRYPT_EXPORTDATA == "1") :
                  // Get company associated to the current headquarter
                  $cmp_id  = getFieldValueFromId("headquarters","hq_id",$hq_id,"cmp_id");
                  // Get key user
                  $cmp_keyuser  = getFieldValueFromId("company","cmp_id",$cmp_id,"cmp_keyuser");
                  
                  if (encryptFile($globalExportPath . $f_secretFileName, $cmp_keyuser, "")) :
                     // Update secret filename with valid extension
                     updateStmt("exportfiles", "expf_cryptname", $f_secretFileName, array("expf_cryptname", $f_secretFileName . "." . ENCRYPT_FILEEXTENSION, "expf_name", $f_fileName . "." . ENCRYPT_FILEEXTENSION));
      
                     // If crypted, delete original non-crypted file from the filesystem (without extension)
                     if (file_exists($globalExportPath . $f_secretFileName)) :
                        unlink($globalExportPath . $f_secretFileName);
                     endif;
      
                     $statusMessage .= " Die Verschlüsselung erfolgte!";
                  else :
                     $statusMessage .= " Die Verschlüsselung konnte nicht erfolgen!";
                  endif;
               endif;
               
               // Write export status of the exported rows into the database
               setExportValues();
      
            else :
               $statusMessage = "Es wurden keine Daten exportiert!";
            endif;
         else:              
             $statusMessage = "Der Dateiname existiert schon! Bitte gleich noch einmal versuchen!";
         endif;
      else :
         $statusMessage = "Es wurden kein Dateiname vergeben! Bitte gleich noch einmal versuchen!";
      endif;
   else :
      $statusMessage = "Der Export wurde ggfs. von einer anderen Station aktuell ausgeführt und ist zur Zeit für diese Kategorie gesperrt! Bitte gleich noch einmal versuchen!";
   endif;
endif;   


// **********************************************
// * Manually removal of a specified exportfile *
// **********************************************
if ($f_act == "removeExportfile") :

   if ($f_exportFileToDelete != "") :

      // get crypted physical filename
      if (getDbFieldValues("exportfiles",array("expf_cryptname"),array("expf_name",$f_exportFileToDelete,"hq_id",$hq_id,"cs_id",$customerId,))) :

         // check crypted physical filename from the "getDbFieldValues"-function
         if ($expf_cryptname != "") :

            // delete file from the filesystem            
            if (file_exists($globalExportPath . $expf_cryptname)) :
            
               unlink($globalExportPath . $expf_cryptname);
            else :
               $statusMessage = "Die Datei befindet sich nicht mehr in dem Verzeichnis!";
            endif;
   
            // remove entry from the database
            deleteStmt("exportfiles","expf_name = '" . $f_exportFileToDelete . "' AND hq_id = '" . $hq_id . "' AND cs_id = '" . $customerId . "'");
         endif;         
      else :
         $statusMessage = "Dateninkonsistenz! Eintrag wurde nicht gefunden! Bitte diesen Fehler weiterleiten!";
      endif;
   else :
      $statusMessage = "Es liegt kein Dateiname vor!";
   endif;
endif;


// Special export according to a special export function
if (substr($f_act,0,15) == "special_export_") :

   $funcNo = substr($f_act,15);
   if ($funcNo != "" && is_numeric($funcNo)) :

      if ($f_fileName != "") :

         // Check existence of this name
         if (!existsEntry("exportfiles",array("hq_id",$hq_id,"cs_id",$customerId,"expf_name",$f_fileName))) :

            // Get data and write file
            $specialExportArray = specialExportInterface($customerId, $funcNo);
            $specialExportArrayLen = count($specialExportArray);

            if ($specialExportArrayLen == 0) :
               $statusMessage = "Es wurden keine Daten exportiert!";
            endif;
         else :
            $statusMessage = "Der Dateiname existiert schon!";
         endif;
      else:
         $statusMessage = "Es wurden kein Dateiname vergeben! Bitte gleich noch einmal versuchen!";
      endif;
   endif;
endif;


// **************************************************************************
// * Read the default-parameter-string for the current headquarter/customer *
// **************************************************************************

if (!$isCron) :

   $lfdArray = array();
   $customConfigOutput = "";
   if ($f_exp_category != "0") :
   
      // get the parameter-string and the row_id of format with the specified f_parname for the headquarter/customer
      $tmp = getParameterData($userTypeName,$hq_id,$customerId,$f_exp_category,$f_parname);
      $f_expp_id = $tmp[0];
      $f_expp_parstr = $tmp[1];
      $f_bolchars = $tmp[2];
      $f_eolchars = $tmp[3];
      $f_bofchars = $tmp[4];
      $f_eofchars = $tmp[5];
      
      // split the parameter-string, generate a new customized array and compare with the general "idArray"
      $customArray = splitParstr($f_expp_parstr, $idArray, $titleArray);
   
      // output of the changeable configuration
      $customConfigOutput = "<tr><td>LFD.&nbsp;&nbsp;FELD</td><td>AKTIV</td><td>LÄNGE</td><td>AUSRICHTUNG</td><td>FÜLLZEICHEN</td>" . 
                            "<td>FORMAT</td><td>SORTIERUNG</td><td>KEIN DELIMITER</td><td>TEILWORT VON-BIS</td><td>LINKS/RECHTS</td>" .
                            "<td>ZUSATZFELD(ER)</td><td>AKTIV, WENN...</td></tr>";
      for ($i = 0; $i < $idArrayLen; $i++) :
          
          // get db-name of the current field
          $dbFieldName = substr($fieldArray[$i], strrpos($fieldArray[$i],".") + 1);
          
          $customConfigOutput .= "<tr><td>";       
          
          // lfd and title
          $customConfigOutput .= pad($i, 3, $specialChar = "&nbsp;") . ".&nbsp;&nbsp;&nbsp;&nbsp;";
          $customConfigOutput .= $titleArray[$i] . "\n";
          $customConfigOutput .= "</td><td>";
   
          // active
          $isChecked = "";
          $customArray["active"][$i] = mcArrMultiDimIsSet($customArray["active"], $i);
          if ($customArray["active"][$i] == "1") : $isChecked = "checked"; endif;
          $customConfigOutput .= "<input type=\"checkbox\" name=\"f_parstr_active[]\" value=\"" . $idArray[$i] . "\" " . $isChecked . ">\n";
          $customConfigOutput .= "</td><td>";
          
          // length       
          $customFieldLength = "%";
          $customArray["length"][$i] = mcArrMultiDimIsSet($customArray["length"], $i);
          if ($customArray["length"][$i] != "") : $customFieldLength = $customArray["length"][$i]; endif;
          $customConfigOutput .= "<input type=\"text\" name=\"f_parstr_len_" . $idArray[$i] . "\" value=\"" . $customFieldLength . "\" size=\"3\">\n";       
          $customConfigOutput .= "</td><td>";

          // direction (left, right, ...)
          $customFieldDirection = "%";
          $customArray["direction"][$i] = mcArrMultiDimIsSet($customArray["direction"], $i);
          if ($customArray["direction"][$i] != "") : $customFieldDirection = $customArray["direction"][$i]; endif;       
          $isSelected = array("","","");
          if ($customFieldDirection == "%") : $isSelected[0] = "selected"; endif; 
          if ($customFieldDirection == "r") : $isSelected[1] = "selected"; endif;
          if ($customFieldDirection == "l") : $isSelected[2] = "selected"; endif;       
          $customConfigOutput .= "<select name=\"f_parstr_dir_" . $idArray[$i] . "\">\n<option value=\"%\" " . $isSelected[0] . ">%</option>\n<option value=\"r\" " . $isSelected[1] . ">rechts</option>\n<option value=\"l\" " . $isSelected[2] . ">links</option>\n</select>\n";
          $customConfigOutput .= "</td><td>";

          // fillup-sign
          $customArray["fillupsign"][$i] = mcArrMultiDimIsSet($customArray["fillupsign"], $i);
          $customConfigOutput .= "<input type=\"text\" name=\"f_parstr_fillupsign_" . $idArray[$i] . "\" value=\"" . $customArray["fillupsign"][$i] . "\" size=\"1\" maxlength=\"1\">\n";
          $customConfigOutput .= "</td><td>";

          // format according to the type of the db-field
          mcArrIsSet($dbFieldTypeArray, $dbFieldName);
          $customArray["format"][$i] = mcArrMultiDimIsSet($customArray["format"], $i);
          if ($dbFieldTypeArray[$dbFieldName] == "float") :
             $customFieldFormat = "%";
             if ($customArray["format"][$i] != "") : $customFieldFormat = $customArray["format"][$i]; endif;          
             $isSelected = array("","","","");
             if ($customFieldFormat == "%") : $isSelected[0] = "selected"; endif; 
             if ($customFieldFormat == "1") : $isSelected[1] = "selected"; endif;
             if ($customFieldFormat == "2") : $isSelected[2] = "selected"; endif;
             if ($customFieldFormat == "3") : $isSelected[3] = "selected"; endif;
             $customConfigOutput .= "<select name=\"f_parstr_format_" . $idArray[$i] . "\">\n" .
                                        "<option value=\"%\" " . $isSelected[0] . ">%</option>\n" .
                                        "<option value=\"1\" " . $isSelected[1] . ">...xxx.yy</option>\n" .
                                        "<option value=\"2\" " . $isSelected[2] . ">...xxx,yy</option>\n" .
                                        "<option value=\"3\" " . $isSelected[3] . ">...xxxyy</option>\n" .
                                    "</select>\n";
          elseif ($dbFieldTypeArray[$dbFieldName] == "datetime") :       
             $customFieldFormat = "%";
             if ($customArray["format"][$i] != "") : $customFieldFormat = $customArray["format"][$i]; endif;          
             $isSelected = array("","");
             if ($customFieldFormat == "%") : $isSelected[0] = "selected"; endif; 
             for ($j = 2; $j < 12; $j++) :
                 $isSelected[$j] = "";
                 if ($customFieldFormat == $j) : $isSelected[$j] = "selected"; endif;
             endfor;          
             $customConfigOutput .= "<select name=\"f_parstr_format_" . $idArray[$i] . "\">\n" .
                                        "<option value=\"%\" " . $isSelected[0] . ">%</option>\n" .
                                        "<option value=\"2\" " . $isSelected[2] . ">h.i.s</option>\n" .
                                        "<option value=\"3\" " . $isSelected[3] . ">y.m.d : h.i.s</option>\n" .
                                        "<option value=\"4\" " . $isSelected[4] . ">d.m.Y</option>\n" .
                                        "<option value=\"5\" " . $isSelected[5] . ">d.m.y</option>\n" .
                                        "<option value=\"6\" " . $isSelected[6] . ">y.m.d</option>\n" .
                                        "<option value=\"7\" " . $isSelected[7] . ">ymd</option>\n" .
                                        "<option value=\"8\" " . $isSelected[8] . ">Y.m.d</option>\n" .
                                        "<option value=\"9\" " . $isSelected[9] . ">Ymd</option>\n" .
                                        "<option value=\"10\" " . $isSelected[10] . ">h:i</option>\n" .
                                        "<option value=\"11\" " . $isSelected[11] . ">m/y</option>\n" .
                                    "</select>\n";          
          else :
             // no existing format => no output
             $customConfigOutput .= "&nbsp;";
          endif;

          $customConfigOutput .= "</td><td>";

          // sort
          $customConfigOutput .= "<select name=\"f_parstr_sort_" . $idArray[$i] . "\">\n";
          for ($j = 0; $j < $idArrayLen; $j++) :
              $isSelected = "";
              $customArray["sort"][$i] = mcArrMultiDimIsSet($customArray["sort"], $i);
              if ($customArray["sort"][$i] == $j) : $isSelected = "selected"; endif; 
              $customConfigOutput .= "<option value=\"" . $j . "\" " . $isSelected . ">" . $j . "</option>\n";
          endfor;
          $customConfigOutput .= "</select>\n";       
          $customConfigOutput .= "</td><td>";

          // no delimiter
          $isChecked = ""; 
          $customArray["nodelimiter"][$i] = mcArrMultiDimIsSet($customArray["nodelimiter"], $i);
          if ($customArray["nodelimiter"][$i] == "1") : $isChecked = "checked"; endif;
          $customConfigOutput .= "<input type=\"checkbox\" name=\"f_parstr_nodelimiter[]\" value=\"" . $idArray[$i] . "\" " . $isChecked . ">\n";
          $customConfigOutput .= "</td><td>";

          // substring from
          $customConfigOutput .= "<select name=\"f_parstr_substrfrom_" . $idArray[$i] . "\">\n";
          $customConfigOutput .= "  <option value=\"%\">%</option>\n";
          for ($j = 1; $j < 26; $j++) :
              $isSelected = "";
              $customArray["substr_from"][$i] = mcArrMultiDimIsSet($customArray["substr_from"], $i);
              if ($customArray["substr_from"][$i] == $j) : $isSelected = "selected"; endif; 
              $customConfigOutput .= "<option value=\"" . $j . "\" " . $isSelected . ">" . $j . "</option>\n";
          endfor;
          $customConfigOutput .= "</select>\n";
          // substring to
          $customConfigOutput .= "-<select name=\"f_parstr_substrto_" . $idArray[$i] . "\">\n";
          $customConfigOutput .= "  <option value=\"%\">%</option>\n";
          for ($j = 1; $j < 26; $j++) :
              $isSelected = "";
              $customArray["substr_to"][$i] = mcArrMultiDimIsSet($customArray["substr_to"], $i);
              if ($customArray["substr_to"][$i] == $j) : $isSelected = "selected"; endif; 
              $customConfigOutput .= "<option value=\"" . $j . "\" " . $isSelected . ">" . $j . "</option>\n";
          endfor;
          $customConfigOutput .= "</select>\n";       
          $customConfigOutput .= "</td><td>";       

          // substring mode (normal or left/right)
          $isChecked = "";
          $customArray["substr_mode"][$i] = mcArrMultiDimIsSet($customArray["substr_mode"], $i);
          if ($customArray["substr_mode"][$i] == "1") : $isChecked = "checked"; endif;
          $customConfigOutput .= "<input type=\"checkbox\" name=\"f_parstr_substrmode[]\" value=\"" . $idArray[$i] . "\" " . $isChecked . ">\n";
          $customConfigOutput .= "</td><td>";       

          // extra-field(s) (dummy)
          $customArray["dummy"][$i] = mcArrMultiDimIsSet($customArray["dummy"], $i);
          $customConfigOutput .= "<input type=\"text\" name=\"f_parstr_dummy_" . $idArray[$i] . "\" value=\"" . $customArray["dummy"][$i] . "\" size=\"40\">\n";
          $customConfigOutput .= "</td><td>";

          // filter, whether a field will be exported if another fields have special values
          $customArray["active_if"][$i] = mcArrMultiDimIsSet($customArray["active_if"], $i);
          $customConfigOutput .= "<input type=\"text\" name=\"f_parstr_activeif_" . $idArray[$i] . "\" value=\"" . $customArray["active_if"][$i] . "\" size=\"10\">\n";

          $customConfigOutput .= "</td></tr>";       
      endfor;
   endif;
   
   
   // *********************************************************************
   // * Read all of the template-names stored by the headquarter/customer *
   // *********************************************************************
   $parameterNamesOptions = "";
   
   $whereClause = " cs_id = '0' AND ";
   if ($userTypeName == "cs") : $whereClause = " cs_id = '$customerId' AND "; endif;   // only for login as customer
   
   $sqlquery = "SELECT expp_name"
               . " FROM exportparameters"
               . " WHERE hq_id = '$hq_id' AND" . $whereClause
               . "       expc_id = '$f_exp_category'";
   
   $result = $db->query($sqlquery);
   if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());   
      
   $isSelected = "";
   while ($row = $result->fetch_assoc()):            
         if ($row["expp_name"] == $f_parname) : $isSelected = "selected"; endif;
         $parameterNamesOptions .= "<option value=\"" . $row["expp_name"] . "\" " . $isSelected . ">" . $row["expp_name"] . "</option>";
         $isSelected = "";
   endwhile;
   $result->free();
   
   
   // ********************************************
   // * Read all of the local exported filenames *
   // ********************************************
   $storedExportFiles = "";
   
   $whereClause = " cs_id = '0' AND ";
   if ($userTypeName == "cs") : $whereClause = " cs_id = '$customerId' AND "; endif;   // only for login as customer
   
   // Restrictions regarding to the user rights for the displayed files
   $parFileExtension = getParameterValue("0", "EXPORT_CAT_09_FILE_EXTENSION", $hq_id);
   if ($parFileExtension == "") :
      $parFileExtension = getParameterValue("0", "EXPORT_CAT_09_FILE_EXTENSION", "0");
      if ($parFileExtension == "") :
         $parFileExtension = "ums";
      endif;
   endif;
   $tmpExtensionLen = strlen($parFileExtension);
   $tmpExtensionLen++;  // Increment because of "."-sign
   if (!$empHasAccess_06 && $empHasAccess_26) :
      $whereClause .= " RIGHT(expf_name," . $tmpExtensionLen . ") = '." . $parFileExtension . "' AND ";
   elseif (!$empHasAccess_26) :
      $whereClause .= " RIGHT(expf_name," . $tmpExtensionLen . ") != '." . $parFileExtension . "' AND ";
   endif;
   
   $sqlquery = "SELECT expf_id, expf_name, expf_cryptname, expf_storetime, expf_ftpupload"
               . " FROM exportfiles"
               . " WHERE " . $whereClause . "hq_id = '$hq_id'"
               . " ORDER BY expf_storetime DESC";
   
   $result = $db->query($sqlquery);
   if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());   
   
   $expfIdArray = array();
   $expfCryptNameArray[] = "";
   
   // Restrictions to display links for FTP upload
   $parFTPuploadDisabled = getParameterValue("0", "EXPORT_MASK_FTP_UPLOAD_DISABLED", $hq_id);
   if ($parFTPuploadDisabled == "") : $parFTPuploadDisabled = getParameterValue("0", "EXPORT_MASK_FTP_UPLOAD_DISABLED", "0"); endif;
   
   // Get enabled file extensions for FTP upload
   $ftpExportFileExtensionArr = array();
   if ($parFTPuploadDisabled != "1") :
      // Get file extensions to be exported only
      $parFtpExportFileExtensionsEnabled = getParameterValue("0", "EXPORT_FTP_FILE_EXTENSIONS_ENABLED", $hq_id);
      if ($parFtpExportFileExtensionsEnabled == "") : $parFtpExportFileExtensionsEnabled = getParameterValue("0", "EXPORT_FTP_FILE_EXTENSIONS_ENABLED", "0"); endif;
      if ($parFtpExportFileExtensionsEnabled != "") : 
         $ftpExportFileExtensionArr = explode("|", $parFtpExportFileExtensionsEnabled);
      endif;
   endif;
   
   $storedExportFiles .= "<table>";
   // Define table header
   $storedExportFiles .= "<tr>";
   $storedExportFiles .= ($adminInterfacePassword == $configPassword ? "<td>Löschen&nbsp;&nbsp;&nbsp;&nbsp;</td>" : "") . "<td>Datum / Uhrzeit</td><td>WEB-Download</td>";
   if ($userTypeName == "hq" && $parFTPuploadDisabled != "1") :
      $storedExportFiles .= "<td>FTP-Upload</td>";
   endif;
   $storedExportFiles .= "</tr>";
   // Define table body from result set
   while ($row = $result->fetch_assoc()):            
         $expfIdArray[] = $row["expf_id"];
         $expfCryptNameArray[] = $row["expf_cryptname"];
         $storedExportFiles .= "<tr>";
         if ($adminInterfacePassword == $configPassword) :
            $storedExportFiles .= "<td align=\"center\"><a href=\"javascript:removeExportfile('".$row["expf_name"]."');\">"
                                          . "<img src=\"../images/trash.jpg\" border=\"0\" height=\"13\" width=\"8\">" 
                                          . "</a>" . "&nbsp;&nbsp;&nbsp;&nbsp;</td>";
         endif;
         $storedExportFiles .= "<td>" . formatOutput($row["expf_storetime"],"timestamp") . "&nbsp;&nbsp;&nbsp;&nbsp;</td>";
         $storedExportFiles .= "<td><a href=\"exportdata.php?customerId=" . ec($customerId) . "&cscIdRoot=" . ec($cscIdRoot) . 
                                                           "&cscIdActual=" . ec($cscIdActual) . "&f_fileName=" . $row["expf_name"] . "\" target=\"_blank\">" . 
                                     $row["expf_name"] . "</a>&nbsp;&nbsp;&nbsp;&nbsp;</td>";
         // Enable FTP upload option only for headquarter
         if ($userTypeName == "hq" && $parFTPuploadDisabled != "1") :
            if ($row["expf_ftpupload"] != "1") :
               // Check extension of the file to enable special FTP-Upload
               $fileExtension = substr($row["expf_name"], strrpos($row["expf_name"], ".")); 
               if (in_array($fileExtension, $ftpExportFileExtensionArr)) :
                  $storedExportFiles .= "<td><a href=\"exportdata_ftp.php?f_fileName=" . $row["expf_name"] . "&customerId=" . ec($customerId) . 
                                             "&cscIdRoot=" . ec($cscIdRoot) . "&cscIdActual=" . ec($cscIdActual) . "\" target=\"_blank\">" . 
                                             $row["expf_name"] . "</a></td>";
               else :
                  $storedExportFiles .= "<td>" . $row["expf_name"] . "</td>";
               endif;
            else :
               $storedExportFiles .= "<td>" . $row["expf_name"] . "</td>";
            endif;
         endif;
         $storedExportFiles .= "</tr>";
   endwhile;
   $storedExportFiles .= "</table>";
   $result->free();
   
   // Automatical deletion of more than 5 files
   $maxEntries = EXPORT_FILES_ON_SERVER;
   if ($userTypeName == "cs") : $maxEntries = EXPORT_FILES_ON_SERVER_CUSTOMER; endif;
   if ($maxEntries == "" || !is_numeric($maxEntries)) : $maxEntries = "10"; endif;
   $expfIdArrayLen = count($expfIdArray);
   if ($expfIdArrayLen >= $maxEntries) :
      
      for ($j = $maxEntries - 1; $j < $expfIdArrayLen; $j++) :
          if (file_exists($globalExportPath . $expfCryptNameArray[$j])) :
             unlink($globalExportPath . $expfCryptNameArray[$j]);               // delete file
          endif;
          deleteStmt("exportfiles","expf_id = " . $expfIdArray[$j]);   // delete corresponding db-entry
      endfor;   
   endif;
   
   
   // **************************************************
   // * Get the list of remote files on the FTP server *
   // **************************************************
   $storedRemoteExportFiles = "";
   
   // Restrictions to display remote (FTP-)server files
   $parFTPDisplayServerFilesDisabled = getParameterValue("0", "EXPORT_MASK_FTP_SERVER_FILES_DISABLED", $hq_id);
   if ($parFTPDisplayServerFilesDisabled == "") : $parFTPDisplayServerFilesDisabled = getParameterValue("0", "EXPORT_MASK_FTP_SERVER_FILES_DISABLED", "0"); endif;
   
   if ($userTypeName == "hq" && $parFTPDisplayServerFilesDisabled != "1") : 
      $remoteFileList = array();
      $connId = ftpGetConnection();
      if ($connId != "") :
         $remoteFileList = ftpGetDirectoryContent($connId, FTP_UPLOADPATH);
         ftpQuitConnection($connId);
      endif;
      if ($remoteFileList != FALSE) :
         $storedRemoteExportFiles .= "<table>";
         $remoteFileListLen = count($remoteFileList);
         for ($j = 0; $j < $remoteFileListLen; $j++) :
             $fileNameToBeDisplayed = $remoteFileList[$j];
             // Remove path, display filename only
             $tmpPos = strrpos($fileNameToBeDisplayed, '/') + 1;
             $fileNameToBeDisplayed = substr($fileNameToBeDisplayed, $tmpPos);
             $storedRemoteExportFiles .= "<tr>";
             $storedRemoteExportFiles .= "<td>" . $fileNameToBeDisplayed . "</td>";
             $storedRemoteExportFiles .= "</tr>";
         endfor;
         $storedRemoteExportFiles .= "</table>";
      endif;
   endif;


   $passwdOK = false;
   // Check for interface mode (headquarter access)
   if ($userTypeName == "hq") : 
      if ($adminInterfacePassword != "") :
         // if (sha1($adminInterfacePassword) == "7c627cdefcd5e699b458394b2ffdd27f052680f4") :
         if ($adminInterfacePassword == $configPassword) :
            $passwdOK = true;
         endif;   
      endif;
   endif;
   // Customer access?
   if ($userTypeName == "cs") :
      $passwdOK = true;      
   endif;
   // Load interface
   if ($passwdOK) :
      include_once ("../export/exportinterface_admin.inc.php");
   else :
      include_once ("../export/exportinterface_customer.inc.php");
   endif;
   
else :
   // Automatic upload of the export file to remote server

endif;
?>

