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

// Gets request password
function getPwd ($salt) {
	$retPwd = "";
	if ($salt != "") :
     $currDate = getDateTime("1");  // "20180313" und "34a78d91s83g"   =>   13d910334a78180313s83g
     //            "13" (day)        .      "d91"        .     "03" (month)      .     "34a78"       . "180313" (year month day) . "s83g"
     $retPwd = substr($currDate,6,2) . substr($salt,5,3) . substr($currDate,4,2) . substr($salt,0,5) . substr($currDate,2,6) . substr($salt,8,4);
  endif;
  return $retPwd;
}

// Checks request password
function checkPwd ($passPhrase, $salt) {
	global $debug;
	$retBool = false;
	if ($passPhrase != "" && $salt != "") :
     $currDate = getDateTime("1");
     $tmpDate = "20" . substr($passPhrase,12,2) . substr($passPhrase,5,2) . substr($passPhrase,0,2);
     $tmpDate2 = "20" . substr($passPhrase,12,6);
     $tmpSalt = substr($passPhrase,7,5) . substr($passPhrase,2,3) . substr($passPhrase,18,4);
     if ($debug) :
        echo "currDate = " . $currDate . "<br>";
        echo "tmpDate = " . $tmpDate . "<br>";
        echo "tmpSalt = " . $tmpSalt . "<br>";
     endif;
     if ($tmpDate == $currDate && $tmpDate2 == $currDate && $tmpSalt == $salt) :
        $retBool = true;
     endif;
  endif;
  return $retBool;
}

// Checks authentication data being in the request
function checkRequestAuthenticationData ($usrAccount, $usrPassword, $sessionId, $objId, $objType = "cs") {
	global $db, $PHP_SELF;
	global $dbname, $dblogin, $dbpassword, $usr_id;

  $retBool = false; 
  if ($objType != "" && $usrAccount != "" && $usrPassword != "") :

     $usrType = "2";
     if ($objType == "cr") : $usrType = "3"; endif;

     // Check for existing user !!!!
     $sqlquery = "SELECT usr_id, hq_id FROM user WHERE usr_account = '$usrAccount' AND usr_password = PASSWORD('$usrPassword') AND usr_type = '" . $usrType . "'";
     $result = $db->query($sqlquery);

     $usr_id = "";
     $hq_id = "";
     if (!(DB::isError($result))):  

       while ($row = $result->fetch_assoc()):
          $usr_id = $row["usr_id"];
          $hq_id = $row["hq_id"];
       endwhile;
       $result->free();
     
       // Get the IP of the current client calling the page
       $currentClientIP = trim($_SERVER['REMOTE_ADDR']);  

       if ($usr_id != "") :
          // Check for correct association
          if ($objType == "cr") :
             // Courier
             $tmpObjId = getFieldValueFromId("courier", "usr_id", $usr_id, "cr_id");
          else :
             // Customer
             $tmpEmpId = getFieldValueFromId("employee", "usr_id", $usr_id, "emp_id");
             $tmpCscId = getFieldValueFromId("employee", "emp_id", $tmpEmpId, "csc_id");
             $tmpObjId = getFieldValueFromId("costcenter", "csc_id", $tmpCscId, "cs_id");
          endif;

          if ($tmpObjId != "" && $tmpObjId == $objId) :
             // Check for "session hash" in remote instance metaobjects
             $sessionHash = "";
             // Get current global number of THIS database instance
             $constGlobalDbInstNo = getParameterValue("0", "GLOBAL_UNIQUE_DB_INSTANCE_NO", "0", "0");
             if ($constGlobalDbInstNo != "" && is_numeric($constGlobalDbInstNo)) :

                // Get database instance connection data of metaobject
                $constExtDbInst = getExternalMetaDbInst();
                $db_conn = getDbConnectionSpecial($constExtDbInst, $dbname, $dblogin, $dbpassword);
                $tmpSqlQuery = "SELECT mo_hash FROM meta_object.metaobject WHERE mo_obj_type = 'usr' AND mo_id_ref_db = '" . $constGlobalDbInstNo . "' AND mo_obj_id = '" . $usr_id . "'";
                $result = $db_conn->query($tmpSqlQuery);
                while ($row = $result->fetch_assoc()):
                   $sessionHash = $row["mo_hash"];
                endwhile;
                $result->free();
             endif;

             $usrRealName = getFieldValueFromId("user", "usr_id", $usr_id, "usr_name");
             $usrRealFirstname = getFieldValueFromId("user", "usr_id", $usr_id, "usr_firstname");
             $hqName = "";
             $hqMnemonic = "";
             if ($hq_id > "0") :
                $hqName = getFieldValueFromId("headquarters", "hq_id", $hq_id, "hq_name");
                $hqMnemonic = getFieldValueFromId("headquarters", "hq_id", $hq_id, "hq_mnemonic");
             endif;

             if ($sessionHash != "" && $sessionHash == $sessionId) :
                $retBool = true;  // Authentication OK !!!
             endif;
          endif;
       endif;    
     endif;
  endif;

  if ($retBool) :
     writeToLogDB("52",$hq_id,"",$usr_id,"","","","ACCOUNT=" . $usrAccount . "|MESS=Login ok|IP=" . $currentClientIP);
  else :
     writeToLogDB("52",$hq_id,"",$usr_id,"","","","ACCOUNT=" . $usrAccount . "|MESS=Login NOT ok|IP=" . $currentClientIP);
  endif;

  return $retBool;
}

