<?php
/*=======================================================================
 *
 * dbglobal.inc.php
 *
 * Autor: Marc Vollmann, Carsten Annacker
 *
 =======================================================================*/

include_once ("../include/dbconnect.inc.php");
include_once ("../locating/xServer.inc.php");

/*
function getCurrentScript($scriptFileName) {};
function getLanguage($scriptFileName) {};
function getLngt($defaultText) {return $defaultText;};
*/

// Gets the special script name with relative path
function getCurrentScript($scriptFileName) {
	global $currentScript;
	$scriptFileName = str_replace("\\", "/", $scriptFileName);	
	$tmpPos = strrpos($scriptFileName, "/");
	$idxName2 = substr($scriptFileName, $tmpPos);	
	$scriptFileName = substr($scriptFileName, 0, $tmpPos);
	$tmpPos = strrpos($scriptFileName, "/");
	$idxName1 = substr($scriptFileName, $tmpPos + 1);
	$currentScript = $idxName1 . $idxName2;
	return $currentScript;
}

// Get output texts according to the requested language in global array "$languageText"
// This function has to be called at the beginning of each script with texts to be displayed
function getLanguage($scriptFileName) {
	global $db, $PHP_SELF, $languageText, $languageSelected, $currentScript;
	if ($languageSelected != "0") :
	   $idxName = getCurrentScript($scriptFileName);
     $sqlStmt = "SELECT lngt.lngt_key, lngt.lngt_value"
              . " FROM phoenix_special.languagetext AS lngt"
              . " WHERE lngt.lngt_file = '" . $idxName . "' AND"
              . "       lngt.lng_num = '" . $languageSelected . "'";
     $result = $db->dbQ($sqlStmt);
     while ($row = $result->fetch_assoc()):
           $languageText[$row["lngt_key"]] = $row["lngt_value"];
     endwhile;
     $result->free();
  endif;
}

// The name "getLngt" is the short version of "getLanguagetext".
// This function checks the existence of an corresponding entry in the global array "$languageText".
// If the entry does not exist according to the requested language, an entry will be generated
// with default german text editable in the database. If it does exist, the text will be returned
function getLngt($defaultText, $dbConnection = "") {
	global $db, $PHP_SELF, $languageText, $languageSelected, $languageDBUpdateMode, $currentScript;
	if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;
	$defaultText = trim($defaultText);
	$lngText = $defaultText ;
	if ($languageSelected != "0") :
	   mcArrIsSet($languageText, $defaultText);
     $lngText = $languageText[$defaultText];
     if ($lngText == "") :
        // Insert missing entry into database
        if ($languageDBUpdateMode == "1" && $defaultText != "") :
           if (!existsEntry("phoenix_special.languagetext",array("lngt_file",$currentScript,"lng_num",$languageSelected,"lngt_key",$defaultText))) :
              $sqlStmt = "INSERT INTO phoenix_special.languagetext (lngt_file,lng_num,lngt_key,lngt_value) VALUES ('$currentScript','$languageSelected','$defaultText','$defaultText');";
              $res = $dbConnection->dbQ($sqlStmt);
           endif;
        endif;
        $lngText = $defaultText ;
     endif;
  endif;
	return $lngText;
}

getLanguage(__FILE__);

$db_log_file = "../log/dbwrite.log";

function writeDbLog($sqlStmt) {  
//  global $db_log_file, $HTTP_SESSION_VARS;
//
//  $fileHandle = @fopen($db_log_file, 'a');
//  @fwrite($fileHandle, "[" . date("Y-m-d H:i:s O") .
//    " (usr_id = " . sprintf("%4d", $HTTP_SESSION_VARS['usr_id']) . ")" . '] "' .
//    $sqlStmt . '"' . "\n");
//  @fclose($fileHandle);
return;
}

function insertStmt($table,$fields,$dbConnection = "") {
     global $db, $PHP_SELF;
     if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;
                
     $fs = "";
     $vs = "";     
     $fieldsLength = count($fields);          
     for ($i = 0; $i < $fieldsLength; $i += 2) :
       $fs .= $fields[$i];
       $vs .= "'" . $fields[$i + 1] . "'";
       if ($i < $fieldsLength - 2) :
         $fs .= ",";
         $vs .= ",";
       endif;
     endfor;
            
     $sqlStmt = "INSERT INTO $table ($fs) VALUES ($vs)";
     $res = $dbConnection->dbQ($sqlStmt);

     return $res;
}

// Inserts object into database table and returns the last inserted ID
function dbInsert($table, $keyValueArray, $dbConnection = "") {
  global $db, $PHP_SELF;
  if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;
  $retVal = "";
  if ($table != "" && is_array($keyValueArray) && count($keyValueArray) > 0) :
     insertStmt($table, $keyValueArray,$dbConnection);
     $retVal = getLastInsertId($dbConnection);
  endif;
  return $retVal;
}

function updateStmt($table,$pKeyName,$pKeyVal,$fields,$whereClause = "",$dbConnection = "") {
     global $db, $PHP_SELF;
     if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;

     $fs = "";     
     $fieldsLength = count($fields);          
     for ($i = 0; $i < $fieldsLength; $i += 2) :
       $fs .= $fields[$i] . "='" . $fields[$i + 1] . "'";
       if ($i < $fieldsLength - 2) :
         $fs .= ", ";
       endif;
     endfor;
     if ($pKeyName != ""):
       $sqlStmt = "UPDATE $table SET $fs WHERE $pKeyName = '$pKeyVal'";
       if ($whereClause != "") : $sqlStmt .= " AND " . $whereClause ; endif;
     else:
       $sqlStmt = "UPDATE $table SET $fs WHERE " . $whereClause;
     endif;
     $res = $dbConnection->dbQ($sqlStmt);
     if ($dbConnection->connect_errno) die ("$PHP_SELF: <br>$sqlStmt<br>" . $dbConnection->connect_error);
     
     return $res;
}

function deleteStmt($table,$whereClause, $dbConnection = "") {
     global $db;
     if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;

     if ($whereClause != "") :              
       $sqlStmt = "DELETE FROM $table WHERE $whereClause";
       $res = $dbConnection->dbQ($sqlStmt);
       return $res;
     endif;
     
     return false;
}

function getOneStmt($sqlStmt, $retField, $dbConnection = "") {
     global $db;
     if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;

     $retVal = "";
     if ($sqlStmt != "" && $retField != "") :
        $retField = (strpos($retField, " AS ")) ? (substr(stristr($retField, " AS "), 4)) : $retField;
        $retField = (strpos($retField, ".")) ? (substr(stristr($retField, "."), 1)) : $retField;
        if ($retField != "") :
           $result = $dbConnection->dbQ($sqlStmt);
           if ($row = $result->fetch_assoc()):
                 $retVal = $row[$retField];
           endif;
           $result->free();
        endif;
     endif;
     
     return $retVal;
}

// Gets exactly the value of one specified field from the specified row by key of a certain table
function getFieldValueFromId($table,$pKeyName,$pKeyVal,$field,$dbConnection = "") {
     global $db, $PHP_SELF;
     if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;
     
     $retValue = "";
     $sqlStmt = "SELECT $field FROM $table WHERE $pKeyName = '$pKeyVal'";
     $result = $dbConnection->dbQ($sqlStmt);
     while ($row = $result->fetch_assoc()):
           $retValue = $row[$field];
     endwhile;
     $result->free();
     return $retValue;
}     

