<?php

$HTTP_POST_VARS = !empty($HTTP_POST_VARS) ? $HTTP_POST_VARS : $_POST;
$HTTP_GET_VARS = !empty($HTTP_GET_VARS) ? $HTTP_GET_VARS : $_GET;
$HTTP_COOKIE_VARS = !empty($HTTP_COOKIE_VARS) ? $HTTP_COOKIE_VARS : $_COOKIE;
$HTTP_SERVER_VARS = !empty($HTTP_SERVER_VARS) ? $HTTP_SERVER_VARS : $_SERVER;
$HTTP_ENV_VARS = !empty($HTTP_ENV_VARS) ? $HTTP_ENV_VARS : $_ENV;
$HTTP_POST_FILES = !empty($HTTP_POST_FILES) ? $HTTP_POST_FILES : $_FILES;

if (!isset($PHP_SELF))
  $PHP_SELF = $_SERVER["PHP_SELF"];

if (substr(phpversion(), 0, 3) >= "5.1") :
   date_default_timezone_set('Europe/Berlin');
endif;

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


// *****************************************************************************

// Decryption
// Takes the parameter "$value" and returns the decrypted, original value
// See also corresponding function "ec" for encryption of the original value
function dc($value) {
   global $eca, $randomCryptionNumber;
   $len = strlen(HTTP_VARS_SEC_SEQ);
   if ((HTTP_VARS_SEC_STATE == "1") && (substr($value, 0, $len) == HTTP_VARS_SEC_SEQ) && (substr($value, -$len) == HTTP_VARS_SEC_SEQ)) :
      // Extract value from identificator-box
      $value = substr($value, strlen(HTTP_VARS_SEC_SEQ), -strlen(HTTP_VARS_SEC_SEQ));      

      // Decrypt the encrypted value
      if (is_numeric($value)) :
         $value = (((((((($value - $eca[4]) / 2) - $eca[3]) / 2) - $eca[2]) / 2) - $eca[1]) / 2) - $eca[0] - $randomCryptionNumber;
      else :
         $value = urldecode($value);
      endif;      
   endif;
   return $value;
}

function getHttpVars($httpVars)
{
  global $HTTP_GET_VARS, $HTTP_POST_VARS;
  
  $retArr = array();
  foreach($httpVars as $hVar)
    $retArr[] = (isset($HTTP_GET_VARS[$hVar])) ? $HTTP_GET_VARS[$hVar] : 
      ((isset($HTTP_POST_VARS[$hVar])) ? $HTTP_POST_VARS[$hVar] : "");
  return $retArr;
}

// Gets all script-parameters (HTTP_GET_VARS and HTTP_POST_VARS).
// If "$mode == 1" then all id-parameters (only these!) will be decoded
function getSecHttpVars($getSecHttpVarsMode = "0", $httpVars)
{
  global $HTTP_GET_VARS, $HTTP_POST_VARS;

  $retArr = getHttpVars($httpVars);
  $i = 0;
  foreach ($httpVars as $par) {
      global $$par;
      $$par = $retArr[$i];
      $i++;
  }
  // Decryption of the fields if encrypted
  if ($getSecHttpVarsMode == "1") :
     foreach ($httpVars as $par) {
        $$par = dc($$par);
     }         
  endif;  
  return $retArr;
}  

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

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->query($sqlStmt);          
     if (DB::isError($result)) die ("$PHP_SELF: <br>$sqlStmt<br>" . $result->getMessage());
     while ($row = $result->fetch_assoc()):
           $retValue = $row[$field];
     endwhile;
     $result->free();
     return $retValue;
}

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";
// writeToFile("xxxxxxxx.log", $sqlStmt);
     $result = $dbConnection->query($sqlStmt);          
     if (DB::isError($result)) die ("$PHP_SELF: <br>$sqlStmt<br>" . $result->getMessage());
     while ($row = $result->fetch_assoc()):
           $retValue = $row[$field];
     endwhile;
     $result->free();       
     return $retValue;
}

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->query($sqlStmt);
     if (DB::isError($result)) die ("$PHP_SELF: <br>$sqlStmt<br>" . $result->getMessage());
     $pValName = (strpos($pValName, " AS ")) ? (substr(stristr($pValName, " AS "), 4)) : $pValName;
     $pValName = (strpos($pValName, ".")) ? (substr(stristr($pValName, "."), 1)) : $pValName;
     $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;
}