// Checks authentication based on two factors
// 1. Fix session ID per database instance (hash in metaobject) with mo_type = "system"
// 2. (Daily new) passphrase based on an one-direction-encryption algorithm executed on client side and compared with execution on server side
function checkRequestAuthenticationData2 ($sessionId, $passPhrase) {
	global $db, $PHP_SELF, $debug;
	global $dbname, $dblogin, $dbpassword, $usr_id;

  $retBool = false;
  if ($sessionId != "" && $passPhrase != "") :

    $sessionHash = "";
    // Get current global number of THIS database instance
    $constGlobalDbInstNo = getParameterValue("0", "GLOBAL_UNIQUE_DB_INSTANCE_NO", "0", "0");
    if ($constGlobalDbInstNo != "" && is_numeric($constGlobalDbInstNo)) :

       // Get special system ID 
       $system_id = getParameterValue("0", "GLOBAL_SESSION_SYSTEM_ID", "0", "0");  // Fix ID like "42"
       if ($system_id != "" && is_numeric($system_id)) :

          // Get database instance connection data of metaobject
          $constExtDbInst = getExternalMetaDbInst();
          $db_conn = getDbConnectionSpecial($constExtDbInst, $dbname, $dblogin, $dbpassword);
          $tmpSqlQuery = "SELECT mo_hash FROM meta_object.metaobject WHERE mo_obj_type = 'system' AND mo_id_ref_db = '" . $constGlobalDbInstNo . "' AND mo_obj_id = '" . $system_id . "'";
          $result = $db_conn->query($tmpSqlQuery);
          while ($row = $result->fetch_assoc()):
             $sessionHash = $row["mo_hash"];
          endwhile;
          $result->free();

          // 1st check "session ID"
          if ($sessionHash != "" && $sessionHash == $sessionId) :

             // 2nd check "passphrase"
             $salt = getParameterValue("0", "GLOBAL_SESSION_SALT", "0", "0");  // Fix code like "34a78d91s83g"
             if ($salt != "") :
                if ($debug) :
                   echo "salt = " . $salt . "<br>";
                   echo "passPhrase = " . $passPhrase . "<br>";
                endif;
                if (checkPwd($passPhrase, $salt)) :
                   $retBool = true;  // Authentication OK !!!
                endif;
             endif;
          endif;
       endif;
    endif;
  endif;

  if ($retBool) :
     // writeToLogDB("52",$hq_id,"",$usr_id,"","","","ACCOUNT=" . $usrAccount . "|MESS=Login ok|IP=" . $currentClientIP);
  else :
     // writeToLogDB("52",$hq_id,"",$usr_id,"","","","ACCOUNT=" . $usrAccount . "|MESS=Login NOT ok|IP=" . $currentClientIP);
  endif;

  return $retBool;
}