// Gets exactly the value of one specified field from the specified SQL-WHERE clause
function getFieldValueFromClause($table,$field,$whereClause = "",$dbConnection = "") {
     global $db, $PHP_SELF;
     if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;
     
     $retValue = "";
     $sqlStmt = "SELECT $field FROM $table WHERE $whereClause";
     $result = $dbConnection->dbQ($sqlStmt);
     while ($row = $result->fetch_assoc()):
           $retValue = $row[$field];
     endwhile;
     $result->free();     
     return $retValue;
}     

// Gets exactly the values of specified fields from the specified row by key of a certain table
function getFieldsValueFromId($table,$pKeyName,$pKeyVal,$fields,$dbConnection = "") {
     global $db, $PHP_SELF;
     if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;
     
     $fs = "";
     $fieldsLength = count($fields);          
     for ($i = 0; $i < $fieldsLength; $i++) :
       $fs .= $fields[$i];
       if ($i < $fieldsLength - 1) :
         $fs .= ",";
       endif;
     endfor;    
     
     $retValue = array();
     $sqlStmt = "SELECT $fs FROM $table WHERE $pKeyName = '$pKeyVal'";
     $result = $dbConnection->dbQ($sqlStmt);
     while ($row = $result->fetch_assoc()):
           for ($i = 0; $i < $fieldsLength; $i++) :
               $retValue[$i] = $row[$fields[$i]];
           endfor;
     endwhile;
     $result->free();  
     
     return $retValue;
}

// Gets exactly the values of specified fields from the specified row by key of a certain table
// $table contains the name of the database-table
// $fields is an array and contains the fields to be generated global parameter
// $whereFields is an array and contains the fields and values for the where-clause
function getDbFieldValues($table,$fields,$whereFields,$dbConnection = "") {
     global $db;
     if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;
     
     $fs = "";
     $fieldsLength = count($fields);          
     for ($i = 0; $i < $fieldsLength; $i++) :
       $fs .= $fields[$i];
       if ($i < $fieldsLength - 1) : $fs .= ","; endif;
     endfor;    
     
     $whereClause = "";
     $whereFieldsLength = count($whereFields);          
     for ($i = 0; $i < $whereFieldsLength; $i += 2) :
       $whereClause .= $whereFields[$i] . " = '" . $whereFields[$i + 1] . "'";
       if ($i < $whereFieldsLength - 2) : $whereClause .= " AND "; endif;
     endfor;  
     if ($whereClause != "") : $whereClause = " WHERE " . $whereClause ; endif;

     $retValue = FALSE;
     $sqlStmt = "SELECT $fs FROM $table $whereClause";
     $result = $dbConnection->dbQ($sqlStmt);
     while ($row = $result->fetch_assoc()):
           for ($i = 0; $i < $fieldsLength; $i++) :
// echo "fields[" . $i . "] = " . $fields[$i] . "<br>";
             global ${$fields[$i]};
             ${$fields[$i]} = $row[$fields[$i]];
           endfor;
           $retValue = TRUE;
     endwhile;     
     $result->free();  
          
     return $retValue;
}

// Gets col values of a specified db field of a certain table
// $table     : table of the db
// $pKeyName  : name of the key field to search
// $pKeyVal   : value to be searched for in the key field
// $pValName  : name of the field to get the data
// $pSortName : "order by"-field
function getColVectorFromDB2Array($table,$pKeyName,$pKeyVal,$pValName,$pSortName = "",$dbConnection = "") {
     global $db, $PHP_SELF;
     if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;

     $retArray = array();
     $sqlStmt = "SELECT $pValName FROM $table WHERE $pKeyName = '$pKeyVal'";
     if ($pSortName != "") : $sqlStmt .= " ORDER BY $pSortName"; endif;
     $result = $dbConnection->dbQ($sqlStmt);
     while ($row = $result->fetch_assoc()):
           array_push($retArray, $row[$pValName]);
     endwhile;
     $result->free();  
     
     return $retArray;
}


// Gets col values of a specified db field of a certain table
// $table         : table of the db
// $pWhereClause  : WHERE clause of the statement
// $pValName      : name of the field to get the data
// $pSortName     : "order by"-field
function getColVectorFromDB2ArrayByClause($table, $pValName, $pWhereClause, $pKeyName = "", $pSortName = "", $pDistinct = "", $dbConnection = "") {
     global $db, $PHP_SELF;
     if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;
     
     $retArray = array();
     $sqlStmt = "SELECT " . ($pDistinct != "" ? "DISTINCT " : "") . ($pKeyName != "" ? $pKeyName . ", " : "") . "$pValName FROM $table " . ($pWhereClause != "" ? "WHERE " . $pWhereClause : "");
     if ($pSortName != "") : $sqlStmt .= " ORDER BY $pSortName"; endif;
     $result = $dbConnection->dbQ($sqlStmt);
     $pValName = (strpos($pValName, " AS ")) ? (substr(stristr($pValName, " AS "), 4)) : $pValName;
     $pValName = (strpos($pValName, ".")) ? (substr(stristr($pValName, "."), 1)) : $pValName;
     $pKeyName = (strpos($pKeyName, " AS ")) ? (substr(stristr($pKeyName, " AS "), 4)) : $pKeyName;
     $pKeyName = (strpos($pKeyName, ".")) ? (substr(stristr($pKeyName, "."), 1)) : $pKeyName;
     while ($row = $result->fetch_assoc()):
           if ($pKeyName != "") :
              $retArray[$row[$pKeyName]]= $row[$pValName];
           else :
              array_push($retArray, $row[$pValName]);
           endif;
     endwhile;
     $result->free();
     return $retArray;
}


// Gets array (matrix) of a result set by SQL statement using "$row" only
// $sqlQuery : valid SQL statement
function getMatrixFromDbResultByStatement ($sqlStmt, $dbConnection = "") {
     global $db, $PHP_SELF;
     if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;
     $retArray = array();
     if ($sqlStmt != "") :
        $result = $dbConnection->dbQ($sqlStmt);
        while ($row = $result->fetch_assoc()):
              $retArray[] = $row;
        endwhile;
        $result->free();
     endif;
     return $retArray;
}


// Checks the existence of a specified field-combination of a certain table
function existsEntry($table,$fields,$dbConnection = "") {
     global $db, $PHP_SELF;
     if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;
     
     $fs = "";
     $whereClause = "";
     $fieldsLength = count($fields);          
     for ($i = 0; $i < $fieldsLength; $i += 2) :
       $fs .= $fields[$i];
       $whereClause .= $fields[$i] . " = '" . $fields[$i + 1] . "'";
       if ($i < $fieldsLength - 2) :
         $fs .= ",";
         $whereClause .= " AND ";
       endif;
     endfor;  
     if ($whereClause != "") : 
       $whereClause = " WHERE " . $whereClause;
     endif;

     $retValue = FALSE;
     $sqlStmt = "SELECT $fs FROM $table $whereClause";
     $result = $dbConnection->dbQ($sqlStmt);
     while ($row = $result->fetch_assoc()):
           $retValue = TRUE;
     endwhile;
     $result->free();  
     
     return $retValue;
}   

// Returns the cardinality of a table
function getCountOfTable($table, $whereClause = "", $dbConnection = "") {
     global $db, $PHP_SELF;
     if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;

     $retValue = -1;
     $sqlStmt = "SELECT count(*) AS cardinality FROM $table";
     if ($whereClause != "") : 
       $sqlStmt .= " WHERE " . $whereClause;
     endif;
     $result = $dbConnection->dbQ($sqlStmt);     
     while ($row = $result->fetch_assoc()):
           mcArrIsSet($row, "cardinality");
           $retValue = $row["cardinality"];
     endwhile;
     $result->free();  
     
     return $retValue;
}

