<?php
/*=======================================================================
 *
 * mcglobal.inc.php
 *
 * Autor: Marc Vollmann
 *
 =======================================================================*/

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

getLanguage(__FILE__);

// Returns the tablenames of a specified database especially in mysql.
// $dbname      : gets the name of the database which tables should be listed
// $returnMode  : sets the mode to return the tablenames
//                0 = returns the array (default)
//                1 = returns a string containing the names separated by $delimiter
// $delimiter   : used in some modes of $returnMode
/*
function getTableNames($dbname,$returnMode = 0, $delimiter = ",") {
    global $PHP_SELF,$dbhost,$dblogin,$dbpassword;
    $tableNames = array();    
    if (!mysql_connect($dbhost,$dblogin,$dbpassword)) {
    	die ("$PHP_SELF: No conection to mysql!");
    }
    $result = mysql_list_tables($dbname);    
    if (!$result) {
    	die ("$PHP_SELF: DB Error, could not list tables!");
    }    
    while ($row = mysql_fetch_row($result)) {
        $tableNames[] = $row[0];
    }
    mysql_free_result($result);
    if ($returnMode == 1) {return implode($delimiter,$tableNames);};
    return $tableNames;
}
*/

// Returns the fieldnames of a specified table especially in mysql.
// $dbname      : gets the name of the database to connect
// $tableName   : gets the name of the table which fields should be listed
// $fieldPrefix : each field gets the specified prefix (e.g. "tablename.")
// $returnMode  : sets the mode to return the fieldnames
//                0 = returns the array (default)
//                1 = returns a string containing the names separated by $delimiter
//                2 = like 1 plus the table
// $delimiter   : used in some modes of $returnMode
/*
function getFieldNames($dbname,$tableName,$fieldPrefix = "",$returnMode = 0, $delimiter = ",") {
    global $PHP_SELF,$dbhost,$dblogin,$dbpassword;
    $fieldNames = array();    
    if (!mysql_connect($dbhost,$dblogin,$dbpassword)) {
    	die ("$PHP_SELF: No conection to mysql!");
    }    
    $fields = mysql_list_fields($dbname,$tableName);
    $columns = mysql_num_fields($fields);        
    for ($i = 0; $i < $columns; $i++) {
        $fieldNames[] =  $fieldPrefix . mysql_field_name($fields, $i);
    }
    if ($returnMode == 1) {return implode($delimiter,$fieldNames);};
    return $fieldNames;
}
*/

// Writes a string to a file optional with or without linefeed
function writeToFile($fileName, $stringToOperate, $mode = 'a', $noLf = "") {
  if (is_array($stringToOperate)) {
    writeLog_("../log/mc_global_", "\$fileName = |" . var_dump($fileName) . "|, \$stringToOperate = |" . var_dump($stringToOperate) . "|, \$mode = |" . var_dump($mode) . "|, \$noLf = |" . var_dump($noLf) . "|");
    return 0;
  }
  $fileHandle = fopen($fileName, $mode);
  if ($noLf == "") : $stringToOperate .= "\n"; endif;
  $opCode = fwrite($fileHandle, $stringToOperate);
  fclose($fileHandle);
  return $opCode;
}

// Reads the content of a file optional with a specified length
function readFromFile ($fileName, $lenToRead = "", $mode = 'r') {
  if ($lenToRead == "") : $lenToRead = filesize($fileName); endif;
  $fileHandle = fopen($fileName, $mode);
  $contents = fread($fileHandle, $lenToRead);
  fclose($fileHandle);
  return $contents;
}

// Encrypts a specified file according to the given key and corresponding user
function encryptFile ($fileName, $keyUser, $publicKey) {
  $retBool = FALSE;
  if ($fileName != "" && $keyUser != "") :
     if (file_exists($fileName)) :
        // $command = GPG_PATH . "gpg -e -r " . $keyUser . " " . $fileName . " >xxx" . $fileName;
        $command = GPG_PATH . "gpg -e -r " . $keyUser . " " . $fileName;
        $result = exec($command, $encrypted, $errorcode);
        if ($errorcode == "0") :
           $retBool = TRUE;
        endif;
     endif;
  endif;
  return $retBool;
}


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

// Generates the SQL-statement from the values
function generateStatement($fieldClause,$fromClause,$whereClause,$orderByClause) {	
   $sqlStatement = "SELECT " . $fieldClause . " FROM " . $fromClause . " ";
   if ($whereClause != "") : $sqlStatement .= " WHERE " . $whereClause . " "; endif;
   if ($orderByClause != "") : $sqlStatement .= " ORDER BY " . $orderByClause . " "; endif;	
   return $sqlStatement;
}