function getSingleTagContent ($strToParse, $tagBegin, $tagEnd) {
  $tagContent = "";
  $repeat = TRUE;
  while ($repeat && !(strpos($strToParse, $tagBegin) === FALSE) && !(strpos($strToParse, $tagEnd) === FALSE)) :

     $pos0 = strpos($strToParse, $tagBegin);                         // begin of tagBegin (first occurrence)
     $pos1 = strpos($strToParse, $tagBegin) + strlen($tagBegin);     // end of tagBegin   (first occurrence)
     $pos2 = strpos($strToParse, $tagEnd);                           // begin of tagEnd   (first occurrence)
     $pos3 = strpos($strToParse, $tagEnd) + strlen($tagEnd);         // end of tagEnd     (first occurrence)
     
     $repeat = FALSE;
     if ($pos2 - $pos1 > 0) :
        // Get the content of the tag
        $tagContent = substr($strToParse, $pos1, $pos2 - $pos1);
     endif;
  endwhile;
  return $tagContent;
};

function getTagContent ($strToParse, $tagBegin, $tagEnd) {
  $tagContentArray = array();
  $repeat = TRUE;
  while ($repeat && !(strpos($strToParse, $tagBegin) === FALSE) && !(strpos($strToParse, $tagEnd) === FALSE)) :
     $pos0 = strpos($strToParse, $tagBegin);                         // begin of tagBegin (first occurrence)
     $pos1 = strpos($strToParse, $tagBegin) + strlen($tagBegin);     // end of tagBegin   (first occurrence)
     $pos2 = strpos($strToParse, $tagEnd);                           // begin of tagEnd   (first occurrence)
     $pos3 = strpos($strToParse, $tagEnd) + strlen($tagEnd);         // end of tagEnd     (first occurrence)
     if ($pos2 - $pos1 > 0) :
        // Get the content of the tag
        $tmpContent = substr($strToParse, $pos1, $pos2 - $pos1);
        $tagContentArray[] = $tmpContent;
        $strToParse = str_replace($tagBegin . $tmpContent . $tagEnd, "", $strToParse);
     endif;
  endwhile;
  return $tagContentArray;
}

// Returns the whole value in $strToParse with removed tags (e.g. "<postparser>....</postparser>") and
// the tag content is substituted by $substitutionString with macro [TAG_CONTENT] by itself is replaced by tag content
function substituteSingleTagContent ($strToParse, $tagBegin, $tagEnd, $substitutionString, $macro = "[TAG_CONTENT]") {
  $tagContent = "";
  $repeat = TRUE;
  while ($repeat && !(strpos($strToParse, $tagBegin) === FALSE) && !(strpos($strToParse, $tagEnd) === FALSE)) :

     $pos0 = strpos($strToParse, $tagBegin);                         // begin of tagBegin (first occurrence)
     $pos1 = strpos($strToParse, $tagBegin) + strlen($tagBegin);     // end of tagBegin   (first occurrence)
     $pos2 = strpos($strToParse, $tagEnd);                           // begin of tagEnd   (first occurrence)
     $pos3 = strpos($strToParse, $tagEnd) + strlen($tagEnd);         // end of tagEnd     (first occurrence)
     
     $repeat = FALSE;
     if ($pos2 - $pos1 > 0) :
        // Get the content of the tag
        $tagContent = substr($strToParse, $pos1, $pos2 - $pos1);

        // Replace macro (e.g. "[TAG_CONTENT]") with tag content
        $substitutionString = str_replace($macro, $tagContent, $substitutionString);

        // Replace tags with substitution phrase
        $strToParse = substr_replace($strToParse, $substitutionString, $pos0, $pos3 - $pos0);
     endif;
  endwhile;
  return $strToParse;
};