// Returns the cardinality of a table
function getSumOfTable($table, $field, $whereClause = "", $dbConnection = "") {
     global $db, $PHP_SELF;
     if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;
     
     $retValue = -1;
     if ($field != "") :
        $sqlStmt = "SELECT SUM(" . $field . ") AS amount FROM $table";
        if ($whereClause != "") : 
          $sqlStmt .= " WHERE " . $whereClause;
        endif;
        $result = $dbConnection->dbQ($sqlStmt);
        while ($row = $result->fetch_assoc()):
              $retValue = $row["amount"];
        endwhile;
        $result->free();
     endif;
     
     return $retValue;
}

// Returns the max-value of a specified field of a table
function getMaxOfField($table, $field, $whereClause = "", $dbConnection = "") {
     global $db, $PHP_SELF;
     if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;

     $retValue = "";
     $sqlStmt = "SELECT max(" . trim($field) . ") AS max_val FROM " . $table;
     if ($whereClause != "") : 
       $sqlStmt .= " WHERE " . $whereClause;
     endif;
     $result = $dbConnection->dbQ($sqlStmt);     
     while ($row = $result->fetch_assoc()):
           $retValue = $row["max_val"];
     endwhile;
     $result->free();  
     
     return $retValue;
}   

// Returns the max-value of a specified field of a table
function getMinOfField($table, $field, $whereClause = "", $dbConnection = "") {
     global $db, $PHP_SELF;
     if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;

     $retValue = "";
     $sqlStmt = "SELECT min(" . trim($field) . ") AS min_val FROM " . $table;
     if ($whereClause != "") : 
       $sqlStmt .= " WHERE " . $whereClause;
     endif;
     $result = $dbConnection->dbQ($sqlStmt);     
     while ($row = $result->fetch_assoc()):
           $retValue = $row["min_val"];
     endwhile;
     $result->free();  
     
     return $retValue;
} 

// Get crypted database password from a string
function cryptDbPassword($passwordToBeCrypted) {
  global $db, $PHP_SELF;
  $retVal = "";
  $passwordToBeCrypted = trim($passwordToBeCrypted);
  if ($passwordToBeCrypted != "") :
     $retVal = $db->getOne("SELECT PASSWORD('" . $passwordToBeCrypted . "')");
  endif;
  return $retVal;
}

// Creates HTML-Options from the contents of the fields with an optional WHERE-clause
function addOptionsFromTable($table, $idField, $textField, $orderByField, $whereClause = "", $selVal = "", $distinct = "", $dbConnection = "") {
  global $PHP_SELF, $db;
  global $htmlEntitiesFlags, $htmlEntitiesCharset;
  if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;

  $whereClause = ($whereClause == "") ? "" : "WHERE $whereClause";
  if (trim($distinct) != "") : $distinct = "DISTINCT"; endif;
  $sqlStmt = "SELECT $distinct $idField, $textField FROM $table $whereClause ORDER BY $orderByField";
  $result = $dbConnection->dbQ($sqlStmt);
  $options = "";
  $idField = (strpos($idField, ".")) ? (substr(stristr($idField, "."), 1)) : $idField;
  $textField = (strpos($textField, " AS ")) ? (substr(stristr($textField, " AS "), 4)) : $textField;
  $textField = (strpos($textField, ".")) ? (substr(stristr($textField, "."), 1)) : $textField;
  $selVal = htmlentities($selVal, $htmlEntitiesFlags, $htmlEntitiesCharset);
  while ($row = $result->fetch_assoc()):  
    $id = htmlentities($row[$idField], $htmlEntitiesFlags, $htmlEntitiesCharset);
    $text = htmlentities($row[$textField], $htmlEntitiesFlags, $htmlEntitiesCharset);
    if ($selVal == "" || !($selVal === $id)) :
       $options .= "<option value=\"$id\">$text</option>\n";
    else :
       $options .= "<option value=\"$id\" selected>$text</option>\n";
    endif;
  endwhile;
  $result->free();
  return $options;
}

// Creates HTML-Checkboxes from the contents of the fields with an optional WHERE-clause
function addCheckboxesFromTable($name, $table, $idField, $textField, $orderByField, $whereClause = "", $selVal = "", $spacer = "", $readonly = "", $noHtmlEntities = "", $jsFunctionName = "", $dbConnection = "") {
  global $PHP_SELF, $db;
  global $htmlEntitiesFlags, $htmlEntitiesCharset;
  if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;
                
  $whereClause = ($whereClause == "") ? "" : "WHERE $whereClause";
  $sqlStmt = "SELECT $idField, $textField AS textfield FROM $table $whereClause ORDER BY $orderByField";
  $result = $dbConnection->dbQ($sqlStmt);
  $output = "";
  $idField = (strpos($idField, ".")) ? (substr(stristr($idField, "."), 1)) : $idField;
  $textField = (strpos($textField, ".")) ? (substr(stristr($textField, "."), 1)) : $textField;
  $jsFunction = "";
  while ($row = $result->fetch_assoc()):
    if ($noHtmlEntities != "") :
      $id = $row[$idField];
      $text = $row["textfield"];
    else :
      $id = htmlentities($row[$idField], $htmlEntitiesFlags, $htmlEntitiesCharset);
      $text = htmlentities($row["textfield"], $htmlEntitiesFlags, $htmlEntitiesCharset);
    endif;
    if ($jsFunctionName != "") : 
       $jsFunction = " onclick=\"" . $jsFunctionName . "('" . $id . "');\" ";
    endif;
    if (is_array($selVal)) :
       if (is_array($readonly)) :
          $output .= "<input type=\"checkbox\" name=\"" . $name . "[]\" value=\"" . $id . "\" " . $jsFunction . " " . (in_array($id, $selVal) ? "checked" : "") . " " . (in_array($id, $readonly) ? "disabled" : "") . ">" . $text;
       else :
          $output .= "<input type=\"checkbox\" name=\"" . $name . "[]\" value=\"" . $id . "\" " . $jsFunction . " " . (in_array($id, $selVal) ? "checked" : "") . " " . ($readonly != "" && $readonly == $id ? "disabled" : "") . ">" . $text;
       endif;
    else :
       if (is_array($readonly)) :
          $output .= "<input type=\"checkbox\" name=\"" . $name . "[]\" value=\"" . $id . "\" " . $jsFunction . " " . ($selVal != "" && $selVal == $id ? "checked" : "") . " " . (in_array($id, $readonly) ? "disabled" : "") . ">" . $text;
       else :
          $output .= "<input type=\"checkbox\" name=\"" . $name . "[]\" value=\"" . $id . "\" " . $jsFunction . " " . ($selVal != "" && $selVal == $id ? "checked" : "") . " " . ($readonly != "" && $readonly == $id ? "disabled" : "") . ">" . $text;
       endif;
    endif;
    if ($spacer != "") : $output .= $spacer; endif;
  endwhile;
  $result->free();
  return $output;
}

// Returns last autoincrement-value of previous INSERT/UPDATE
function getLastInsertID($dbConnection = "") {
  global $db;
  if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;

  $lastInsertId = $dbConnection->getOne("SELECT LAST_INSERT_ID()");
  return $lastInsertId;
}