function getDbConnectionSpecial ($dbhost, $dbname, $dblogin, $dbpassword) {
  global $PHP_SELF;
  $db_conn = "";
  $dsn = "mysql://$dblogin:$dbpassword@$dbhost/$dbname";
  $db_conn = DB::connect($dsn, false);
  if (DB::isError($db_conn)) return "ERR_DB";
  $db_conn->setFetchMode(DB_FETCHMODE_ASSOC);
  return $db_conn;
}

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->query($sqlStmt);     
     if (DB::isError($result)) die ("$PHP_SELF: <br>$sqlStmt<br>" . $result->getMessage());
     while ($row = $result->fetch_assoc()):
           $retValue = TRUE;
     endwhile;
     $result->free();
     return $retValue;
}

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->query($sqlStmt);
     if (DB::isError($res)) die ("$PHP_SELF:<br>$sqlStmt<br>" . $res->getMessage());
     
     return $res;
}

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();
  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->query($sqlStmt);
     if (DB::isError($res)) die ("$PHP_SELF: <br>$sqlStmt<br>" . $res->getMessage());   
     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 = $db->query($sqlStmt);       
       return $res;
     endif;
     return FALSE;
}

// 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;
}

// Gets the connection to the central meta objects table
function getConnectionToMetaDB ($dbName = "meta_object", $tableName = "metaobject") {
	global $dbhost, $dblogin, $dbpassword;
  // $constExtDbInst = getParameterValue("0", "EXTERNAL_DB_METAOBJECT", "0", "0");
  $constExtDbInst = $dbhost;
  $db_conn = getDbConnectionSpecial($constExtDbInst, $dbName, $dblogin, $dbpassword);
  if ($db_conn == "ERR_DB") :
     // Check cascade of replicants
     $constExtDbInst = "172.16.0.111:3711";
     $db_conn = getDbConnectionSpecial($constExtDbInst, $dbName, $dblogin, $dbpassword);
     if ($db_conn == "ERR_DB") :
        $constExtDbInst = "172.16.0.109:3711";
        $db_conn = getDbConnectionSpecial($constExtDbInst, $dbName, $dblogin, $dbpassword);
        if ($db_conn == "ERR_DB") :
           $constExtDbInst = "172.16.0.103:3711";
           $db_conn = getDbConnectionSpecial($constExtDbInst, $dbName, $dblogin, $dbpassword);
        endif;
     endif;
     // Send info mail
     // sendInternalMail("metaobject_db_fail");
  endif;
  return $db_conn;
}

// Gets all databases and its IPs and ports listed in the central meta objects table
function getGlobalDbEnvironments ($dbName = "meta_object", $tableName = "metaobject") {
  $dbhostArray = array();
  $db_conn = getConnectionToMetaDB($dbName, $tableName);
  if ($db_conn != "ERR_DB") :
     $sqlquery = "SELECT mo_mnemonic, mo_value FROM " . $dbName . "." . $tableName . " AS mo WHERE mo_obj_type = 'db' AND mo_mnemonic != ''";
     $result = $db_conn->query($sqlquery);
     if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
     while ($row = $result->fetch_assoc()):
           $dbhostArray[$row["mo_mnemonic"]] = $row["mo_value"];
     endwhile;
     $result->free();
  endif;
  return $dbhostArray;
}

// Gets the operational database via connection data of metaobject
function getOperationalDatabase ($moId) {
	global $db, $PHP_SELF;
	global $dbhost, $dbname, $dblogin, $dbpassword;
	$retVal = "";
	if ($moId != "" && is_numeric($moId)) :
     // $constExtDbInst = getExternalMetaDbInst();
     $constExtDbInst = $dbhost;
     if ($constExtDbInst != "") :
        $db_conn = getDbConnectionSpecial($constExtDbInst, $dbname, $dblogin, $dbpassword);
        $tmpSqlQuery = "SELECT mo_value FROM meta_object.metaobject WHERE mo_id = '" . $moId . "' AND mo_obj_type = 'db'";
        $result = $db_conn->query($tmpSqlQuery);
        while ($row = $result->fetch_assoc()):
              $retVal = $row["mo_value"];
        endwhile;
        $result->free();
     endif;
  endif;
  return $retVal;
}