// Delivers row-data from a specified table
function getDBFields($table) {
  switch($table) {
     case "address" : 
          return "ad.ad_street,ad.ad_zipcode,ad.ad_city,ad.ad_country,ad.ad_modify"; break;
     case "address_invoice" : 
          return "ad_inv.ad_id AS ad_id_inv,ad_inv.ad_street AS ad_street_inv,ad_inv.ad_zipcode AS ad_zipcode_inv,ad_inv.ad_city AS ad_city_inv,ad_inv.ad_country AS ad_country_inv,ad_inv.ad_modify AS ad_modify_inv"; break;
     case "address_pickup" : 
          return "ad_pck.ad_id AS ad_id_pck,ad_pck.ad_street AS ad_street_pck,ad_pck.ad_zipcode AS ad_zipcode_pck,ad_pck.ad_city AS ad_city_pck,ad_pck.ad_country AS ad_country_pck,ad_pck.ad_modify AS ad_modify_pck"; break;
     case "address_service" : 
          return "ad_srv.ad_id AS ad_id_srv,ad_srv.ad_street AS ad_street_srv,ad_srv.ad_zipcode AS ad_zipcode_srv,ad_srv.ad_city AS ad_city_srv,ad_srv.ad_country AS ad_country_srv,ad_srv.ad_modify AS ad_modify_srv"; break;
     case "ad_street_hsno" : 
          return "CONCAT(ad.ad_street,' ',tr.tr_hsno) AS streethsno"; break;
     case "ad_zipcode_city" : 
          return "CONCAT(ad.ad_zipcode,' ',ad.ad_city) AS zipcodecity"; break;
     case "ad_street_hsno_2" : 
          return "CONCAT(ad2.ad_street,' ',tr2.tr_hsno) AS streethsno2"; break;
     case "ad_zipcode_city_2" : 
          return "CONCAT(ad2.ad_zipcode,' ',ad2.ad_city) AS zipcodecity2"; break;
     case "costcenter" : 
          return "csc.csc_id,csc.cs_id,csc.csc_name,csc.csc_pre_id,csc.csc_path,csc.csc_is_extern,csc.csc_blocked,csc.csc_visible,csc.csc_inv_interval,csc.csc_inv_type,csc.csc_modify"; break;
     case "costcenteraddress" : 
          return "cscad.csc_id,cscad.cscad_comp,cscad.cscad_comp2,cscad.ad_id,cscad.adt_id,cscad.cscad_hsno,cscad.cscad_remark,cscad.cscad_person,cscad.cscad_phone,cscad.cscad_modify"; break;
     case "costcenteraddress_invoice" : 
          return "cscad_inv.csc_id AS csc_id_inv,cscad_inv.cscad_comp AS cscad_comp_inv,cscad_inv.cscad_comp2 AS cscad_comp2_inv,cscad_inv.cscad_comp3 AS cscad_comp3_inv,cscad_inv.cscad_comp4 AS cscad_comp4_inv,"
               . "cscad_inv.adt_id AS adt_id_inv,cscad_inv.cscad_hsno AS cscad_hsno_inv,cscad_inv.cscad_floor AS cscad_floor_inv,cscad_inv.cscad_remark AS cscad_remark_inv,cscad_inv.cscad_person AS cscad_person_inv,cscad_inv.cscad_phone AS cscad_phone_inv,"
               . "cscad_inv.cscad_email AS cscad_email_inv,cscad_inv.cscad_gln AS cscad_gln_inv,cscad_inv.cscad_modify AS cscad_modify_inv"; break;
     case "costcenteraddress_pickup" : 
          return "cscad_pck.csc_id AS csc_id_pck,cscad_pck.cscad_comp AS cscad_comp_pck,cscad_pck.cscad_comp2 AS cscad_comp2_pck,cscad_pck.cscad_comp3 AS cscad_comp3_pck,cscad_pck.cscad_comp4 AS cscad_comp4_pck,"
               . "cscad_pck.adt_id AS adt_id_pck,cscad_pck.cscad_hsno AS cscad_hsno_pck,cscad_pck.cscad_floor AS cscad_floor_pck,cscad_pck.cscad_remark AS cscad_remark_pck,cscad_pck.cscad_person AS cscad_person_pck,cscad_pck.cscad_phone AS cscad_phone_pck,"
               . "cscad_pck.cscad_email AS cscad_email_pck,cscad_pck.cscad_gln AS cscad_gln_pck,cscad_pck.cscad_modify AS cscad_modify_pck"; break;
     case "costcenteraddress_service" : 
          return "cscad_srv.csc_id AS csc_id_srv,cscad_srv.cscad_comp AS cscad_comp_srv,cscad_srv.cscad_comp2 AS cscad_comp2_srv,cscad_srv.cscad_comp3 AS cscad_comp3_srv,cscad_srv.cscad_comp4 AS cscad_comp4_srv,"
               . "cscad_srv.adt_id AS adt_id_srv,cscad_srv.cscad_hsno AS cscad_hsno_srv,cscad_srv.cscad_floor AS cscad_floor_srv,cscad_srv.cscad_remark AS cscad_remark_srv,cscad_srv.cscad_person AS cscad_person_srv,cscad_srv.cscad_phone AS cscad_phone_srv,"
               . "cscad_srv.cscad_email AS cscad_email_srv,cscad_srv.cscad_gln AS cscad_gln_srv,cscad_srv.cscad_modify AS cscad_modify_srv"; break;
     case "metatype" : 
          return "mt.mt_id,mt.mt_type,mt.mt_sort,mt.mt_value,mt.mt_modify"; break;
     case "vehicletype" : 
          return "vht.mt_sort AS vht_sort,vht.mt_value AS vht_value"; break;
     case "vehicletype_real" : 
          return "vht_real.mt_value AS vht_value_real"; break;
     case "jobstatus" : 
          return "jbs.mt_sort AS jbs_sort,jbs.mt_value AS jbs_value"; break;
     case "job" : 
          return "jb.jb_id,jb.csc_id,jb.hq_id_exec,jb.hq_id_dispo,jb.hq_id_sales,jb.vht_id,jb.vht_id_real,jb.csc_id_payer,jb.jb_payment,jb.jb_outlay,jb.jb_weight,jb.jb_ordertime,jb.jb_reserv,jb.jb_permanent,jb.jb_permanent2,jb.jp_permenddat,jb.jb_specials,jb.cr_id,jb.cr_sid,jb.cr_id_order,jb.cr_id_permanent,jb.jb_cr_filter,jb.jb_cr_filter_opt,jb.jb_waitstorno,jb.jb_waittime,jb.jb_taketime,jb.jb_tourname,jb.jb_status,jb.jb_type,jb.jb_incomplete,jb.jb_storno,jb.jb_finishtime,jb.jb_warningtime,jb.jb_createtime,jb.emp_id,jb.jb_fixprice,jb.jb_serviceprice,jb.jb_totalprice,jb.jb_cr_price,jb.jb_hq_id_exec_price,jb.jb_cr_subprice,jb.jb_id_parent,jb.jb_booktime,jb.jb_export_time,jb.jb_postage,jb.jb_modify,jb.jb_longhaul,jb.jb_longhaul_export,jb.jb_dispoinfo,jb.jb_offer,jb.jb_subtotalprice,jb.jb_markup,jb.csc_id_related,jb.jb_timeunits,jb.jb_service,jb.jb_orderer"; break;
     case "jb_edit" :
          return "jb.jb_id AS jb_edit"; break;
     case "jb_tourzipcodes" :
          return "jb.jb_tourdata AS jb_tourzipcodes"; break;
     case "jb_tourcities" :
          return "jb.jb_tourdata AS jb_tourcities"; break;
     case "tour" : 
          return "tr.tr_id,tr.ad_id,tr.tr_sort,tr.tr_comp,tr.tr_comp2,tr.tr_hsno,tr.tr_remark,tr.tr_person,tr.tr_phone,tr.csc_id,tr.tr_km_extra,tr.tr_srv_extra,tr.tr_status,tr.tr_sign,tr.tr_signname,tr.tr_ware_from_to,tr.tr_finishtime,tr.tr_commission_no"; break;
     case "tourservice" :
          return "trs.csc_id,trs.tr_sort,trs.srv_id,trs.trs_srv_name,trs.srvt_id,trs.trs_srvt_name,trs.trs_price,trs.trs_discount"; break;
     case "tourarticle" : 
          return "trat.trat_id,trat.tr_sort,trat.trat_sort,trat.at_id,trat.trat_quantity,trat.trat_price,trat.trat_packingpieces,trat.trat_serialno,trat.trat_state,trat.trat_remark,trat.trat_createtime,trat.trat_modify"; break;
     case "tourarticleprocess" : 
          return "tratp.trat_id,tratp.tratp_type,tratp.tratp_state,tratp.tratp_remark,tratp.tratp_createtime"; break;
     case "article" :
          return "at.at_id,at.at_eid,at.at_name,at.at_match,at.at_description,at.at_barcode,at.at_bundlequantity,at.at_bundlecode,at.at_stk_itemquantity,at.at_stk_areaquantity,at.at_serialno,at.at_totalweight,at.at_packingpieces,at.at_timeunits"; break;
     case "employee" : 
          return "emp_id,usr_id,csc_id"; break;
     case "jobemployee" :
          return "jbemp.jb_id,jbemp.usr_id,jbemp.jbemp_modifytime,jbemp.jbemp_description"; break;
     case "user" : 
          return "usr.usr_id,usr.usr_type,usr.usr_name,usr.usr_firstname,usr.usr_email,usr.usr_phone,usr.usr_phone2,usr.usr_fax,usr.usr_account,usr.usr_password"; break;
     case "jb_latesttaketime" :
          return "jb.jb_ordertime AS jb_latesttaketime"; break;
     case "jb_traveltime" :
          // return "CASE WHEN NOW() > DATE_SUB(jb.jb_ordertime, INTERVAL GREATEST(srvpt.srvpt_traveltime, 30) MINUTE) THEN (- TIMESTAMPDIFF(MINUTE, DATE_SUB(jb.jb_ordertime, INTERVAL GREATEST(srvpt.srvpt_traveltime, 30) MINUTE),NOW())) ELSE TIMESTAMPDIFF(MINUTE, NOW(), DATE_SUB(jb.jb_ordertime, INTERVAL GREATEST(srvpt.srvpt_traveltime, 30) MINUTE)) END AS jb_traveltime"; break;
          return "CASE WHEN (jb.jb_status IN ('0','1','8','9')) AND (jb.jb_reserv = '1') THEN TIMESTAMPDIFF(MINUTE, jb.jb_ordertime, NOW()) WHEN (jb.jb_status IN ('0','1','8','9')) AND (jb.jb_reserv != '1') AND (DATE_ADD(jb.jb_ordertime, INTERVAL GREATEST(srvpt.srvpt_traveltime, 30) MINUTE) < NOW()) THEN TIMESTAMPDIFF(MINUTE, NOW(), DATE_ADD(jb.jb_ordertime, INTERVAL GREATEST(srvpt.srvpt_traveltime, 30) MINUTE)) WHEN (jb.jb_status IN ('0','1','8','9')) AND (jb.jb_reserv != '1') AND (jb.jb_ordertime < NOW()) THEN TIMESTAMPDIFF(MINUTE, NOW(), DATE_ADD(jb.jb_ordertime, INTERVAL GREATEST(srvpt.srvpt_traveltime, 30) MINUTE)) ELSE '0' END AS jb_traveltime"; break;
     case "courier" :
          return "cr.cr_id,cr.cmp_id,cr.usr_id,cr.cr_sid,cr.cr_eid,cr.vht_id,cr.cr_filter,cr.cr_maxweight,cr.cr_outlay,cr.cr_available,cr.cr_availabletime,cr.cr_locationzipcode,cr.cr_mobile_pda"; break;
     case "company" :
          return "cmp.cmp_id,cmp.cmp_type,cmp.cmp_comp,cmp.cmp_comp2,cmp.cmp_comp3,cmp.cmp_comp4,cmp.ad_id,cmp.cmp_hsno,cmp.cmp_iln,cmp.cmp_tax_idno,cmp.cmp_stax_idno,cmp.tx_id,cmp.br_id,"
               . "cmp.emp_id_sales,cmp.cmp_fingerprint,cmp.cmp_sales_ranking_man,cmp.cmp_bank,cmp.cmp_bankno,cmp.cmp_bankacc,cmp.cmp_bankmode,cmp.cmp_iban,cmp.cmp_swift,cmp.cmp_postage,"
               . "cmp.cmp_hqlino,cmp.cmp_gln,cmp.cmp_inv2hq,cmp.cmp_authenticated,cmp.cmp_visible,cmp.cmp_visible_internal,cmp.cmp_archived,cmp.cmp_no_longhaul,cmp.cmp_cashmode,cmp.cmp_keyuser,"
               . "cmp.cmp_publickey,cmp.cmp_defaultkey,cmp.cmp_modify,cmp.cmp_logo,cmp.cmp_logo_width,cmp.cmp_logo_height,cmp.cmp_remark,cmp.cmp_remark2,cmp.cmp_match,cmp.cmp_match2,"
               . "cmp.cmp_sustainability_email,cmp.cmp_sustainability_interval,cmp.cmp_new_date,cmp.cmp_contract_date,cmp.cmp_dpf_state,cmp.cmp_dpf_datetime,cmp.cmp_dpf_checksum,cmp.cmp_dsgvo,"
               . "cmp.cmp_newsletter,cmp.cmp_proof_delivery,cmp.cmp_pda_usage,cmp.cmp_freetext1,cmp.cmp_modify_status,cmp.cmp_export_time"; break;
     case "couriervehicle" :
          return "crvh.crvh_id,crvh.vht_id,crvh.cr_id,crvh.crvh_id_inv,crvh.crvh_sort,crvh.crvh_sid,crvh.crvh_comm_no,crvh.crvh_vh_sign,crvh.crvh_vh_name,crvh.crvh_licence_date,crvh.crvh_owner,crvh.crvh_env_badge_level,crvh.crvh_prov,crvh.crvh_payload,crvh.crvh_totalweight,crvh.crvh_length,crvh.crvh_width,crvh.crvh_height,crvh.crvh_position,crvh.crvh_aperture_height_side,crvh.crvh_aperture_height_rear,crvh.crvh_mobile,crvh.crvh_insurance_name,crvh.crvh_insurance_no,crvh.crvh_remark,crvh.crvh_filter,crvh.crvh_service,crvh.crvh_group,crvh.crvh_special,crvh.crvh_vhd_disabled,crvh.crvh_corporate_identity,crvh.crvh_funding_state,crvh.crvh_funding_final_installment,crvh.crvh_funding_residual_value,crvh.crvh_pda_usage,crvh.crvh_system_fee,crvh.crvh_freetext_1,crvh.crvh_modify_status,crvh.crvh_modify,crvh.crvh_export_time"; break;
     case "courierfilter" :
          return "crf.crf_id,crf.crf_type,crf.crf_short,crf.crf_text,crf.crf_status,crf.vht_id,crf.crf_sort,crf.crf_longtext"; break;
     case "genericdatacontainer" :
          return "gdc.gdc_gen_fieldname,gdc.gdc_content,gdc.gdc_context"; break;
     case "log" :
          return "log.logo_id,log.log_createtime,log.hq_id,log.jb_id,log.usr_id,log.cr_id,log.cr_sid,log.cs_id,log.logo_description"; break;
     case "logoperation" :
          return "logo.logo_id,logo.logo_op_category,logo.logo_op_name,logo.logo_op_shortname"; break;
     case "customer" :
          return "cs.cs_id,cs.cmp_id,cs.hq_id,cs.cs_eid,cs.cs_sid,cs.csc_id,cs.csc_id_payer,cs.cs_admin,cs.cs_id_parent,cs.cs_id_related,cs.cs_discount,cs.cs_fixprice_discount,cs.cs_prov,cs.cs_invmode,cs.cs_commission_no,"
               . "cs.cs_cr_fav_only,cs.cs_cr_fav_only,cs.cs_jbstatusmail2csc,cs.cs_jbstatusmail_price,cs.cs_jbstatusmail_emp,cs.cs_jbstatusmail_pdf,cs.cs_jbstatusmail_fields,cs.cs_jbstatusmail,cs.cs_jbstatusmail2,cs.cs_jbstatusmail3,"
               . "cs.cs_jb_jam_waittime,cs_jb_jam_waittime_minutes,cs.cs_jb_jam_waittime_minutes,cs.cs_jbedit,cs.cs_jbedit_cr,cs.cs_ar,cs.cs_jbcond,cs.cs_jobbatch,cs.cs_invtext_mode,cs.cs_filter,cs.cs_filter_jbedit,"
               . "cs.cs_markup,cs.cs_markup_prov,cs.cs_group,cs.cs_price_warn_uncomplete,cs.cs_joblist_disabled,cs.cs_become_cs_date,cs.cs_repayment,cs.cs_tracking,cs.cs_charging_time,cs.cs_blur_markup_time,cs.cs_payment_term,cs.cs_modify"; break;
     case "asset" :
          return "ast.as_obj_type,ast.as_obj_id,ast.as_key,ast.as_value,ast.as_context,ast.as_location,ast.as_weekdays,ast.as_modify"; break;
     case "assetrelation" :
          return "asr.as_id,asr.as_id_ref,asr.asr_type,asr.asr_context,asr.asr_modify"; break;
     case "assetdisposition" :
          return "asd.asd_id,asd.as_id,asd.asd_time_from,asd.asd_time_to,asd.asd_location,asd.jb_id"; break;
     default : return "";
  };
}