// Returns the whole value in $strToParse with ALL removed tags (e.g. "<postparser>....</postparser>") and
// ALL tag content are substituted by $substitutionString with macro [TAG_CONTENT] by itself is replaced by tag content
function substituteTagContent ($strToParse, $tagBegin, $tagEnd, $substitutionString, $macro = "[TAG_CONTENT]") {
  $tagContentArray = array();
  $repeat = TRUE;
  while ($repeat && !(strpos($strToParse, $tagBegin) === FALSE) && !(strpos($strToParse, $tagEnd) === FALSE)) :
     $pos0 = strpos($strToParse, $tagBegin);                         // begin of tagBegin (first occurrence)
     $pos1 = strpos($strToParse, $tagBegin) + strlen($tagBegin);     // end of tagBegin   (first occurrence)
     $pos2 = strpos($strToParse, $tagEnd);                           // begin of tagEnd   (first occurrence)
     $pos3 = strpos($strToParse, $tagEnd) + strlen($tagEnd);         // end of tagEnd     (first occurrence)

     $tmpSubstitutionString = $substitutionString;                   // Do not change the original value
     if ($pos2 - $pos1 > 0) :
        // Get the content of the tag
        $tagContent = substr($strToParse, $pos1, $pos2 - $pos1);
        
        // Replace macro (e.g. "[TAG_CONTENT]") with tag content
        $tmpSubstitutionString = str_replace($macro, $tagContent, $tmpSubstitutionString);

        // Replace tags with substitution phrase
        $strToParse = substr_replace($strToParse, $tmpSubstitutionString, $pos0, $pos3 - $pos0);
     endif;
  endwhile;
  return $strToParse;
};

// Parses a XML and converts it to an array
function xml2array($contents, $get_attributes = 1, $priority = 'tag') {
	$retArray = array();

  if (function_exists('xml_parser_create')) :
     $contents = trim($contents);
     if ($contents != "") :
        $parser = xml_parser_create('UTF-8');   // ISO-8859-1
        xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
        xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
        xml_parse_into_struct($parser, $contents, $xml_values);
        xml_parser_free($parser);

        $xml_array = array ();
        $parents = array ();
        $opened_tags = array ();
        $arr = array ();
        $current = & $xml_array;
        $repeated_tag_index = array ();
        foreach ($xml_values as $data)
        {
            unset ($attributes, $value);
            extract($data);
            $result = array ();
            $attributes_data = array ();
            if (isset ($value))
            {
                if ($priority == 'tag')
                    $result = $value;
                else
                    $result['value'] = $value;
            }
            if (isset ($attributes) and $get_attributes)
            {
                foreach ($attributes as $attr => $val)
                {
                    if ($priority == 'tag')
                        $attributes_data[$attr] = $val;
                    else
                        $result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
                }
            }
            if ($type == "open")
            {
                $parent[$level -1] = & $current;
                if (!is_array($current) or (!in_array($tag, array_keys($current))))
                {
                    $current[$tag] = $result;
                    if ($attributes_data)
                        $current[$tag . '_attr'] = $attributes_data;
                    $repeated_tag_index[$tag . '_' . $level] = 1;
                    $current = & $current[$tag];
                }
                else
                {
                    if (isset ($current[$tag][0]))
                    {
                        $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
                        $repeated_tag_index[$tag . '_' . $level]++;
                    }
                    else
                    {
                        $current[$tag] = array (
                            $current[$tag],
                            $result
                        );
                        $repeated_tag_index[$tag . '_' . $level] = 2;
                        if (isset ($current[$tag . '_attr']))
                        {
                            $current[$tag]['0_attr'] = $current[$tag . '_attr'];
                            unset ($current[$tag . '_attr']);
                        }
                    }
                    $last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;
                    $current = & $current[$tag][$last_item_index];
                }
            }
            elseif ($type == "complete")
            {
                if (!isset ($current[$tag]))
                {
                    $current[$tag] = $result;
                    $repeated_tag_index[$tag . '_' . $level] = 1;
                    if ($priority == 'tag' and $attributes_data)
                        $current[$tag . '_attr'] = $attributes_data;
                }
                else
                {
                    if (isset ($current[$tag][0]) and is_array($current[$tag]))
                    {
                        $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
                        if ($priority == 'tag' and $get_attributes and $attributes_data)
                        {
                            $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
                        }
                        $repeated_tag_index[$tag . '_' . $level]++;
                    }
                    else
                    {
                        $current[$tag] = array (
                            $current[$tag],
                            $result
                        );
                        $repeated_tag_index[$tag . '_' . $level] = 1;
                        if ($priority == 'tag' and $get_attributes)
                        {
                            if (isset ($current[$tag . '_attr']))
                            {
                                $current[$tag]['0_attr'] = $current[$tag . '_attr'];
                                unset ($current[$tag . '_attr']);
                            }
                            if ($attributes_data)
                            {
                                $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
                            }
                        }
                        $repeated_tag_index[$tag . '_' . $level]++; //0 and 1 index is already taken
                    }
                }
            }
            elseif ($type == 'close')
            {
                $current = & $parent[$level -1];
            }
        }
        $retArray = $xml_array;
     endif;
  endif;
  return $retArray;
}