// Checks if specified address exists in db and saves it if new
// If all values in $ad_street, $ad_zipcode and $ad_city are empty,
// then existing addressnumber is taken from costcenternumber
// If one or two values in $ad_street, $ad_zipcode and $ad_city are empty,
// then the missing values are taken from existing address that
// belongs to costcenternumber
// Returns new or existing address_id and housenumber of existing address,
// if existing address was taken from costcenternumber
//
// If address is new, its validity will be checked;
// if invalid, the first parameter in the return-list (ad_id) is empty,
// the last parameter contains an error-Message
function insertAddress($ad_street, $ad_zipcode, $ad_city, $csc_id = "", $ad_country = "DE", $ignoreInvalidity = false, $dbConnection = "") {
  global $db, $PHP_SELF, $toursubmit;

  if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;

  $ad_streetArr = explode("|", $ad_street);
  $ad_street = trim($ad_streetArr[0]);
  $tr_hsno = "";
  if (isset($ad_streetArr[1]))
    $tr_hsno = trim($ad_streetArr[1]);
  $ad_zipcode = trim($ad_zipcode);
  $ad_city = trim($ad_city);
  $ad_country = trim($ad_country);
  if ($ad_country == "") : $ad_country = "DE"; endif;

  // Wenn mind. ein Feld in der übergebenen Adresse nicht leer ist, die csc_id aber leer ist,
  // dann müssen die fehlenden Angaben ergänzt werden, ansonsten würde die nachfolgende
  // DB-Abfrage in einen Error laufen
  if ($csc_id == "" && ($ad_street == "" || $ad_zipcode == "" || $ad_city == "")):
    if ($ad_street == "")
      $ad_street = "(ohne Angabe)";
    if ($ad_zipcode == "")
      $ad_zipcode = "(ohne Angabe)";
    if ($ad_city == "")
      $ad_city = "(ohne Angabe)";
  endif;

  // Wenn mind. ein Feld in der übergebenen Adresse nicht leer ist, dann müssen die
  // fehlenden Angaben aus der Kostenstellenadresse übernommen werden
  if ($ad_street == "" || $ad_zipcode == "" || $ad_city == ""):
    $sqlStmt = "SELECT costcenteraddress.ad_id, costcenteraddress.cscad_hsno," .
      " costcenteraddress.cscad_comp," .
      " costcenteraddress.cscad_remark, costcenteraddress.cscad_person, costcenteraddress.cscad_phone" .
      " FROM costcenteraddress INNER JOIN costcenter ON costcenteraddress.csc_id = costcenter.csc_id" .
      " WHERE costcenteraddress.csc_id = $csc_id AND costcenteraddress.adt_id = 4";
    $result = $dbConnection->query($sqlStmt)
      or die ("$PHP_SELF, function 'insertAddress': " .
        "Wert '$csc_id' in Parameter 'csc_id' ist ung&uuml;ltig (keine Adresse gefunden)!");
    if ($dbConnection->connect_errno) die ("$PHP_SELF: <br>$sqlStmt<br>" . $dbConnection->connect_error);
    $row = $result->fetch_assoc();
    if (!is_array($row)):
      var_dump($row);
      $fileHandle = @fopen("../log/dbglobal.inc._" . date("Ym") . ".log", 'a');
      @fwrite($fileHandle, "[" . date("Y-m-d H:i:s") . "] " . var_dump($row) .  "\n");
      @fclose($fileHandle);
    endif;
    $ad_id = $row["ad_id"];
    $hsno = $row["cscad_hsno"];
    $comp = $row["cscad_comp"];
    $remark = $row["cscad_remark"];
    $person = $row["cscad_person"];
    $phone = $row["cscad_phone"];
    $result->free();  
    // Wenn alle Felder in der übergebenen Adresse leer sind, dann ist hier Schluss
    // und die ermittelten Werte für ad_id und hsno werden zurückgegeben
    if ($ad_street == "" && $ad_zipcode == "" && $ad_city == ""):
      return (array($ad_id, $hsno, $comp, $remark, $person, $phone));
    // Wenn ein oder zwei Felder in der übergebenen Adresse leer sind, dann
    // werden die fehlenden Angaben aus der Kostenstellenadresse ermittelt
    else:
      $result = $dbConnection->query("SELECT address.ad_street, address.ad_zipcode, address.ad_country " .
        "FROM address, costcenteraddress WHERE address.ad_id = '$ad_id' " .
        "AND costcenteraddress.ad_id = '$ad_id' AND costcenteraddress.adt_id = '4'")
        or die ("$PHP_SELF, function 'insertAddress': " .
          "Interner Fehler: Keine Lieferadresse für Wert '$csc_id' in Parameter 'csc_id' gefunden!");
      if ($dbConnection->connect_errno)
        die ("$PHP_SELF, function 'insertAddress': " . $dbConnection->connect_error);
      $row = $result->fetch_assoc();
      if ($ad_street == "")
        $ad_street = $row["ad_street"];
      if ($ad_zipcode == "")
        $ad_zipcode = $row["ad_zipcode"];
      if ($ad_country == "")
        $ad_country = $row["ad_country"];
      $result->free();
    endif;
  endif;

  $ad_street_tmp = $ad_street;
  while (!strpos($ad_street_tmp, "\\") === FALSE)
    $ad_street_tmp = str_replace("\\", "", $ad_street_tmp);
  // Ab hier liegt auf jeden Fall eine vollständige Adresse vor, deren Vorhandensein
  // in der DB überprüft werden muss; ist sie noch nicht vorhanden, wird sie angelegt
  $ad_zipcode_search = $ad_zipcode;
  $ad_city_search = $ad_city;
  $ad_street_search = $ad_street_tmp;
  if (MASK_CR_PRICE_MODE == "1" && getParameterValue("0", "MASK_CR_PRICE_MODE_CHECK_CHARS", "0") == "1" && isset($toursubmit) && $toursubmit == "Senden") {
    // 18.04.2023: Notmaßnahme wg. Zeichensatzprobleme
    $ad_zipcode_search = my_str_check_mobile($ad_zipcode);
    $ad_city_search = my_str_check_mobile($ad_city);
    $ad_street_search = my_str_check_mobile($ad_street_tmp);
  }
  $sqlStmt = "SELECT ad_id FROM address WHERE ad_street = '" . my_str_check($ad_street_search) . "' " .
    "AND ad_zipcode = '" . my_str_check($ad_zipcode_search) . "' AND ad_city = '" . my_str_check($ad_city_search) . "' AND ad_country = '$ad_country'";
//echo $sqlStmt . "\n<br>";
  $ad_id = $dbConnection->getOne($sqlStmt);
  if ($dbConnection->connect_errno) die ("$PHP_SELF: <br>$sqlStmt<br>" . $dbConnection->connect_error);
  if ($ad_id == ""):
  // neue Adresse, deren Gültigkeit muss überprüft werden
    if ($tr_hsno == ""):
      $addressValid = getGeoCoordinates($ad_street, $ad_zipcode, $ad_city, "1");
      if ($addressValid == "" && $ignoreInvalidity == false):
        $statusMessage = getLngt("Der Adress-Server kennt die folgende Adresse nicht:") . "\\n";
      else:
      // Check zipcode and city
        // 04.01.2019: as citynames now sometimes are concatenated like "name - district" (e. g. "Rangsdorf - Groß Machnow"), the district has to be deleted from the cityname before the check 
        $ad_city_check = $ad_city;
        if (!(strpos($ad_city, " - ") === false))
          $ad_city_check = substr($ad_city, 0, strpos($ad_city, " - ") - 1);
        $addressValidityArray =
          checkCityZipcode($ad_zipcode, $ad_city_check, $ad_street);
        if ($addressValidityArray[0] < 1 && $ignoreInvalidity == false):
          $statusMessage = getLngt("Die Postleitzahl passt nicht zum Ort und/oder zur Strasse:") . "\\n";
          $addressValid = "";
        endif;
      endif;
    else:
      $addressValid = "ok";
      $coords = get_coords($ad_country, my_str_check($ad_zipcode), my_str_check($ad_city), my_str_check($ad_street), my_str_check($tr_hsno));
      if ($coords[0] == 0 || $coords[1] == 0) {
        $statusMessage = "Google Maps kann folgende Adresse nicht finden:\\n\\n";
        $addressValid = "";
      }
    endif;
    if ($addressValid == "" && !$ignoreInvalidity):
      $statusMessage .=
        "'" . $ad_street . ($tr_hsno == "" ? "" : " ") . $tr_hsno . ", " . $ad_zipcode . " " . $ad_city . "'\\n\\n" . getLngt("Bitte korrigieren!");
      return (array("", "", "", "", $statusMessage));  
    endif;
    if (MASK_CR_PRICE_MODE == "1" && getParameterValue("0", "MASK_CR_PRICE_MODE_CHECK_CHARS", "0") == "1" && isset($toursubmit) && $toursubmit == "Senden") {
      // 18.04.2023: Notmaßnahme wg. Zeichensatzprobleme
      $ad_zipcode = my_str_check_mobile($ad_zipcode);
      $ad_city = my_str_check_mobile($ad_city);
      $ad_street = my_str_check_mobile($ad_street);
    }
    // address ok    
    insertStmt("address", array("ad_street", my_str_check($ad_street), "ad_zipcode", my_str_check($ad_zipcode), "ad_city", my_str_check($ad_city), "ad_country", $ad_country), $dbConnection);
    $ad_id = getLastInsertID($dbConnection);
  endif;
  
  mcIsSet($ad_id); mcIsSet($hsno); mcIsSet($comp); mcIsSet($remark); mcIsSet($person); mcIsSet($phone);
  return (array($ad_id, $hsno, $comp, $remark, $person, $phone));
}