// Gets DB fields with each type
function getFieldsAndTypes($table) {
	$retArr = array();
  switch($table) {
     case "address" : 
          $retArr = array("ad_street","varchar","ad_zipcode","varchar","ad_city","varchar","ad_country","varchar","ad_modify","datetime"); break;
     case "user" : 
          $retArr = array("usr_name","varchar","usr_firstname","varchar","usr_birthdate","date","usr_email","email","usr_inv_email","email",
                          "usr_phone","phone","usr_phone2","phone","usr_fax","phone","usr_account","db.account","usr_password","db.password"); break;
     case "company" :
          $retArr = array("cmp_type","integer","cmp_comp","varchar","cmp_comp2","varchar","cmp_comp3","varchar","cmp_comp4","varchar",
                          "cmp_hsno","varchar","cmp_iln","varchar","cmp_tax_idno","varchar","cmp_stax_idno","varchar",
                          "cmp_bank","varchar","cmp_bankno","varchar","cmp_bankacc","varchar","cmp_iban","varchar","cmp_swift","varchar",
                          "cmp_logo","varchar","cmp_logo_width","varchar","cmp_logo_height","varchar","cmp_remark","varchar","cmp_remark2","varchar",
                          "cmp_match","varchar","cmp_match2","varchar","cmp_newsletter","integer","cmp_pda_usage","integer"); break;
     case "customer" :
          $retArr = array("cs_eid","varchar","cs_sid","varchar","hq_id","integer","cs_invmode","integer","cs_cr_fav_only","integer",
                          "cs_jbstatusmail","integer","cs_jbstatusmail2","integer","cs_jbstatusmail3","integer","cs_jbstatusmail_pdf","integer",
                          "cs_filter","varchar","cs_group","varchar","cs_tracking","integer"); break;
     case "costcenteraddress" :
          $retArr = array("cscad_comp","varchar","cscad_comp2","varchar","cscad_comp3","varchar","cscad_comp4","varchar","cscad_person","varchar",
                          "cscad_phone","varchar","cscad_email","email","cscad_remark","varchar"); break; 
     case "courier" :
          $retArr = array("cr_eid","varchar","cr_sid","varchar","cr_id_parent","integer","hq_id","integer","vht_id","integer","vht_id_inv","integer",
                          "cr_filter","varchar","cr_vh_sign","varchar","cr_imei","varchar","cr_mobile_pda","varchar","cr_maxweight","integer",
                          "cr_outlay","integer","cr_locationzipcode","varchar","cr_available","integer","cr_availabletime","datetime",
                          "cr_occupied","integer","cr_logintime","datetime"); break; 
     case "couriervehicle" :
          $retArr = array("vht_id","integer","crvh_sort","integer","crvh_sid","varchar","crvh_comm_no","varchar","crvh_vh_sign","varchar",
                          "crvh_vh_name","varchar","crvh_licence_date","date","crvh_env_badge_level","integer","crvh_prov","numeric",
                          "crvh_payload","integer","crvh_totalweight","integer","crvh_length","integer","crvh_width","integer",
                          "crvh_height","integer","crvh_position","integer","crvh_aperture_height_side","integer","crvh_aperture_height_rear","integer",
                          "crvh_insurance_name","varchar","crvh_insurance_no","varchar","crvh_remark","varchar","crvh_filter","varchar",
                          "crvh_service","varchar","crvh_group","varchar","crvh_special","integer","crvh_corporate_identity","integer",
                          "crvh_funding_state","integer","crvh_funding_final_installment","date","crvh_funding_residual_value","numeric",
                          "crvh_pda_usage","integer","crvh_system_fee","integer","crvh_freetext_1","varchar"); break;
     case "geocode" :
          $retArr = array("gc_id","integer","gc_obj_type","varchar","gc_obj_id","integer","gc_lat","numeric","gc_long","numeric"); break;
     default : $retArr = array();
  };
  return $retArr;
}