// Write to log file
function XMLRequestLogFile ($msg, $logLevel = 0, $logFile = "XML_Request.log", $logPath = "../log/") {
	global $hqId;
	$msg = trim($msg);
	$maxLogLevel = getParameterValue("0", "XML_REQUEST_LOGLEVEL_MAX", $hqId);
	if ($maxLogLevel == "") : $maxLogLevel = getParameterValue("0", "XML_REQUEST_LOGLEVEL_MAX", "0"); endif;
	if ($maxLogLevel == "") : $maxLogLevel = "2"; endif;
	if ($logLevel <= $maxLogLevel && $msg != "") :
     writeToFile($logPath . $logFile, $msg);
  endif;
}

// Write to log file
function CSVRequestLogFile ($msg, $logLevel = 0, $logFile = "CSV_Request_Log.csv", $logPath = "../log/") {
	global $hqId;
	$msg = trim($msg);
	$maxLogLevel = getParameterValue("0", "CSV_REQUEST_LOGLEVEL_MAX", $hqId);
	if ($maxLogLevel == "") : $maxLogLevel = getParameterValue("0", "CSV_REQUEST_LOGLEVEL_MAX", "0"); endif;
	if ($maxLogLevel == "") : $maxLogLevel = "0"; endif;
	if ($msg != "" && (((int)$logLevel & (int)$maxLogLevel) > 0)) :
     writeToFile($logPath . $logFile, $msg);
  endif;
}

// Special encoding
function mcEncode ($text, $mode = "0") {
  if ($mode == "1") :
     // ...
  else :
     if (preg_match("/[äöüÄÖÜß]/", $text) == 1) :
        $text = utf8_encode($text);
     endif;
  endif;
  return $text;
}

// Special decoding
function mcDecode ($text, $mode = "0") {
  if ($mode == "1") :
     // ...
  else :
     $text = utf8_decode($text);
     $text = str_replace("ÃŸ", "ß", $text);
     $text = str_replace("Ã¤", "ä", $text);
     $text = str_replace("Ã¶", "ö", $text);
     $text = str_replace("Ã¼", "ü", $text);
     $text = str_replace("Ã„", "Ä", $text);
     $text = str_replace("Ã–", "Ö", $text);
     $text = str_replace("Ãœ", "Ü", $text);
  endif;
  return $text;
}

// Converts the content of an tag
function convertSpecial ($str, $conversionType = "") {
	if (is_array($str) && count($str) == 0) : 
	   $str = "";
	endif;
	$str = trim($str);
	$str = str_replace("'", "", $str);
	$str = mcDecode($str);
	$str = str_replace("'", "", $str);
	if ($str != "" && $conversionType == "intval") :
	   $str = intval($str);
	endif;
	return $str;
}

// Converts the content of an tag and replace decimal sign
function convertNumSpecial ($str, $conversionType = "") {
	$str = convertSpecial($str, $conversionType);
  $str = str_replace (",", ".", $str);
	return $str;
}

// Checks the datetime format (Look for PHP-Version)
function checkDateTimeFormat($dateTimeToBeChecked, $dateTimeFormat = "Y-m-d H:i:s") {
	// Check compability of format
  if ($dateTimeToBeChecked != "" && $dateTimeFormat != "") :
     $xDate = date_create($dateTimeToBeChecked);
     $dateTimeToBeChecked = "";  // Init
     if ($xDate) :
        $dateTimeToBeChecked = $xDate->format('Y-m-d H:i:s');
     endif;
  else :
     $dateTimeToBeChecked = "";  // Init
  endif;
  // Check special date ranges for
  if ($dateTimeToBeChecked != "") :
     // 
  endif;
  return $dateTimeToBeChecked;
}
?>