// Gets the address of a company/courier/customer
function getAddress($id, $table = "company", $id2 = "", $dbConnection = "") {
  global $db, $PHP_SELF, $hq_id;
  if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;
  
  $address = array();
  $fieldClause = "";
  $fromClause = "";
  $whereClause = "";
  if ($table == "company" || $table == "cmp") :
     $fieldClause = ", cmp.cmp_comp AS comp, cmp.cmp_comp2 AS comp2, cmp.cmp_hsno AS hsno";
     $fromClause = ", company AS cmp";
     $whereClause = "cmp.cmp_id = '" . $id . "' AND cmp.ad_id = ad.ad_id";
  endif;
  if ($table == "customer" || $table == "cs") :
     $fieldClause = ", cmp.cmp_comp AS comp, cmp.cmp_comp2 AS comp2, cmp.cmp_hsno AS hsno";
     $fromClause = ", company AS cmp, customer AS cs";
     $whereClause = "cs.hq_id = '" . $hq_id . "' AND cs.cs_id = '" . $id . "' AND cmp.cmp_id = cs.cmp_id AND cmp.ad_id = ad.ad_id";
  endif;
  if ($table == "courier" || $table == "cr") :
     $fieldClause = ", cmp.cmp_comp AS comp, cmp.cmp_comp2 AS comp2, cmp.cmp_hsno AS hsno";
     $fromClause = ", company AS cmp, courier AS cr";
     $whereClause = "cr.hq_id = '" . $hq_id . "' AND cr.cr_id = '" . $id . "' AND cmp.cmp_id = cr.cmp_id AND cmp.ad_id = ad.ad_id";
  endif;
  if ($table == "headquarters" || $table == "hq") :
     $fieldClause = ", cmp.cmp_comp AS comp, cmp.cmp_comp2 AS comp2, cmp.cmp_hsno AS hsno";
     $fromClause = ", company AS cmp, headquarters AS hq";
     $whereClause = "hq.hq_id = '" . $id . "' AND cmp.cmp_id = hq.cmp_id AND cmp.ad_id = ad.ad_id";
  endif;
  if ($table == "costcenteraddress" || $table == "cscad") :
     if ($id2 == "") : $id2 = "4"; endif;  // Pick-up/Delivery address
     $fieldClause = ", cscad.cscad_comp AS comp, cmp.cmp_comp2 AS comp2, cscad.cscad_hsno AS hsno";
     $fromClause = ", costcenteraddress AS cscad, costcenter AS csc, customer AS cs";
     $whereClause = "cs.cs_id = '" . $id . "' AND cs.cs_id = csc.cs_id AND csc.csc_id = cscad.csc_id AND adt_id = '" . $id2 . "' AND cscad.ad_id = ad.ad_id";
  endif;

  $sqlquery = "SELECT ad.ad_id, ad.ad_street, ad.ad_zipcode, ad.ad_city, ad.ad_country" . $fieldClause 
               . " FROM address AS ad" . $fromClause
               . " WHERE " . $whereClause;

  $result = $dbConnection->dbQ($sqlquery);
  
  while ($row = $result->fetch_assoc()):  
    $address["id"]      = $row["ad_id"];
    $address["street"]  = $row["ad_street"];    
    $address["zipcode"] = $row["ad_zipcode"];
    $address["city"]    = $row["ad_city"];
    $address["country"] = $row["ad_country"];
    $address["hsno"]    = $row["hsno"];
    $address["comp"]    = $row["comp"];
    $address["comp2"]   = $row["comp2"];
  endwhile;
  $result->free();  

  return $address;
}      


// Check all specified parameters for existence and value in the beginning of a php-page
function checkPageParameterSettings($fields) {
   $retVal = "OK";     
   $fieldsLength = count($fields);          
   for ($i = 0; $i < $fieldsLength; $i++) :
     global ${$fields[$i]};
     if (!isset($$fields[$i])):
       global $HTTP_POST_VARS, $HTTP_GET_VARS, $GLOBALS;
       if(isset($HTTP_POST_VARS[$fields[$i]])):
         $GLOBALS[$fields[$i]] = $HTTP_POST_VARS[$fields[$i]];
       elseif(isset($HTTP_GET_VARS[$fields[$i]])):
         $GLOBALS[$fields[$i]] = $HTTP_GET_VARS[$fields[$i]];
       endif;
     endif;
     global ${$fields[$i]};
     if (!isset($$fields[$i]) || $$fields[$i] == "") :
        $retVal = "NOK";
     endif;
   endfor;     
   return $retVal;
}

// Define a special shortname ONLY if type-ids ("1", "2", ...) will be changed in the future
function getUserTypeName($userType) {
   $userTypeName = "";
   if ($userType == "1") : $userTypeName = "hq"; endif;
   if ($userType == "2") : $userTypeName = "cs"; endif;
   if ($userType == "3") : $userTypeName = "cr"; endif;
   if ($userType == "4") : $userTypeName = "stk"; endif;
   return $userTypeName;
}

// Get the empoyee-id of the root admin
function getEmpIdOfRootAdmin($userTypeName, $dbConnection = "") {
	global $db, $hq_id;
	 if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;
   $empIdRootAdmin = "";   
   if ($userTypeName == "hq") :
      global $hq_id;
      $empIdRootAdmin = getFieldValueFromId("headquarters","hq_id",$hq_id,"hq_admin",$dbConnection);
   endif;
   if ($userTypeName == "cs") :
      global $customerId;
      $empIdRootAdmin = getFieldValueFromId("customer","cs_id",$customerId,"cs_admin",$dbConnection);
   endif;
   return $empIdRootAdmin;
}