// Sets the align-value for HTML-output
function setAlign($shortValue) {
  switch($shortValue) {
     case "c" : return "center"; break;
     case "l" : return "left"; break;
     case "r" : return "right"; break;
     case "t" : return "top"; break;
     case "b" : return "bottom"; break;
     default : return "center";
  };
}

// Gets an array with time components or formatted string
function getTimeSpan ($sec, $mode = "0", $timeWindowOffsetSec = 0) {
	 if ($timeWindowOffsetSec != "" && is_numeric($timeWindowOffsetSec)) :
	    $sec = $sec + $timeWindowOffsetSec;
	 endif;
	 $td = array();
   $td['total'] = $sec;    
   $td['sec'] = $sec % 60;
   $td['min'] = (($sec - $td['sec']) / 60) % 60;
   $td['std'] = (((($sec - $td['sec']) /60) - $td['min']) / 60) % 24;    
   $td['day'] = floor( ((((($sec - $td['sec']) /60) - $td['min']) / 60) / 24) );
   if ($mode == "1") :
      return ($td['day'] > 0 ? $td['day'] . " d " : "") . ($td['std'] > 0 ? $td['std'] . " h " : "") . ($td['min'] > 0 ? $td['min'] . " min " : "") . ($td['sec'] > 0 ? $td['sec'] . " sec " : "");
   elseif ($mode == "2") :
      return ($td['day'] > 0 ? $td['day'] . " d " : "") . ($td['std'] > 0 ? $td['std'] . " h " : "") . ($td['min'] > 0 ? $td['min'] . " min " : "");
   elseif ($mode == "11") :
      return ($td['day'] > 0 ? $td['day'] . "&nbsp;d&nbsp;" : "") . ($td['std'] > 0 ? $td['std'] . "&nbsp;h&nbsp;" : "") . ($td['min'] > 0 ? $td['min'] . "&nbsp;min&nbsp;" : "") . ($td['sec'] > 0 ? $td['sec'] . "&nbsp;sec&nbsp;" : "");
   elseif ($mode == "12") :
      return ($td['day'] > 0 ? $td['day'] . "&nbsp;d&nbsp;" : "") . ($td['std'] > 0 ? $td['std'] . "&nbsp;h&nbsp;" : "") . ($td['min'] > 0 ? $td['min'] . "&nbsp;min&nbsp;" : "");
   else :
      return $td;
   endif;
}

// Transforms the input value to a special output format
function formatOutput($value,$type = "varchar",$format = "1",$decimals = "") {
	 global $hq_id;
   $retVal = trim($value);

   // DB wrapper for "timestamp" to "datetime"
   $parDbFieldWrapper = getParameterValue("0", "DB_FIELDTYPE_WRAPPER_1", $hq_id);
   if ($parDbFieldWrapper == "") : $parDbFieldWrapper = getParameterValue("0", "DB_FIELDTYPE_WRAPPER_1", "0"); endif;
   if ($parDbFieldWrapper == "1") :
      if ($type == "timestamp") :
         $type = "datetime";
         $format = "3";
      endif;
   endif;

   if ($value != "") :      
      if ($type == "datetime") :
         if ($format == 1) :
            // if today : "hour.minutes" else : "hour.minutes (day.month)"
            if (date("dmY") == substr($value,8,2).substr($value,5,2).substr($value,0,4)) :
               $retVal = substr($value,11,2).":".substr($value,14,2);
            else :
               $retVal = substr($value,11,2).":".substr($value,14,2)." (".substr($value,8,2).".".substr($value,5,2).".";
               $currentYear = getDateTime("year");
               if (substr($value,0,4) != $currentYear) :
                  $retVal .= substr($value,2,2);
               endif;
               $retVal .= ")";
            endif;
         endif;
         if ($format == 2) :
            // transformed in: hour.minutes,seconds (h.i.s)
            $retVal = substr($value,11,2).".".substr($value,14,2).".".substr($value,17,2);
         endif;
         if ($format == 3) :
            // transformed in: day.month.year : hour.minutes.seconds (y.m.d : h.i.s)
            $retVal = substr($value,8,2).".".substr($value,5,2).".".substr($value,2,2)." : ".substr($value,11,2).".".substr($value,14,2).".".substr($value,17,2);
         endif;
         if ($format == 4) :
            // transformed in: d.m.Y
            $retVal = substr($value,8,2).".".substr($value,5,2).".".substr($value,0,4);
         endif;
         if ($format == 5) :
            // transformed in: d.m.y
            $retVal = substr($value,8,2).".".substr($value,5,2).".".substr($value,2,2);
         endif;
         if ($format == 6) :
            // transformed in: y.m.d
            $retVal = substr($value,2,2).".".substr($value,5,2).".".substr($value,8,2);
         endif;
         if ($format == 7) :
            // transformed in: ymd
            $retVal = substr($value,2,2).substr($value,5,2).substr($value,8,2);
         endif;         
         if ($format == 8) :
            // transformed in: Y.m.d
            $retVal = substr($value,0,4).".".substr($value,5,2).".".substr($value,8,2);
         endif;
         if ($format == 9) :
            // transformed in: Ymd
            $retVal = substr($value,0,4).substr($value,5,2).substr($value,8,2);
         endif;
         if ($format == 10) :
            // transformed in: hour.minutes,seconds (h:i)
            $retVal = substr($value,11,2).":".substr($value,14,2);
         endif;         
         if ($format == 11) :
            // transformed in: m/y
            $retVal = substr($value,5,2)."/".substr($value,2,2);
         endif;
         if ($format == 12) :
            // transformed in: Ymdhis (<=> timestamp)
            $retVal = substr($value,0,4).substr($value,5,2).substr($value,8,2).substr($value,11,2).substr($value,14,2).substr($value,17,2);
         endif;
         if ($format == 13) :
            // transformed in:  H:i (d.m)"
            $retVal = substr($value,11,2).":".substr($value,14,2)." (".substr($value,8,2).".".substr($value,5,2).".";
            $currentYear = getDateTime("year");
            if (substr($value,0,4) != $currentYear) :
               $retVal .= substr($value,2,2).".";
            endif;
            $retVal .= ")";
         endif;
         if ($format == 14) :
            $retVal = substr($value,11,2).":".substr($value,14,2)." (".substr($value,8,2).".".substr($value,5,2).".".substr($value,0,4).")";
         endif;
      endif;
      if ($type == "timestamp_classic") : 
         if ($format == 1) :      
            // transformed in: day.month.year : hour.minutes.seconds
            $retVal = substr($value,6,2).".".substr($value,4,2).".".substr($value,2,2)." : ".substr($value,8,2).".".substr($value,10,2).".".substr($value,12,2);
         endif;
         if ($format == 2) :
            // transformed in:  H:i (d.m)"
            $retVal = substr($value,8,2).":".substr($value,10,2)." (".substr($value,6,2).".".substr($value,4,2).".";
            $currentYear = getDateTime("year");
            if (substr($value,0,4) != $currentYear) :
               $retVal .= substr($value,2,2).".";
            endif;
            $retVal .= ")";
         endif;
      endif;
      if ($type == "timestamp") : 
         if ($format == 1) :      
            // transformed in: day.month.year : hour.minutes.seconds
            $retVal = substr($value,6,2).".".substr($value,4,2).".".substr($value,2,2)." : ".substr($value,8,2).".".substr($value,10,2).".".substr($value,12,2);
         endif;
      endif;
      if ($type == "text") : 
         if ($format == 1) :      
            // like a varchar
            $retVal = trim($retVal);
         endif;
      endif;
      if ($type == "bool") :
         $retVal = "";
         if ($format == 1 && $value != "" && $value != "0") :
            $retVal = "<img src=\"../images/circle.png\" height=\"8\" width=\"8\">";
         endif;
      endif;
      if ($type == "bool2") :
         $retVal = "";
         if ($format == 1 && $value != "" && $value != "0") :
            $retVal = "<img src=\"../images/circle_green.png\" height=\"8\" width=\"8\">";
         endif;
      endif;
      if ($type == "bool3") :
         $retVal = "";
         if ($format == 1 && $value != "" && $value != "0") :
            $retVal = "<img src=\"../images/circle_blue.png\" height=\"8\" width=\"8\">";
         endif;
      endif;
      if ($type == "bool4") :
         $retVal = "";
         if ($format == 1 && $value != "" && $value != "0") :
            $retVal = "<img src=\"../images/circle_yellow.png\" height=\"8\" width=\"8\">";
         endif;
      endif;
      if ($type == "bool5") :
         $retVal = "";
         if ($format == 1 && $value != "" && $value != "0") :
            $retVal = "<img src=\"../images/circle_orange.png\" height=\"8\" width=\"8\">";
         endif;
      endif;
      if ($type == "number") :
         if (is_numeric($value)) :
            $retVal = $value;
            if ($decimals != "" && is_numeric($decimals)) :
               $retVal = number_format(round($value,$decimals), $decimals, ",", ".");
            endif;
         endif;
      endif;
      if ($type == "float_rounded_2") :
         if (is_numeric($value)) :
            $retVal = number_format(round($value,2), 2, ",", ".");
         endif;
      endif;
      if ($type == "float") :
         $value = str_replace (",", ".", $value);
         $value = number_format(round($value,2), 2, ".", "");
         $dotSignPos = strrpos($value,".");
         $numberPrefix = "";
         $numberSuffix = "";
         if (!($dotSignPos === FALSE)) :
            $numberPrefix = substr($value, 0, $dotSignPos);
            $numberSuffix = substr($value, $dotSignPos + 1);
         endif;
         if ($format == 1) :      
            // transformed in: ...xxx.yy
            $retVal = $numberPrefix . "." . substr($numberSuffix, 0, 2);
         endif;
         if ($format == 2) :
            // transformed in: ...xxx,yy
            $retVal = $numberPrefix . "," . substr($numberSuffix, 0, 2);
         endif;
         if ($format == 3) :
            // transformed in: ...xxxyy
            $retVal = $numberPrefix . substr($numberSuffix, 0, 2);
         endif;
      endif;
      if ($type == "bar") :
         // Parameter "format" contains the scaling-factor
         if ($format == "" || $format == "0") : $format == "1"; endif;
         if (is_numeric($value)) :
            $numericValue = number_format(round($value / $format), 2, ",", ".");
            $retVal = "";
            for ($i = 0; $i < $numericValue; $i++) {
                $retVal .= "<span style=\"background-color:red\">&nbsp;&nbsp;&nbsp;</span><span class=\"f8np1\">&nbsp;</span>";
            }
         endif;
      endif;
   endif;
   if (trim($retVal) == "") : $retVal = "&nbsp;"; endif;
   return $retVal;
}