// Gets XML tag
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;
};

// Get the actual DATETIME (e.g. according to the scheme needed in MySql)
function getDateTime($mode = "0", $dateTimeArray = "", $formatStr = "") {
   $retVal = "";   
   if ($mode == "0") : $retVal = date("Y-m-d H:i:s"); endif;            // 2003-03-10 17:16:17
   if ($mode == "1") : $retVal = date("Ymd"); endif;                    // 20030310
   if ($mode == "2") : $retVal = date("m.d.y"); endif;                  // 03.10.01
   if ($mode == "3") : $retVal = date("Y-m-d"); endif;                  // 2003-03-10
   if ($mode == "4") : $retVal = date("H:i:s"); endif;                  // 17:16:17
   if ($mode == "5") : $retVal = date("d.m.Y"); endif;                  // 10.03.2003
   if ($mode == "6") : $retVal = date("YmdHis"); endif;                 // 20030310171617
   if ($mode == "7") : $retVal = date("dmY"); endif;                    // 31122003
   
   if ($mode == "day") : $retVal = date("d"); endif;                    // 01 .. 31
   if ($mode == "month") : $retVal = date("m"); endif;                  // 01 .. 12
   if ($mode == "year") : $retVal = date("Y"); endif;                   // 2003, ...
   if ($mode == "hour") : $retVal = date("H"); endif;                   // 00 .. 11
   if ($mode == "minute") : $retVal = date("i"); endif;                 // 00 .. 59
   if ($mode == "second") : $retVal = date("s"); endif;                 // 00 .. 59
   
   if ($mode == "now") : $retVal = date("YmdHis", mktime(date("H"),date("i"),date("s"),date("m"),date("d"),date("y"))); endif;    // 20090807105959

   if ($mode == "day_tomorrow") : $retVal = date("d",mktime(0,0,0,date("m"),date("d")+1,date("Y"))); endif;    // 01 .. 31
   if ($mode == "month_tomorrow") : $retVal = date("m",mktime(0,0,0,date("m"),date("d")+1,date("Y"))); endif;  // 01 .. 12
   if ($mode == "year_tomorrow") : $retVal = date("Y",mktime(0,0,0,date("m"),date("d")+1,date("Y"))); endif;   // 2003, ...
   
   if ($mode == "day_yesterday") : $retVal = date("d",mktime(0,0,0,date("m"),date("d")-1,date("Y"))); endif;    // 01 .. 31
   if ($mode == "month_yesterday") : $retVal = date("m",mktime(0,0,0,date("m"),date("d")-1,date("Y"))); endif;  // 01 .. 12
   if ($mode == "year_yesterday") : $retVal = date("Y",mktime(0,0,0,date("m"),date("d")-1,date("Y"))); endif;   // 2003, ...
   
   if ($mode == "date_plus_offset") :
      $retVal = date($formatStr, mktime(0,0,0,date("m")+$dateTimeArray[0],date("d")+$dateTimeArray[1],date("Y")+$dateTimeArray[2]));
   endif;
   
   if ($mode == "datetime_plus_offset") :
      $retVal = date($formatStr, mktime(date("H")+$dateTimeArray[0],date("i")+$dateTimeArray[1],date("s")+$dateTimeArray[2],date("m")+$dateTimeArray[3],date("d")+$dateTimeArray[4],date("Y")+$dateTimeArray[5]));
   endif;

   if ($mode == "format" && $dateTimeArray != "" && $formatStr != "") :
      // int mktime ( [int Stunde [, int Minute [, int Sekunde [, int Monat [, int Tag [, int Jahr [, int is_dst]]]]]]])
      $retVal = date($formatStr, mktime($dateTimeArray[0],$dateTimeArray[1],$dateTimeArray[2],$dateTimeArray[3],$dateTimeArray[4],$dateTimeArray[5]));
   endif;

   return $retVal;
}

?>