// Get the rights of the employee logged in
// These rights restrict the access to menu entries and corresponding scripts of ALL headquarters (of the current mandator).
// They have to be set and overrule the settings of the headquarters rights. If it is NOT set AND at least one headquarters
// right is set, the result is that the the right is NOT set and the access is denied.
function getRights($empId, $forceRestriction = "0", $dbConnection = "") {
	global $db, $hq_id;
	if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;
   $retVal = "";
   if ($empId != "") :
       $retVal = getFieldValueFromId("employee","emp_id",$empId,"emp_rights",$dbConnection);
       // Check for reduced rights regarding the ability to change headquarters according to callcenter mode
       if ($forceRestriction == "0") :
          $usrId = getFieldValueFromId("employee","emp_id",$empId,"usr_id",$dbConnection);
          $hqId = getFieldValueFromId("user","usr_id",$usrId,"hq_id",$dbConnection);
          if ($hq_id != "" && $hq_id > 0 && $hqId != $hq_id) :
             // If employee has headquarters rights then do NOT restrict access rights for the other headquarters.
             // But in case he/she has NOT, then do the following:
             if (substr($retVal,"10",1) != "1") :
                $retVal = "11101001110000000000000000000000000000000000000000";
             endif;
          endif;
       endif;
   endif;
   if ($retVal == "") : $retVal = "00000000000000000000000000000000000000000000000000"; endif;
   return $retVal;
}

// Get an associative array of the rights of a special employee
// The array is a matrix (hq_id, rgt_id) where the cells contain "1" if access is granted for the specified employee
function getEmpHqRights($empId, $dbConnection = "") {
	 global $db, $PHP_SELF, $hq_id, $userTypeName;
	 if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;
   $retArray = array();
   if ($userTypeName == "hq" && $empId != "") :
      $usrId = getFieldValueFromId("employee","emp_id",$empId,"usr_id",$dbConnection);
      $hqId = getFieldValueFromId("user","usr_id",$usrId,"hq_id",$dbConnection);
      if ($hq_id != "" && $hq_id > 0) :  //  && $hqId == $hq_id
         $sqlquery = "SELECT emprgt.hq_id, emprgt.rgt_id FROM employeerights AS emprgt WHERE emprgt.emp_id = '" . $empId . "'";
         $result = $dbConnection->dbQ($sqlquery);
         while ($row = $result->fetch_assoc()):
               $retArray[$row["hq_id"]][$row["rgt_id"]] = "1";
         endwhile;
         $result->free();
      endif;
   endif;
   return $retArray;
}

// Gets structure for accessing to headquarters
// (Needed for generating headquarters checkboxes, headquarters options, etc.)
function getHeadquartersAccessStructure($dbConnection = "") {
	global $md_id, $hq_id, $emp_id, $empGlobalMasterRights, $db;
  if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;

	$mdId = $md_id;
	if ($mdId == "" || !is_numeric($mdId)) :
	   $mdId = getFieldValueFromId("mandatorheadquarters", "hq_id", $hq_id, "md_id", $dbConnection);
	endif;

	// Check employee logged in for being root user
  $empIdRootAdmin = getEmpIdOfRootAdmin("hq", $dbConnection);

  // Get headquarters the employee has access to
	$empHqAccess = "";      // Init (e.g. reference error, no access to any headquarters)
	$mdHqVector = array();  // Init
  if ($mdId != "" && is_numeric($mdId) && $emp_id != "" && is_numeric($emp_id) && $emp_id > 0) :
     $mdHqVector = getColVectorFromDB2Array("mandatorheadquarters","md_id",$mdId,"hq_id","",$dbConnection);
     if ($empIdRootAdmin == $emp_id) :
        $empHqAccess = implode(",", $mdHqVector);
     else :
        // Restriction according to the headquarters access vector for the current employee logged in
        $empHqAccess = getFieldValueFromId("employee","emp_id",$emp_id,"emp_headquarters",$dbConnection);
     endif;
  endif;
  $numOfHq = 0;
  $empHqAccessArray = explode(",", $empHqAccess);

  // Check for right matrix having access to
  // Each script has to restrict the output regarding the rights set in "employeerights", e.g. in lists (customer or courier list) accessible headquarters for the employee logged in will be displayed only
  $empIdHqRgtVector = getEmpHqRights($emp_id, $dbConnection);  // Special headquarter rights of the user logged in (headquarter right matrix)
  if ($emp_id != $empIdRootAdmin) :
     $mdHqVectorLen = count($mdHqVector);       // All headquarters of the mandator
     $empGlobalMasterRightsLen = count($empGlobalMasterRights);
     $hqNoAccessByRightArray = array();
     for ($i = 0; $i < $mdHqVectorLen; $i++) :
        if ($mdHqVector[$i] != $hq_id) :
           for ($j = 0; $j < $empGlobalMasterRightsLen; $j++) :
               if ($empIdHqRgtVector[$mdHqVector[$i]][$empGlobalMasterRights[$j]] != "1") :
                  // Reduce array because employee has no access to the headquarters regarding to the current right of the right matrix
                  $hqNoAccessByRightArray[] = $mdHqVector[$i];
               endif;
           endfor;
        endif;
     endfor;
     if (count($hqNoAccessByRightArray) > 0) :
        $empHqAccessArray = array_diff($empHqAccessArray, $hqNoAccessByRightArray);
        $empHqAccessArray = array_values($empHqAccessArray);
     endif;
  endif;

  $numOfHq = count($empHqAccessArray);
  $empHqAccess = implode(",", $empHqAccessArray);

  return array($mdId, $empHqAccess, $numOfHq);
}

// Get the parameters of the employee (or headquarter [<=> $empId = "0"]) logged in
function getParameterArray($empId, $hqId = "", $retMode = "0", $dbConnection = "") {
   global $db, $PHP_SELF, $hq_id;
   if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;
   $retArray = array();
   if ($hqId == "") : $hqId = $hq_id; endif;
   
   // Check for existing (session) hq_id
   if ($hqId != "" && is_numeric($empId)) :
      $sqlquery = "SELECT par.par_id, par.par_key, par.par_value"
                  . " FROM parameter AS par"
                  . " WHERE par.emp_id = '$empId' AND par.hq_id = '$hqId'";

      $result = $dbConnection->dbQ($sqlquery);
      $count = 0;
      while ($row = $result->fetch_assoc()):
            if ($retMode == "0") :
               $retArray[$row["par_key"]] = array($row["par_id"],$row["par_value"]);   // E.g.: $retArray[MASK_MULTI_JOBLIST] = (10000,1)
            else :
               $retArray[$count] = array($row["par_key"],$row["par_value"]);   // E.g.: $retArray[0] = (MASK_MULTI_JOBLIST,1)
               $count++;
            endif;
      endwhile;
      $result->free();
   endif;
   return $retArray;
}

// Defines global constants
function defineGlobalParameters($hqId = "", $dbConnection = "") {
	global $db, $hq_id;
	if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;
	if ($hqId == "") : $hqId = $hq_id; endif;
  $globalParams = getParameterArray("0",$hqId,"1",$dbConnection);
  if ($globalParams != "") :
     $lenGlobalParams = count($globalParams);
     for ($gp = 0; $gp < $lenGlobalParams; $gp++) {
         if (!defined($globalParams[$gp][0])) : 
  	        define($globalParams[$gp][0], $globalParams[$gp][1]);
         endif;
     }
  endif;
}