// Defines individual changeable types based on the database-scheme-types
function defineOutputFormats($typeConvertMode = "") {
	 $id = "id";
	 $varchar = "varchar";
	 $timestamp = "timestamp";
	 $timestamp_classic = "timestamp_classic";
	 $datetime = "datetime";
	 $int = "int";
	 $int1 = "int1";
	 $float = "float";
	 $float_rounded_2 = "float_rounded_2";
	 $bool = "bool";
	 $bool2 = "bool2";
	 $bool3 = "bool3";
	 $bool4 = "bool4";
	 $bool5 = "bool5";
	 $text = "text";
	
   if ($typeConvertMode == "1") :
	    $int = "bar"; $int1 = "bar"; $float = "bar"; $float_rounded_2 = "bar";
   endif;
	
   $out["ad_id"] = $id;
   $out["ad_street"] = $varchar;
   $out["ad_zipcode"] = $varchar;
   $out["ad_city"] = $varchar;
   $out["ad_country"] = $varchar;
   $out["ad_modify"] = $timestamp;
   $out["adt_id"] = $id;
   $out["cr_id"] = $id;
   $out["cr_id_order"] = $id;
   $out["cr_id_permanent"] = $varchar;
   $out["csc_id"] = $id;
   $out["csc_id_payer"] = $id;
   $out["csc_name"] = $varchar;
   $out["csc_path"] = $varchar;
   $out["cscad_comp"] = $varchar;
   $out["cscad_comp2"] = $varchar;
   $out["cscad_hsno"] = $varchar;
   $out["cscad_remark"] = $varchar;
   $out["cscad_person"] = $varchar;
   $out["cscad_phone"] = $varchar;
   $out["cscad_modify"] = $timestamp;
   $out["jb_id"] = $id;
   $out["hq_id_exec"] = $id;
   $out["hq_id_dispo"] = $id;
   $out["hq_id_sales"] = $id;
   $out["jb_payment"] = $int1;
   $out["jb_outlay"] = $int;
   $out["jb_weight"] = $int;
   $out["jb_ordertime"] = $datetime;   
   $out["jb_reserv"] = $bool;
   $out["jb_permanent"] = $bool2;
   $out["jb_permanent2"] = $varchar;
   $out["jp_permenddat"] = $datetime;
   $out["jb_specials"] = $varchar;
   $out["jb_cr_filter"] = $varchar;
   $out["jb_cr_filter_opt"] = $varchar;
   $out["jb_waitstorno"] = $int1;
   $out["jb_waittime"] = $datetime;
   $out["jb_taketime"] = $datetime;
   $out["jb_tourname"] = $varchar;
   $out["jb_status"] = $int1;
   $out["jb_type"] = $int1;
   $out["jb_incomplete"] = $int1;
   $out["jb_storno"] = $bool;
   $out["jb_finishtime"] = $datetime;
   $out["jb_warningtime"] = $datetime;
   $out["jb_booktime"] = $datetime;
   $out["jb_export_time"] = $datetime;
   $out["jb_postage"] = $float;
   $out["jb_modify"] = $timestamp;
   $out["jb_edit"] = $id;
   $out["jb_tourzipcodes"] = $varchar;
   $out["jb_cr_price"] = $float;
   $out["jb_hq_id_exec_price"] = $float;
   $out["jb_subtotalprice"] = $float;
   $out["jb_markup"] = $float_rounded_2;
   $out["jb_cr_subprice"] = $float;
   $out["jb_id_parent"] = $id;
   $out["jb_orderer"] = $varchar;
   $out["mt_id"] = $id;
   $out["mt_type"] = $varchar;
   $out["mt_sort"] = $int;
   $out["mt_value"] = $varchar;
   $out["mt_modify"] = $timestamp;
   $out["tr_id"] = $id;
   $out["tr_sort"] = $int;
   $out["tr_comp"] = $varchar;
   $out["tr_comp2"] = $varchar;
   $out["tr_hsno"] = $varchar;
   $out["tr_remark"] = $varchar;
   $out["tr_person"] = $varchar;
   $out["tr_phone"] = $varchar;
   $out["tr_signname"] = $varchar;
   $out["tr_km_extra"] = $int;
   $out["tr_srv_extra"] = $int;
   $out["tr_status"] = $int1;
   $out["tr_sign"] = $text;
   $out["tr_finishtime"] = $datetime;
   $out["tr_commission_no"] = $varchar;
   $out["tr_modify"] = $timestamp;
   $out["tr2_comp"] = $varchar;
   $out["vht_id"] = $id;
   $out["vht_id_real"] = $id;
   $out["cr_id"] = $id;      
   $out["cr_sid"] = $varchar;
   $out["cr_eid"] = $varchar;
   $out["cr_maxweight"] = $int;
   $out["cr_outlay"] = $int;
   $out["cr_available"] = $int1;
   $out["usr_id"] = $id;
   $out["usr_name"] = $varchar;
   $out["usr_firstname"] = $varchar;
   $out["usr_phone"] = $varchar;
   $out["usr_fax"] = $varchar;
   $out["usr_email"] = $varchar;
   $out["cmp_id"] = $id;
   $out["cmp_comp"] = $varchar;
   $out["cmp_comp2"] = $varchar;
   $out["cmp_bank"] = $varchar;
   $out["cmp_bankno"] = $varchar;
   $out["cmp_bankacc"] = $varchar;
   $out["cmp_bankmode"] = $int1;
   $out["cmp_postage"] = $float;
   $out["cmp_new_date"] = $datetime;
   $out["cmp_authenticated"] = $bool;   
   $out["crvh_licence_date"] = $datetime;
   $out["crvh_prov"] = $float;
   $out["crvh_corporate_identity"] = $int;
   $out["crvh_partner_premium"] = $float;
   $out["crvh_partner_commission"] = $float;
   $out["crvh_advertising_allowance"] = $float;
   $out["crvh_transport_insurance_amount"] = $float;
   $out["crvh_system_fee_amount"] = $float;
   $out["crvh_business_liability_insurance_amount"] = $float;
   $out["crvh_business_liability_insurance_date"] = $datetime;
   $out["jbemp_modifytime"] = $timestamp;
   $out["jbemp_description"] = $varchar;
   $out["log_createtime"] = $timestamp;
   $out["srvp_traveltime"] = $int;
   $out["cr_id_favoured"] = $bool3;
   $out["cs_prov"] = $float;
   $out["cs_discount"] = $float;   
   $out["jb_longhaul"] = $int;
   $out["jb_longhaul_export"] = $int;
   $out["stk_maxquantity"] = $int;
   $out["stkat_maxquantity"] = $int;
   $out["stkat_quantity"] = $int;
   $out["tratp_createtime"] = $datetime;
   $out["jbc_price"] = $float;
   $out["jbc_totalprice"] = $float;

   // Modified or composed types
   $out["streethsno"] = $varchar;
   $out["zipcodecity"] = $varchar;
   $out["streethsno2"] = $varchar;
   $out["zipcodecity2"] = $varchar;
   $out["jb_latesttaketime"] = $datetime;
   $out["jb_traveltime"] = $int;
   $out["price"] = $float;
   $out["gross_price"] = $float;
   $out["special_price_01"] = $float;
   $out["special_price_02"] = $float;
   $out["count_jobs"] = $int;	// E.g. statistic
   $out["business_volume"] = $float_rounded_2;
   $out["business_volume_gross"] = $float_rounded_2;
   $out["jb_cr_price_gross"] = $float_rounded_2;
   $out["markup_volume"] = $float_rounded_2;
   $out["jb_csc_id"] = $bool4;
   $out["jb_bsg"] = $float;
   $out["jb_emp_hq_id"] = $bool5;
   $out["jb_toll"] = $float;
   $out["business_volume_with_toll"] = $float_rounded_2;
   $out["jb_cr_price_with_toll"] = $float_rounded_2;
   $out["jb_cr_subprice_with_toll"] = $float_rounded_2;
   $out["business_volume_gross_with_toll"] = $float_rounded_2;
   $out["jb_cr_price_gross_with_toll"] = $float_rounded_2;
   $out["jb_crvh_partner_commission"] = $float_rounded_2;
   $out["jb_crvh_system_fee_amount"] = $float_rounded_2;
   $out["gdc_arr_tour_content"] = $timestamp_classic;
   $out["gdc_fin_work_content"] = $timestamp_classic;
   $out["jb_serviceprice"] = $float_rounded_2;
   $out["tr1_ordertime"] = $datetime;
   $out["tr1_arrivaltime"] = $datetime;
   $out["tr1_finishtime"] = $datetime;
   $out["tr2_ordertime"] = $datetime;
   $out["tr2_arrivaltime"] = $datetime;
   $out["tr2_finishtime"] = $datetime;

   // Statistic values
   $out["turnover"] = $float_rounded_2;
   $out["remuneration"] = $float_rounded_2;
   $out["eau"] = $float_rounded_2;
   $out["bsg"] = $float_rounded_2;
   $out["service_price"] = $float_rounded_2;
   $out["service_remuneration_man"] = $float_rounded_2;
   $out["km"] = $float_rounded_2;
   $out["co2e"] = $float_rounded_2;
   $out["km_zone"] = $float_rounded_2;
   $out["turnover_markup"] = $float_rounded_2;
   $out["remuneration_markup"] = $float_rounded_2;
   $out["eau_markup"] = $float_rounded_2;
   $out["bsg_markup"] = $float_rounded_2;

   // For statistic interval comparison
   $tmpCurrYear = getDateTime("year");
   for ($k = ($tmpCurrYear - 10); $k < $tmpCurrYear; $k++) :
       $out[$k] = $int;
       $out["Z".$k] = $float_rounded_2;
   endfor;

   return $out;
}

// Checks a value by (db) type 
function checkValueByType ($value, $type, $sqlPhraseArr = array()) {
  global $db, $PHP_SELF;

	$isOk = true;
	if ($value != "" && $type != "") :

     if ($type == "email" || $type == "mail") :
        $isOk = checkEmailFormat($value);

     elseif ($type == "int" || $type == "integer") :
        if (!is_numeric($value) || !ctype_digit($value)) :
           $isOk = false;
        endif;

     elseif ($type == "float") :
        if (is_numeric($value)) :
           $isOk = is_float($value);
        endif;

     elseif ($type == "numeric" || $type == "number") :
        $isOk = is_numeric($value);

     elseif ($type == "date" || $type == "birthdate" || $type == "triggerdate") :
        $day = substr($value,8,2); $month = substr($value,5,2); $year = substr($value,0,4);
        $delim1 = substr($value,4,1); $delim2 = substr($value,7,1);
        if (!(is_numeric($day) && is_numeric($month) && is_numeric($year) && checkdate($month, $day, $year) && $delim1 == "-" && $delim2 == "-")) :
           $isOk = false;   
        endif;

     elseif ($type == "datetime" || $type == "time" || $type == "triggerdatetime") :
        // 2018-03-02 10:20:30
        $year = substr($value,0,4); $month = substr($value,5,2); $day = substr($value,8,2);
        $hour = substr($value,11,2); $minutes = substr($value,14,2); $seconds = substr($value,17,2);
        $delim1 = substr($value,4,1); $delim2 = substr($value,7,1); $delim3 = substr($value,13,1); $delim4 = substr($value,16,1);
        if (!(is_numeric($day) && is_numeric($month) && is_numeric($year) && checkdate($month, $day, $year) && $delim1 == "-" && $delim2 == "-" && 
              is_numeric($hour) && is_numeric($minutes) && is_numeric($seconds) && $delim3 == ":" && $delim4 == ":")) :
           $isOk = false;
        endif;

     elseif ($type == "db.account") :
        if (count($sqlPhraseArr) > 0) :
           $usrId = $sqlPhraseArr["db.account.1"];
           if ($db->getOne("SELECT usr.usr_id FROM user AS usr WHERE usr.usr_account = '" . $value . "' AND usr.usr_id != '" . $usrId . "'")) :
              $isOk = false;
           endif;
        endif;

     elseif ($type == "db.password") :
        if ($value == "" || !checkPasswordValidation($value, $value)):
           $isOk = false;
        endif;

     endif;
  endif;
	return $isOk;
}

// Checks values to be imported for type consistence and sets update values
function checkTypesForDbImportFieldValues(&$dataArray, &$dbFieldArray, &$checkFieldArray, $sqlPhraseArr = array()) {
  global $db, $PHP_SELF;

  $isOk = true;
  $errKey = "";
  $dataArrayLen = count($dataArray);
  $checkFieldArrayLen = count($checkFieldArray);
  if ($dataArrayLen > 0 && $checkFieldArrayLen > 0) :
     for ($i = 0; $i < $checkFieldArrayLen; $i += 2) :
       $key   = $checkFieldArray[$i];
       $type  = $checkFieldArray[$i + 1];
       $value = $dataArray[$key];

       if ($value != "") :
          if ($value == "--DEL--") :
             array_push($dbFieldArray, $key, "");
          else :
             $isOk = checkValueByType($value, $type, $sqlPhraseArr);
             if ($isOk) :
                if ($type == "db.password") :
                   $value = cryptDbPassword($value);  // Encrypt user password
                endif;
                array_push($dbFieldArray, $key, $value);
             else :
                $errKey = $key;
                break;               
             endif;
          endif;
       endif;
     endfor;
  endif;

  return $errKey;
}