// Get a special parameter of a single employee (or headquarters [<=> $empId = "0"]) logged in
function getParameterValue($empId, $key, $hqId = "", $mdId = "", $dbConnection = "") {
   global $db, $PHP_SELF, $md_id, $hq_id, $globalUseMdIdForDatabaseParameters;
   if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;
   $retVal = "";
   if ($mdId == "") : $mdId = $md_id; endif;
   if ($hqId == "") : $hqId = $hq_id; endif;
   if ($empId == "" || !is_numeric($empId)) : $empId = "0"; endif;
   $whereClause = "emp_id = '" . $empId . "' AND par_key = '" . $key . "' AND hq_id = '" . $hqId . "'";
   // IMPORTANT: Mandator is given implicitly by headquarters ($hqId > 0 => $mdId is specified)
   if (isset($globalUseMdIdForDatabaseParameters) && $globalUseMdIdForDatabaseParameters == "1" && $empId == "0" && $hqId == "0") :
      $whereClause .= " AND md_id = '" . $mdId . "'";
   endif;
   $retVal = getFieldValueFromClause("parameter","par_value",$whereClause,$dbConnection);
   if ($retVal == "" && $empId > "0") :
     // Get hq_id from table user for the current employee to check possible setting in original headquarters associated to the employee
     $usrId = getFieldValueFromId("employee","emp_id",$empId,"usr_id",$dbConnection);
     $usrHqId = getFieldValueFromId("user","usr_id",$usrId,"hq_id",$dbConnection);
     $retVal = getFieldValueFromClause("parameter","par_value","emp_id = '" . $empId . "' AND par_key = '" . $key . "' AND hq_id = '" . $usrHqId . "'",$dbConnection);
   endif;
   return $retVal;
}

// Get parameter ID by "par_key", "hq_id", "emp_id" (and md_id)
function getParameterId ($parKey, $hqId = "0", $empId = "0", $mdId = "0", $dbConnection = "") {
	 global $db, $PHP_SELF, $md_id, $hq_id, $globalUseMdIdForDatabaseParameters;
	 if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;
   $parKey = trim($parKey);
   $whereClause = "emp_id = '" . $empId . "' AND par_key = '" . $parKey . "' AND hq_id = '" . $hqId . "'";
   // IMPORTANT: Mandator is given implicitly by headquarters ($hqId > 0 => $mdId is specified)
   if (isset($globalUseMdIdForDatabaseParameters) && $globalUseMdIdForDatabaseParameters == "1" && $empId == "0" && $hqId == "0") :
      $whereClause .= " AND md_id = '" . $mdId . "'";
   endif;
   $retVal = getFieldValueFromClause("parameter","par_id",$whereClause,$dbConnection);
   return $retVal;
}

// Get a special parameter of a single employee (or headquarters [<=> $empId = "0"]) logged in
function setParameterValue ($parKey, $parValue, $parText = "", $parId = "", $hqId = "0", $empId = "0", $mdId = "0", $dbConnection = "") {
	 global $db, $PHP_SELF, $md_id, $hq_id, $globalUseMdIdForDatabaseParameters;
	 if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;
   $parKey = trim($parKey);
   // $parValue = trim($parValue);
   if ($parId == "" && $parKey != "") :
      $parId = getParameterId($parKey, $hqId, $empId, $mdId, $dbConnection);
      if ($parId != "") :
         $parKey = "";
      endif;
   endif;
   if ($parId != "" && is_numeric($parId)) :
      $updateArray = array("par_value",$parValue);
      if ($parKey != "") :
         array_push($updateArray, "par_key", $parKey);
      endif;
      if ($parText != "") :
         array_push($updateArray, "par_text", $parText);
      endif;
      $mdClause = "";
      if (isset($globalUseMdIdForDatabaseParameters) && $globalUseMdIdForDatabaseParameters == "1" && $empId == "0" && $hqId == "0") :
         $mdClause = " AND md_id = '" . $mdId . "'";
      endif;
      updateStmt("parameter","par_id",$parId,$updateArray,"hq_id = '" . $hqId . "' AND emp_id = '" . $empId . "'" . $mdClause,$dbConnection);
   else :
      if ($parKey != "") :
         $insertArray = array("par_key",$parKey,"par_value",$parValue,"hq_id",$hqId,"emp_id",$empId,"par_text",$parText);
         if (isset($globalUseMdIdForDatabaseParameters) && $globalUseMdIdForDatabaseParameters == "1" && $empId == "0" && $hqId == "0") :
            array_push($insertArray, "md_id", $mdId);
         endif;
         insertStmt("parameter", $insertArray, $dbConnection);
         $parId = getLastInsertId($dbConnection);
      endif;
   endif;
   return $parId;
}

// Get a special parameter with specified object id
function getObjectBasedParameterValue($key, $objId = "", $hqId = "", $empId = "", $noGlobalCheck = "", $mdId = "", $dbConnection = "") {
   global $db, $PHP_SELF, $md_id, $hq_id;
   if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;
   $retVal = "";
   $key = trim($key);
   if ($key != "") :
      // if ($mdId == "" || !is_numeric($mdId)) : $mdId = "0"; endif;
      if ($hqId == "" || !is_numeric($hqId)) : $hqId = "0"; endif;
      if ($empId == "" || !is_numeric($empId)) : $empId = "0"; endif;
      if ($objId != "" && is_numeric($objId)) : 
            $retVal = getParameterValue($empId, $key . "_" . $objId, $hqId, $mdId, $dbConnection);
            if ($retVal == "") : $retVal = getParameterValue("0", $key . "_" . $objId, $hqId, $mdId, $dbConnection); endif;
            if ($retVal == "") : $retVal = getParameterValue($empId, $key . "_" . $objId, "0", $mdId, $dbConnection); endif;
            if ($retVal == "") : $retVal = getParameterValue("0", $key . "_" . $objId, "0", $mdId, $dbConnection); endif;
      endif;
      if ($retVal == "" && $noGlobalCheck == "") : 
         $retVal = getParameterValue($empId, $key, $hqId, $mdId, $dbConnection);
         if ($retVal == "") : $retVal = getParameterValue("0", $key, $hqId, $mdId, $dbConnection); endif;
         if ($retVal == "") : $retVal = getParameterValue($empId, $key, "0", $mdId, $dbConnection); endif;
         if ($retVal == "") : $retVal = getParameterValue("0", $key, "0", $mdId, $dbConnection); endif;
      endif;
   endif;
   return $retVal;
}

// Transaction operations
function TA($op = "", $dbConnection = "") {
   global $db, $PHP_SELF, $md_id, $hq_id, $phpVersion;
   if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;
   $res =  "";
   $taStatus = "";
   if (TA_STATUS == "1") :
      $taStatus = "1";
   endif;
   if ($taStatus != "1") :
      // if ($mdId == "" || !is_numeric($mdId)) : $mdId = "0"; endif;
      $taStatus = getParameterValue("0", "TA_STATUS", $hq_id, "", $dbConnection);
      if ($taStatus != "1") : $taStatus = getParameterValue("0", "TA_STATUS", "0", "", $dbConnection); endif;
   endif;
   if ($taStatus) :
      $op = strtoupper($op);
      if ($phpVersion >= "8.2") :
         // if (!$dbConnection->supports('transactions')) {echo "TA-ERR!"; exit(); }
         if ($op == "B" || $op == "BEGIN") :
            $res = $dbConnection->dbTransactionBegin();
            // $TA_SavepointCounter++;
            // array_push($TA_SavepointStack, $TA_SavepointCounter);
            $dbConnection->dbQ('SET AUTOCOMMIT = 0');
         elseif ($op == "C" || $op == "COMMIT") :
            $res = $dbConnection->dbTransactionCommit();
         elseif ($op == "R" || $op == "ROLLBACK") :
            $res = $dbConnection->dbTransactionRollback();
         elseif ($op == "E" || $op == "END") :
            $res = $dbConnection->dbTransactionBegin();
            // $TA_SavepointCounter = array_pop($TA_SavepointStack);
            $dbConnection->dbQ('SET AUTOCOMMIT = 1');
         else :
            $res = "";
         endif;
      elseif ($phpVersion >= "7.0") :
         if (!$dbConnection->supports('transactions')) {echo "TA-ERR!"; exit(); }
         // global $TA_SavepointStack, $TA_SavepointCounter;  // Get global TA savepoint stack and counter
         if ($op == "B" || $op == "BEGIN") :
            $res = $dbConnection->beginTransaction();
            // $TA_SavepointCounter++;
            // array_push($TA_SavepointStack, $TA_SavepointCounter);
            $dbConnection->query('SET AUTOCOMMIT = 0');
         elseif ($op == "C" || $op == "COMMIT") :
            $res = $dbConnection->commit();
         elseif ($op == "R" || $op == "ROLLBACK") :
            $res = $dbConnection->rollback();
         elseif ($op == "E" || $op == "END") :
            $res = $dbConnection->beginTransaction();
            // $TA_SavepointCounter = array_pop($TA_SavepointStack);
            $dbConnection->query('SET AUTOCOMMIT = 1');
         else :
            $res = "";
         endif;
      else :
         switch($op) {      	 
            case "BEGIN" :    $res = $dbConnection->autoCommit(false); break;
            case "B" :        $res = $dbConnection->autoCommit(false); break;
            case "END" :      $res = $dbConnection->autoCommit(true); break;
            case "E" :        $res = $dbConnection->autoCommit(true); break;
            case "COMMIT" :   $res = $dbConnection->commit(); break;
            case "C" :        $res = $dbConnection->commit(); break;
            case "ROLLBACK" : $res = $dbConnection->rollback(); break;
            case "R" :        $res = $dbConnection->rollback(); break;
            default :         $res =  "";
         };
      endif;
   endif;
   if ($db->connect_errno) : 
      $res = $db->rollback();
   endif;
   return $res;
}