// Gets the ID structure of a single customer
function getDbIdTree ($objType, $objId, $retMode = "", $tagRoot = "", $lf = "") {
	$retArr = array();	
	if ($objType != "" && $objId != "" && is_numeric($objId) && $objId > 0) :
	   if ($objType == "cs") :
        $objId = getFieldValueFromId("customer","cs_id",$objId,"cs_id");
        if ($objId != "") :
           $retArr["customer"]["cs_id"] = $objId;
           $retArr["customer"]["cs_eid"] = getFieldValueFromId("customer","cs_id",$objId,"cs_eid");
           $cscId = getFieldValueFromId("customer","cs_id",$objId,"csc_id");
           $retArr["customer"]["csc_id"] = $cscId;
           $empId = getFieldValueFromId("customer","cs_id",$objId,"cs_admin");
           $retArr["customer"]["cs_admin"] = $empId;
           $retArr["customer"]["hq_id"] = getFieldValueFromId("customer","cs_id",$objId,"hq_id");
           $retArr["customer"]["cs_id_parent"] = getFieldValueFromId("customer","cs_id",$objId,"cs_id_parent");
           $retArr["customer"]["cs_id_related"] = getFieldValueFromId("customer","cs_id",$objId,"cs_id_related");
           $cmpId = getFieldValueFromId("customer","cs_id",$objId,"cmp_id");
           $retArr["customer"]["cmp_id"] = $cmpId;
           $retArr["customer"]["company"]["cmp_id"] = $cmpId;
           $retArr["customer"]["company"]["ad_id"] = getFieldValueFromId("company","cmp_id",$cmpId,"ad_id");
           $retArr["customer"]["company"]["tx_id"] = getFieldValueFromId("company","cmp_id",$cmpId,"tx_id");
           $retArr["customer"]["company"]["br_id"] = getFieldValueFromId("company","cmp_id",$cmpId,"br_id");
           $usrId = getFieldValueFromId("employee","emp_id",$empId,"usr_id");
           $retArr["customer"]["user"]["usr_id"] = $usrId;
           $tmpCscIds = getColVectorFromDB2ArrayByClause("costcenter", "csc_id", "cs_id = '" . $objId . "'", "", "", "");
           $tmpCscIdsLen = count($tmpCscIds);
           if ($tmpCscIdsLen > 0) :
              for ($c = 0; $c < $tmpCscIdsLen; $c++) :
                  $retArr["customer"]["costcenter"][$c]["csc_id"] = $cscId;
                  $retArr["customer"]["costcenter"][$c]["costcenteraddress"]["adt_1"]["csc_id"] = $cscId;
                  $retArr["customer"]["costcenter"][$c]["costcenteraddress"]["adt_1"]["ad_id"] = getFieldValueFromClause("costcenteraddress","ad_id","csc_id = '" . $cscId . "' AND adt_id = '1'");
                  $retArr["customer"]["costcenter"][$c]["costcenteraddress"]["adt_2"]["csc_id"] = $cscId;
                  $retArr["customer"]["costcenter"][$c]["costcenteraddress"]["adt_2"]["ad_id"] = getFieldValueFromClause("costcenteraddress","ad_id","csc_id = '" . $cscId . "' AND adt_id = '2'");
                  $retArr["customer"]["costcenter"][$c]["costcenteraddress"]["adt_3"]["csc_id"] = $cscId;
                  $retArr["customer"]["costcenter"][$c]["costcenteraddress"]["adt_3"]["ad_id"] = getFieldValueFromClause("costcenteraddress","ad_id","csc_id = '" . $cscId . "' AND adt_id = '3'");
                  $retArr["customer"]["costcenter"][$c]["costcenteraddress"]["adt_4"]["csc_id"] = $cscId;
                  $retArr["customer"]["costcenter"][$c]["costcenteraddress"]["adt_4"]["ad_id"] = getFieldValueFromClause("costcenteraddress","ad_id","csc_id = '" . $cscId . "' AND adt_id = '4'");
              endfor;
           endif;
           $tmpCrIds = getColVectorFromDB2ArrayByClause("customercourier", "cr_id", "cs_id = '" . $objId . "'", "", "", "");
           $tmpCrIdsLen = count($tmpCrIds);
           if ($tmpCrIdsLen > 0) :
              for ($c = 0; $c < $tmpCrIdsLen; $c++) :
                  $crId = $tmpCrIds[$c];
                  $retArr["customer"]["customercourier"][$c]["cr_id"] = $crId;
                  $retArr["customer"]["customercourier"][$c]["cr_eid"] = getFieldValueFromId("courier","cr_id",$crId,"cr_eid");
              endfor;
           endif;
        endif;
	   elseif ($objType == "cr") :
        $objId = getFieldValueFromId("courier","cr_id",$objId,"cr_id");
        if ($objId != "") :
           $retArr["courier"]["cr_id"] = $objId;
           $retArr["courier"]["cr_eid"] = getFieldValueFromId("courier","cr_id",$objId,"cr_eid");
           $retArr["courier"]["hq_id"] = getFieldValueFromId("courier","cr_id",$objId,"hq_id");
           $usrId = getFieldValueFromId("courier","cr_id",$objId,"usr_id");
           $retArr["courier"]["usr_id"] = $usrId;
           $retArr["courier"]["cr_id_parent"] = getFieldValueFromId("courier","cr_id",$objId,"cr_id_parent");
           $retArr["courier"]["vht_id"] = getFieldValueFromId("courier","cr_id",$objId,"vht_id");
           $retArr["courier"]["vht_id_inv"] = getFieldValueFromId("courier","cr_id",$objId,"vht_id_inv");
           $retArr["courier"]["cr_ar_jb_id"] = getFieldValueFromId("courier","cr_id",$objId,"cr_ar_jb_id");
           $cmpId = getFieldValueFromId("courier","cr_id",$objId,"cmp_id");
           $retArr["courier"]["cmp_id"] = $cmpId;
           $retArr["courier"]["company"]["cmp_id"] = $cmpId;
           $retArr["courier"]["company"]["ad_id"] = getFieldValueFromId("company","cmp_id",$cmpId,"ad_id");
           $retArr["courier"]["company"]["tx_id"] = getFieldValueFromId("company","cmp_id",$cmpId,"tx_id");
           $retArr["courier"]["company"]["br_id"] = getFieldValueFromId("company","cmp_id",$cmpId,"br_id");
           $retArr["courier"]["user"]["usr_id"] = $usrId;
           $tmpCrvhIds = getColVectorFromDB2ArrayByClause("couriervehicle", "crvh_id", "cr_id = '" . $objId . "'", "", "", "");
           $tmpCrvhIdsLen = count($tmpCrvhIds);
           if ($tmpCrvhIdsLen > 0) :
              for ($c = 0; $c < $tmpCrvhIdsLen; $c++) :
                  $crvhId = $tmpCrvhIds[$c];
                  $retArr["courier"]["couriervehicle"][$c]["crvh_id"] = $crvhId;
                  $retArr["courier"]["couriervehicle"][$c]["vht_id"] = getFieldValueFromId("couriervehicle","crvh_id",$crvhId,"vht_id");
                  $retArr["courier"]["couriervehicle"][$c]["cr_id"] = $objId;
                  $retArr["courier"]["couriervehicle"][$c]["crvh_sid"] = getFieldValueFromId("couriervehicle","crvh_id",$crvhId,"crvh_sid");
              endfor;
           endif;
           $tmpCsIds = getColVectorFromDB2ArrayByClause("customercourier", "cs_id", "cr_id = '" . $objId . "'", "", "", "");
           $tmpCsIdsLen = count($tmpCsIds);
           if ($tmpCsIdsLen > 0) :
              for ($c = 0; $c < $tmpCsIdsLen; $c++) :
                  $csId = $tmpCsIds[$c];
                  $retArr["courier"]["customercourier"][$c]["cs_id"] = $csId;
                  $retArr["courier"]["customercourier"][$c]["cs_eid"] = getFieldValueFromId("customer","cs_id",$csId,"cs_eid");
              endfor;
           endif;
        endif;
     endif;
     if ($retMode == "1") :
        return mcArray2Xml($retArr, $tagRoot, $lf);
     endif;
  endif;
  return $retArr;
}

// Gets the access matrix regarding job status and headquarters type IDs 
// $jbHqIdArr: HQ vector of the current job  ([0] <=> hq_id, [1] <=> hq_id_dispo, [2] = hq_id_exec, [3] = hq_id_sales)
// $jbStatus: Refers to "jb_status" of the current job
function getAccessHqTypeJbStatus ($jbHqIdArr, $jbStatus, $empHasAccessToLonghaul = false, $currentSelectedList = "") {
	global $hq_id, $emp_id, $f_hq_id, $userTypeName, $empIdRootAdmin;

  // Check global access to longhaul jobs
  if ($userTypeName == "hq" && $currentSelectedList != "" && $currentSelectedList != "ALL") :
     if (!isset($empIdRootAdmin)) : $empIdRootAdmin = getEmpIdOfRootAdmin($userTypeName); endif;
     if (($empIdRootAdmin != "" && $emp_id == $empIdRootAdmin)) :
        return array(true, true, true);
     endif;
  // elseif (($empHasAccessToLonghaul && $currentSelectedList != "ALL") || (isset($userTypeName) && $userTypeName == "cs")) :
  //    return array(true, true, true);
  endif;

  // Init
  $retArr = array(false, false, false);
  $roleArr = array(false, false, false, false);

  // Accessible headquarters have to be iterated

  $fHqArr = $f_hq_id;
  if (!is_array($fHqArr)) : $fHqArr = array($hq_id); endif;  
  $fHqArrLen = count($fHqArr);    
  if ($fHqArrLen == 0) : array_push($fHqArr, $hq_id); endif;

	// Access mode: [0] <=> create job, [1] <=> dispose job, [2] = execute job, [3] = customer-providing job
	$createArr = array(false, false, false);  // ("Anzeige", "Änderung", "Vermittlung")
	$dispoArr  = array(false, false, false);  // ("Anzeige", "Änderung", "Vermittlung")
	$execArr   = array(false, false, false);  // ("Anzeige", "Änderung", "Vermittlung")
	$salesArr  = array(false, false, false);  // ("Anzeige", "Änderung", "Vermittlung")
	
	if (is_array($jbHqIdArr)) :

	   // Init conmponents if do not exist
     mcArrIsSet($jbHqIdArr, "0", "0"); mcArrIsSet($jbHqIdArr, "1", "0"); mcArrIsSet($jbHqIdArr, "2", "0"); mcArrIsSet($jbHqIdArr, "3", "0");
     $jbHqIdCreate = $jbHqIdArr["0"];
     $jbHqIdDispo  = $jbHqIdArr["1"];
     $jbHqIdExec   = $jbHqIdArr["2"];
     $jbHqIdSales  = $jbHqIdArr["3"];

     // Iterate headquarters the user has access to (hq vector in lists)
     for ($i = 0; $i < $fHqArrLen; $i++) :

         switch ($jbStatus) {
             case "8":  // "Autoranking"
               if ($jbHqIdCreate == $fHqArr[$i]) :
                  $createArr = array(true, true, false); $roleArr[0] = true;
               endif;
               if ($jbHqIdDispo == $fHqArr[$i]) :
                  $dispoArr = array(true, false, true);  $roleArr[1] = true;
                  if (!$empHasAccessToLonghaul || $currentSelectedList == "ALL") : $dispoArr = array(true, false, false); endif;
               endif;
               if ($jbHqIdExec == $fHqArr[$i]) :
                  $execArr = array(false, false, false); $roleArr[2] = true;
               endif;
               if ($jbHqIdSales == $fHqArr[$i]) :
                  $salesArr = array(true, false, false); $roleArr[3] = true;
               endif;
               break;
             case "9":  // "Zuzuweisende"
               if ($jbHqIdCreate == $fHqArr[$i]) :
                  $createArr = array(true, true, false); $roleArr[0] = true;
               endif;                                                        
               if ($jbHqIdDispo == $fHqArr[$i]) :                            
                  $dispoArr = array(true, false, true);  $roleArr[1] = true;
                  if (!$empHasAccessToLonghaul || $currentSelectedList == "ALL") : $dispoArr = array(true, false, false); endif;
               endif;                                                        
               if ($jbHqIdExec == $fHqArr[$i]) :                             
                  $execArr = array(false, false, false); $roleArr[2] = true;
               endif;                                                        
               if ($jbHqIdSales == $fHqArr[$i]) :                            
                  $salesArr = array(true, false, false); $roleArr[3] = true;
               endif;
               break;
             case "0":  // "Offene"
               if ($jbHqIdCreate == $fHqArr[$i]) :
                  $createArr = array(true, true, false); $roleArr[0] = true;
               endif;                                                        
               if ($jbHqIdDispo == $fHqArr[$i]) :                            
                  $dispoArr = array(true, false, true);  $roleArr[1] = true;
                  if (!$empHasAccessToLonghaul || $currentSelectedList == "ALL") : $dispoArr = array(true, false, false); endif;
               endif;                                                        
               if ($jbHqIdExec == $fHqArr[$i]) :                             
                  $execArr = array(true, false, false); $roleArr[2] = true;
               endif;                                                        
               if ($jbHqIdSales == $fHqArr[$i]) :                            
                  $salesArr = array(true, false, false); $roleArr[3] = true;
               endif;
               break;
             case "1":  // "Angenommene"
               if ($jbHqIdCreate == $fHqArr[$i]) :
                  $createArr = array(true, true, false); $roleArr[0] = true;
               endif;                                                        
               if ($jbHqIdDispo == $fHqArr[$i]) :                            
                  $dispoArr = array(true, false, true);  $roleArr[1] = true;
                  if (!$empHasAccessToLonghaul || $currentSelectedList == "ALL") : $dispoArr = array(true, false, false); endif;
               endif;                                                        
               if ($jbHqIdExec == $fHqArr[$i]) :                             
                  $execArr = array(true, false, false);  $roleArr[2] = true;
               endif;                                                        
               if ($jbHqIdSales == $fHqArr[$i]) :                            
                  $salesArr = array(true, false, false); $roleArr[3] = true;
               endif;
               break;
             case "2":  // "Erledigte"
               if ($jbHqIdCreate == $fHqArr[$i]) :
                  $createArr = array(true, true, false); $roleArr[0] = true;
               endif;                                                        
               if ($jbHqIdDispo == $fHqArr[$i]) :                            
                  $dispoArr = array(true, false, false); $roleArr[1] = true;
               endif;                                                        
               if ($jbHqIdExec == $fHqArr[$i]) :                             
                  $execArr = array(true, false, false);  $roleArr[2] = true;
               endif;                                                        
               if ($jbHqIdSales == $fHqArr[$i]) :                            
                  $salesArr = array(true, false, false); $roleArr[3] = true;
               endif;
               break;
         };

         // Return access for "Anzeige", "Änderung", "Vermittlung"
         $retArr = array(($retArr[0] || $createArr[0] || $dispoArr[0] || $execArr[0] || $salesArr[0]), 
                         ($retArr[1] || $createArr[1] || $dispoArr[1] || $execArr[1] || $salesArr[1]), 
                         ($retArr[2] || $createArr[2] || $dispoArr[2] || $execArr[2] || $salesArr[2]));
     endfor;     
  endif;
/*
if ($emp_id == "100001" || $emp_id == "200001" || $emp_id == "300001" || $emp_id == "867507" || $emp_id == "853915") :
   // print_r($retArr); echo "<br>";
   echo "---------------------------------------------------------------------------------------------------------<br>";
   echo "<b>ROLLEN: &nbsp;&nbsp;" . ($roleArr[0] ? "Erfassend" : "") . "&nbsp;&nbsp;" . ($roleArr[1] ? "Zuweisend" : "") . "&nbsp;&nbsp;" . ($roleArr[2] ? "Ausführend" : "") . "&nbsp;&nbsp;" . ($roleArr[3] ? "Kundenstellend" : "") . "&nbsp;&nbsp;";
   echo "</b><br>";
endif;
*/
  return $retArr;
}
?>