// Insert PDA commands depending of current job operation
function insertPDACommand($hqId, $crId, $command, $mode, $param, $execTime, $execTimelimit, $dbConnection = "") {
	global $db, $PHP_SELF;
	if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;
  $retBool = FALSE;  
  // Set execution time to current time if empty
  if ($execTime == ""): $execTime = getDateTime("0"); endif;  
  // If no timelimit is needed set it far away in the future
  if ($execTimelimit == ""): $execTimelimit = getDateTime("datetime_plus_offset", array(0,0,0,0,0,10), $formatStr = "Y-m-d H:i:s"); endif;
  if (TRUE) :
     insertStmt("phoenix_pda.commandexec", array("cr_id", $crId, "hq_id", $hqId, "cmd_command", $command, 
                "cmde_exec_time", $execTime, "cmde_exec_timelimit", $execTimelimit, 
                "cmde_mode", $mode, "cmde_param", $param), $dbConnection);
     $retBool = TRUE;
  endif;
  return $retBool;
}

// Write DB log
function writeToLogDB($logoId, $hqId, $jbId, $usrId, $crId, $crSid, $csId, $logoDescription, $atId = 0, $ptId = 0, $empId = 0, $dbConnection = "") {
   global $db, $PHP_SELF;
   if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;
   $retBool = FALSE;
   $constLogDB = getParameterValue("0", "LOG_DB", $hqId, "", $dbConnection);
   if ($constLogDB == "1") :
      $tmpArray = array("logo_id", intval($logoId), "hq_id", intval($hqId), "jb_id", intval($jbId), "usr_id", intval($usrId), "cr_id", intval($crId), "cr_sid", $crSid,
                        "cs_id", intval($csId), "at_id", intval($atId), "pt_id", intval($ptId), "emp_id", intval($empId), "logo_description", $logoDescription);
      insertStmt("phoenix_log.log", $tmpArray, $dbConnection);
      $retBool = TRUE;
   endif;
   return $retBool;
}

// Extend aasociative array based on list with keys and value (e.g.: key_1,value_1,key_2,value_2,key_3,value_3,key_4,value_4,....)
function arrayAssocPush(&$assocArray, $keysAndValue) {
   $keysAndValueLength = count($keysAndValue);          
   for ($i = 0; $i < $keysAndValueLength; $i += 2) :
       $assocArray[$keysAndValue[$i]] = $keysAndValue[$i + 1];
   endfor;
}

// Write DB log by associative array
function writeParArrToLogDB(&$parArr, $dbConnection = "") {
   global $db, $PHP_SELF;
   if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;
   $retBool = FALSE;
   $constLogDB = "";
   if ($parArr["hq_id"] != "" && is_numeric($parArr["hq_id"])) :
      $constLogDB = getParameterValue("0", "LOG_DB", $parArr["hq_id"], "", $dbConnection);
   endif;
   if ($constLogDB == "1") :
      $tmpKeyArr = array_keys($parArr);
      $tmpKeyArrLen = count($tmpKeyArr);
      $insertArray = array();
      for ($i = 0; $i < $tmpKeyArrLen; $i++) :
          array_push($insertArray, $tmpKeyArr[$i], $parArr[$tmpKeyArr[$i]]);
      endfor;
      
// $insertArray = array("logo_id", $parArr["logo_id"], "hq_id", $parArr["hq_id"], "jb_id", $parArr["jb_id"], "usr_id", $usrId, "cr_id", $crId, "cr_sid", $crSid, "cs_id", $csId, "at_id", $atId, "pt_id", $ptId, "emp_id", $empId, "logo_description", $logoDescription);
      insertStmt("phoenix_log.log", $insertArray, $dbConnection);
      $retBool = TRUE;
   endif;
   $parArr = array();  // Init array called by reference because of next call of this function will NOT write the same values (!!!!)
   return $retBool;
}

// Gets the country codes according to the parameter settings
function getCountryCodesAsOptions($countryCodeDefault, $idField = "cou_iso_2", $textField = "cou_name", $orderByField = "cou_name", $groupField = "cou_continent", $dbConnection = "") {
   global $db, $PHP_SELF;
   global $hq_id;
   if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;

   if ($countryCodeDefault == "") :
      $constMaskCountryDefault = getParameterValue("0", "MASK_COUNTRY_DEFAULT", $hq_id, "", $dbConnection);
      if ($constMaskCountryDefault == "") : $constMaskCountryDefault = "DE"; endif;
      $countryCodeDefault = $constMaskCountryDefault;
   endif;

   $constMaskCountryGroup = getParameterValue("0", "MASK_COUNTRY_GROUP", $hq_id, "", $dbConnection);
   if (!is_numeric($constMaskCountryGroup) || $constMaskCountryGroup == "") : $constMaskCountryGroup = "1"; endif;
   $tmpCountEntries = getCountOfTable("phoenix_special.country", "cou_continent= '" . $constMaskCountryGroup . "'", $dbConnection);

   if ($tmpCountEntries > 0) :
      $retValue = addOptionsFromTable("phoenix_special.country",$idField,$textField,$orderByField,$groupField . " = '" . $constMaskCountryGroup . "'",$countryCodeDefault,"",$dbConnection);
   else :
      $retValue = "<option value=" . $constMaskCountryDefault . " selected>" . $constMaskCountryDefault . "</option>\n";
   endif;
   return $retValue;
}

// Gets the global unique DB instance number by checking hardcodes LIVE flag
function getGlobalUniqueDbInstanceNo () {
	global $GLOBAL_DB_IS_LIVE, $dbhost;
	if (!isset($GLOBAL_DB_IS_LIVE)) : $GLOBAL_DB_IS_LIVE = false; endif;
	$constGlobalDbInstNo = getParameterValue("0", "GLOBAL_UNIQUE_DB_INSTANCE_NO", "0", "0");
	if (!$GLOBAL_DB_IS_LIVE && $constGlobalDbInstNo < 100) :
	   $errMsg = "Parameter GLOBAL_UNIQUE_DB_INSTANCE_NO on " . $dbhost . " discloses LIVE DB, but seems to be TEST supposedly!";
	   sendInternalMail($errMsg);
	   echo $errMsg . "<br> Please contact administrator! <br>";
	   die();
	endif;
	return $constGlobalDbInstNo;
}
?>
