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

include_once ("../include/mcglobal.inc.php");
// include_once ("../include/auth.inc.php");
include_once ("../include/inc_calendar.inc.php");
include_once ("../groupware/calendar.php");
include_once ("../statistic/statistic_sql.inc.php");
include_once ("../include/email/htmlMimeMail.php");
include_once ("../include/inc_parseXML.inc.php");
include_once ("../include/inc_customer.inc.php");

getLanguage(__FILE__);

getCurrentScript(__FILE__);


function authCheckEmployeeRightsUser($usrId, $menuModeId, $referer = "") {
   $hasAccess = false;
   $empId = getFieldValueFromId("employee", "usr_id", $usrId, "emp_id");
   $empRights = getRights($empId);
   if (substr($empRights,$menuModeId,1) == "1") :
      $hasAccess = true;  // Authentication ok
   endif;
   return $hasAccess;
}

function login ($usrName, $usrPassword) {
	global $db, $PHP_SELF;
	global $dbname, $dblogin, $dbpassword;

  $retArray = array();
  if ($usrName == "" || $usrPassword == "") : 
     $retArray = array("201","<err_no>201</err_no>\n","<err_desc>" . getLngt("Benutzername oder Passwort nicht spezifiziert.") . "</err_desc>\n");
  else :
     $sqlquery = "SELECT usr_id, hq_id FROM user WHERE usr_account = '$usrName' AND usr_password = PASSWORD('$usrPassword') AND usr_type = '1'";
     $result = $db->query($sqlquery);

     $usr_id = "";
     $hq_id = "";
     if (DB::isError($result)):  
       $retArray = array("202","<err_no>202</err_no>\n","<err_desc>" . getLngt("Datenbankfehler") . "</err_desc>\n");
     else:

       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 == '') :
          $retArray = array("203","<err_no>203</err_no>\n","<err_desc>" . getLngt("Benutzerdaten unbekannt.") . "</err_desc>\n");
          writeToLogDB("52",$hq_id,"",$usr_id,"","","","ACCOUNT=" . $usrName . "|MESS=Login failed|IP=" . $currentClientIP);
       else :
          // Check for rights (cs=0, grp=11, rp=16)
          if (!(authCheckEmployeeRightsUser($usr_id, "0") && authCheckEmployeeRightsUser($usr_id, "11") && authCheckEmployeeRightsUser($usr_id, "16"))) :
             $retArray = array("205","<err_no>205</err_no>\n","<err_desc>" . getLngt("Berechtigungen fehlen.") . "</err_desc>\n");
             writeToLogDB("52",$hq_id,"",$usr_id,"","","","ACCOUNT=" . $usrName . "|ACCESS=No rights|IP=" . $currentClientIP);
          else : 
             // 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;
   
             if ($sessionHash != "") :
                $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;
                $retArray = array("0", $usr_id, $hq_id, $sessionHash, $usrRealName, $usrRealFirstname, $hqName, $hqMnemonic);
                writeToLogDB("52",$hq_id,"",$usr_id,"","","","ACCOUNT=" . $usrName . "|MESS=Login ok|IP=" . $currentClientIP);
             else :
                $retArray = array("204","<err_no>204</err_no>\n","<err_desc>" . getLngt("Keine Session-ID für den Benutzer verfügbar.") . "</err_desc>\n");
                writeToLogDB("52",$hq_id,"",$usr_id,"","","","ACCOUNT=" . $usrName . "|MESS=Login failed|IP=" . $currentClientIP);
             endif;
          endif;
       endif;    
     endif;
  endif;
  return $retArray;
}

function checkAccess ($sessionHash) {
	global $db, $PHP_SELF;
	global $dbname, $dblogin, $dbpassword;
	global $usr_id, $hq_id;

  $retBool = false;
  if ($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_obj_id FROM meta_object.metaobject WHERE mo_obj_type = 'usr' AND mo_id_ref_db = '" . $constGlobalDbInstNo . "' AND mo_hash = '" . $sessionHash . "'";
        $result = $db_conn->query($tmpSqlQuery);
        while ($row = $result->fetch_assoc()):
               $usr_id = $row["mo_obj_id"];               
               $retBool = true;
        endwhile;
        $result->free();
        $hq_id = getFieldValueFromId("user", "usr_id", $usr_id, "hq_id");
     endif;
  endif;
  return $retBool;
}



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

// *****************
// *** CONSTANTS ***
// *****************

// <IS_IMPLEMENTED>

// $calWeekDays = getColVectorFromDB2Array("metatype","mt_type","cal_week_days","mt_value","mt_sort");
// $calMonthNames = getColVectorFromDB2Array("metatype","mt_type","cal_months","mt_value","mt_sort");

// $calCurrentDayNumOfTheYear = date("z", mktime(0, 0, 0, $selMonth, $selDay, $selYear));   // 0 .. 365
// $calCurrentDayNumOfTheYear++;  // Increment ...
// $calCurrentDayNumOfTheWeek = date("w", mktime(0, 0, 0, $selMonth, $selDay, $selYear));   // 0 = Sunday, 1 = Monday, etc.
// if ($calCurrentDayNumOfTheWeek == 0) : $calCurrentDayNumOfTheWeek = "7"; endif;          // Reformat to 1 = Monday, ... , 7 = Sunday
// $calCurrentWeekNum = date("W", mktime(0, 0, 0, $selMonth, $selDay, $selYear));           // Calendar week
// $calCurrentWeekName = "KW";                                                              // Calendar week name


// $calMonthDays = array("31","28","31","30","31","30","31","31","30","31","30","31");
// $calCurrentYearIsLeapYear = date("L", mktime(0, 0, 0, $selMonth, $selDay, $selYear));
// if ($calCurrentYearIsLeapYear == "1") : $calMonthDays[1] = "29"; endif;    

// $minuteArray = array("00","05","10","15","20","25","30","35","40","45","50","55");

// </IS_IMPLEMENTED>


// ***********************
// *** Initialisations ***
// ***********************



// $messageReqRawData = file_get_contents('php://input');
getSecHttpVars("1", array("data"));
$messageReq = $data;
// $messageReq = mcDecode($messageReq);

$currentTime = getDateTime("0");
$currentClientIP = trim($_SERVER['REMOTE_ADDR']);
writeToFile("../log/mobile.log", $currentTime . " | " . $currentClientIP);
// writeToFile("../log/mobile.log", $messageReqRawData);
writeToFile("../log/mobile.log", $messageReq);
writeToFile("../log/mobile.log", "-------------------------------------------------------------------------------------------");

// Check for POST raw data
$functionName   = getSingleTagContent($messageReq, "<id>", "</id>");
$userName       = getSingleTagContent($messageReq, "<username>", "</username>");
$userPassword   = getSingleTagContent($messageReq, "<password>", "</password>");
$userSession    = getSingleTagContent($messageReq, "<session>", "</session>");
$selYear        = getSingleTagContent($messageReq, "<year>", "</year>");
$selMonth       = getSingleTagContent($messageReq, "<month>", "</month>");
$selWeek        = getSingleTagContent($messageReq, "<week>", "</week>");
$selDay         = getSingleTagContent($messageReq, "<day>", "</day>");
$apId           = getSingleTagContent($messageReq, "<apid>", "</apid>");
$apText         = getSingleTagContent($messageReq, "<aptext>", "</aptext>");
$execDatetime   = getSingleTagContent($messageReq, "<execdatetime>", "</execdatetime>");
$endDatetime    = getSingleTagContent($messageReq, "<enddatetime>", "</enddatetime>");
$usr_id         = getSingleTagContent($messageReq, "<usrid>", "</usrid>");
$csId           = getSingleTagContent($messageReq, "<csid>", "</csid>");
$csEid          = getSingleTagContent($messageReq, "<cseid>", "</cseid>");
$hq_id          = getSingleTagContent($messageReq, "<hqid>", "</hqid>");
$apCat1         = getSingleTagContent($messageReq, "<apcat1>", "</apcat1>");
$apCat2         = getSingleTagContent($messageReq, "<apcat2>", "</apcat2>");
$apCat3         = getSingleTagContent($messageReq, "<apcat3>", "</apcat3>");
$apCat4         = getSingleTagContent($messageReq, "<apcat4>", "</apcat4>");
$viewMode       = getSingleTagContent($messageReq, "<view>", "</view>");
$actionMode     = getSingleTagContent($messageReq, "<actionmode>", "</actionmode>");
$usrIdsParticipantsString = getSingleTagContent($messageReq, "<participants>", "</participants>");
$search         = getSingleTagContent($messageReq, "<search>", "</search>");
$fromDateRange  = getSingleTagContent($messageReq, "<fromdaterange>", "</fromdaterange>");
$toDateRange    = getSingleTagContent($messageReq, "<todaterange>", "</todaterange>");
$rpId           = getSingleTagContent($messageReq, "<rpid>", "</rpid>");
$rpType         = getSingleTagContent($messageReq, "<rptype>", "</rptype>");   // 1="Verschiedenes", 2="Abschluss", 3="Angebotserstellung", ... 10="Konferenz/Seminar/Urlaub", ...
$rpObjType      = getSingleTagContent($messageReq, "<rpobjtype>", "</rpobjtype>");   // "cs", "cr", ...
$rpObjId        = getSingleTagContent($messageReq, "<rpobjid>", "</rpobjid>");   // e.g. "cs_id = 20001 = rpObjId || cr_id = 3333 = rpObjId"
$rpConfidential = getSingleTagContent($messageReq, "<rpconfidential>", "</rpconfidential>");   // Kennzeichen für "Vertraulich"
$crId           = getSingleTagContent($messageReq, "<crid>", "</crid>");
$crEid          = getSingleTagContent($messageReq, "<creid>", "</creid>");
$rpText         = getSingleTagContent($messageReq, "<rptext>", "</rptext>");


// Decode
$search = mcDecode($search);
$userName = mcDecode($userName);
$userPassword = mcDecode($userPassword);
$apText = mcDecode($apText);
$rpText = mcDecode($rpText);

// Conversion
$execDatetime = substr($execDatetime, 0, 4) . "-" . substr($execDatetime, 4, 2) . "-" . substr($execDatetime, 6, 2) . " " . substr($execDatetime, 8, 2) . ":" . substr($execDatetime, 10, 2) . ":" . substr($execDatetime, 12, 2);
$endDatetime = substr($endDatetime, 0, 4) . "-" . substr($endDatetime, 4, 2) . "-" . substr($endDatetime, 6, 2) . " " . substr($endDatetime, 8, 2) . ":" . substr($endDatetime, 10, 2) . ":" . substr($endDatetime, 12, 2);

// HARDCODED START ENVIRONMENT
if (!isset($hq_id) || $hq_id == "") : $hq_id = ""; endif;      // Empty for default
$f_selUsrId = "0";   // No user selected
if ($usr_id != "") :
   $f_selUsrId = $usr_id;
endif;
if (!isset($rpObjType) || $rpObjType == "") : $rpObjType = "cs"; endif;      // "cs" default (for test)
// "login"
/*
$functionName = "login";
$userName = "hh_testapp";
$userPassword = "testx12345";
$usrIdsParticipants = array();
*/
// "getAppointmentsOfOneMonth"
/*
$functionName = "getAppointmentsOfOneMonth";
$usrIdsParticipants = array();
$userSession = "728af2fb27f319c4be373ea371e0aba4";
*/
// "getCustomerList"
/*
$functionName = "getCustomerList";
$userSession = "728af2fb27f319c4be373ea371e0aba4";
$search = "ther";
*/
// "getCustomerSpecial"
/*
$functionName = "getCustomerSpecial";
$userSession = "6651526b6fb8f29a00507de6a49ce30fec8956637a99787bd197eacd77acce5e2b4ead82e2c7758545e7af34ef7b58cbd41d8cd98f00b204e9800998ecf8427e";
$csId = "20815";
*/
/*
$functionName = "getReportList";
$userSession = "728af2fb27f319c4be373ea371e0aba4";
*/
/*
$functionName = "actionReport";
$userSession = "728af2fb27f319c4be373ea371e0aba4";
$actionMode = "insert";
$rpObjId = "20815"; // <=> $csEid = "HTHH41943";
$rpType = "3";
$rpText = "APP TEST INSERT !!!";
$rpConfidential = "1";
*/


// Mode for output if requested
if ($viewMode == "") : $viewMode = "1"; endif;

// Customer
if ($csEid != "" && $csId == "") :
   $csId = getFieldValueFromId("customer", "cs_eid", $csEid, "cs_id");
endif;
if ($csEid == "" && $csId != "") :
   $csEid = getFieldValueFromId("customer", "cs_id", $csId, "cs_eid");
endif;

// Report
if ($rpObjType == "cs") :
   // Customer of the report
   if ($csEid != "" && $rpObjId == "") :
      $rpObjId = getFieldValueFromId("customer", "cs_eid", $csEid, "cs_id");
   endif;
   if ($csEid == "" && $rpObjId != "") :
      $csEid = getFieldValueFromId("customer", "cs_id", $rpObjId, "cs_eid");
   endif;
elseif ($rpObjType == "cr") :
   // Customer of the report
   if ($crEid != "" && $rpObjId == "") :
      $rpObjId = getFieldValueFromId("courier", "cr_eid", $crEid, "cr_id");
   endif;
   if ($crEid == "" && $rpObjId != "") :
      $crEid = getFieldValueFromId("courier", "cr_id", $rpObjId, "cr_eid");
   endif;
endif;

// Mandator filter
if ($f_hq_id == "") : $f_hq_id = array(); endif;
if (count($f_hq_id) == 0) : array_push($f_hq_id, $hq_id); endif;

if ($selYear == "") : $selYear = date("Y"); endif;
if ($selMonth == "") : $selMonth = date("m"); endif;
if ($selWeek == "") : $selWeek = date("W"); endif;
if ($selDay == "") : $selDay = date("d"); endif;

// Check ranges of time. All fields have to be set
if ($f_hour == "" || $f_minute == "" || $f_hour_to == "" || $f_minute_to == "") :
    $f_hour = "00";
    $f_minute = "00";
    $f_hour_to = "23";
    $f_minute_to = "59";
endif;
$f_hour = pad($f_hour,2);
$f_minute = pad($f_minute,2);
$f_hour_to = pad($f_hour_to,2);
$f_minute_to = pad($f_minute_to,2);

// Time range
if ($fromTimeRange == "" && $f_hour != "" && $f_minute != "") :
   $fromTimeRange = " " . $f_hour . ":" . $f_minute . ":00";
endif;
if ($toTimeRange == "" && $f_hour != "" && $f_minute != "") :
   $toTimeRange = " " . $f_hour . ":" . $f_minute . ":59";
endif;

// Date range
if ($fromDateRange == "" && $f_year != "" && $f_month != "" && $f_day != "") :
   $fromDateRange = $f_year . "-" . pad($f_month,2) . "-" . pad($f_day,2) . $fromTimeRange;
endif;
if ($toDateRange == "" && $f_year_to != "" && $f_month_to != "" && $f_day_to != "") :
   $toDateRange = $f_year_to . "-" . pad($f_month_to,2) . "-" . pad($f_day_to,2) . $toTimeRange;
endif;


// Appointment categories
if ($apCat1 == "") : $apCat1 = "1"; endif;    // State: Business (default), private
if ($apCat2 == "") : $apCat2 = "1"; endif;    // Visibility: Participants, only author, everybody
if ($apCat3 == "") : $apCat3 = "1"; endif;    // Kind: Misc., Meeting, reminder, ...
if ($apCat4 == "") : $apCat4 = "0"; endif;    // Deadline monitoring on/off

// Participants
$usrIdsParticipants = array();
if ($usrIdsParticipantsString != "") :
   $usrIdsParticipants = spliti(",", $usrIdsParticipantsString);
endif;



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

// <IS_IMPLEMENTED>

// Gets the last calendar week (number) of a specified year
// function calLastWeekNumofYear($selYear) {};

// Gets the first calendar week (number) of a specified month and year (calendar week of the 01.01.YYYY)
// function calFirstWeekNumofMonth($selMonth, $selYear) {};

// Gets the first day (number) of a specified month and year
// function calFirstDayNumOfMonth($selMonth, $selYear) {};

// Gets the first day (number) of the first calendar week of a specified year, it has to be a "Monday"
// function calFirstDayNumOfFirstCalendarWeekOfYear($selYear) {};

// Gets the first day (number) of a specified calendar week and year
// function calFirstDayNumOfWeek($selWeek, $selYear) {};

// Gets an array with days of a specified month (and year), where there is at least one appointment per day
// function getDaysWithAppointments($selYear, $selMonth) {}

// Modifies array according to the appointments starting and ending on different days
// $apArray = Array with appointments of the time interval (week, month, ...)
// $lowerRangeDate = Date of the beginning of the interval (week, month, ...)
// $upperRangeDate = Date of the end of the interval (week, month, ...)
// function modifyIntervalAppointments2SingleDayAppointments($apArray, $lowerRangeDate, $upperRangeDate) {}

// Gets the appointments of one day
// function getAppointmentsOfOneDay($selYear, $selMonth, $selDay, $csId = "") {}

// Gets the appointments of one week
// function getAppointmentsOfOneWeek($selWeek, $selYear, $selMonth, $selDay, $csId = "") {}

// Gets the appointments of one month
// function getAppointmentsOfOneMonth($selYear, $selMonth, $csId = "") {}

// Gets the appointments of one year
// function getAppointmentsOfOneYear($selYear, $csId = "") {}

// Gets a customer list according to a special search string
// function getCustomerList ($search)             => defined in "inc_customer.inc.php"

// Gets special data from a single customer
// function getCustomerSpecial ($csId)            => defined in "inc_customer.inc.php"

// Gets ALL data from a special customer
// function getCustomer ($cmpId)                  => defined in "inc_customer.inc.php"

// Inserts a new customer
// function insertCustomer ($csArray = array())   => defined in "inc_customer.inc.php"

// </IS_IMPLEMENTED>


// Gets the headline with the current day
function getAppointmentHeader($viewMode, $selYear, $selMonth, $selDay, $selWeek) {
  global $calWeekDays,$calCurrentDayNumOfTheWeek, $calMonthNames, $calMonthDays;
  global $calCurrentWeekNum, $calCurrentWeekName, $calCurrentDayNumOfTheYear;

  $out = "";
  // Daily output
  if ($viewMode == "1") :
     // Name of the week day (E.g.: "Donnerstag") --- Day, Name of the month and year  (E.g.: "29 Juni 2006") --- calendar week (E.g.: "KW 26")
     $out .= $calWeekDays[$calCurrentDayNumOfTheWeek - 1] . ", " . $selDay . ". " . $calMonthNames[$selMonth - 1] . " " . $selYear . "     " . $calCurrentWeekName . " " . $calCurrentWeekNum . "     " . $calCurrentDayNumOfTheYear . getLngt(". Tag des Jahres");
  endif;
  // Weekly output
  if ($viewMode == "2") :
     // Get the first day ("Monday") of the specified week and compute date interval of the week
     $firstDayOfWeek = calFirstDayNumOfWeek($selWeek, $selYear);
     $tmpDatetime = mktime(0, 0, 0, $firstDayOfWeek[1], $firstDayOfWeek[0] + 6, $firstDayOfWeek[2]);
     // calendar week                    (E.g.: "KW 26")
     $out .= $calCurrentWeekName . " " . $selWeek . "     " . "[" . $selYear . "]" . "     " . $firstDayOfWeek[0] . "." . $firstDayOfWeek[1] . "." . ($firstDayOfWeek[2] != date("Y", $tmpDatetime) ? $firstDayOfWeek[2] : "") . " - " . date("d", $tmpDatetime) . "." . date("m", $tmpDatetime) . "." . ($firstDayOfWeek[2] != date("Y", $tmpDatetime) ? date("Y", $tmpDatetime) : "") . "&nbsp;";
  endif;
  // Monthly output
  if ($viewMode == "3") :
     // Name of the month and year  (E.g.: "Juni 2006")
     $out .= $calMonthNames[$selMonth - 1] . " " . $selYear . "     " . "01." . $selMonth . ". - " . $calMonthDays[$selMonth - 1] . "." . $selMonth . ".";
  endif;
  // Yearly output
  if ($viewMode == "4") :
     // Name of the year  (E.g.: "2006")
     $out .= $selYear . "     " . "01.01. - 31.12.";
  endif;
  return $out;
}

// Gets the title of the output table
function getAppointmentTitle($viewMode) {
  $appointmentTitleArray = array();
  // Daily output
  if ($viewMode == "1") :
     $appointmentTitleArray = array(getLngt("Beginn"), getLngt("Ende"), getLngt("Ersteller, Teilnehmer"), getLngt("Kunde"), getLngt("Aktion"));
  endif;
  // Weekly output
  if ($viewMode == "2") :
     $appointmentTitleArray = array(getLngt("Tag"), getLngt("Zeit"), getLngt("Ersteller, Teilnehmer"), getLngt("Beschreibung"), getLngt("Kunde"));
  endif;  
  return $appointmentTitleArray;
}


// ***********
// * Actions *
// ***********

// DB actions for an appointment
function actionAppointment ($actionMode, $apId, $apText, $execDatetime, $endDatetime, $hq_id, $usr_id, $csId, $usrIdsParticipants, $apCat1, $apCat2, $apCat3, $apCat4) {
	global $db, $PHP_SELF;
	$opCode = "0";
	$currentTime = getDateTime("0");
	$sendPerMail = false;
	$apText = trim($apText);
  // $execDatetime = getDateTime("format",array($f_hour,$f_minute,0,$f_month,$f_day,$f_year),"Y-m-d H:i:s");
  // $endDatetime = getDateTime("format",array($f_hour_to,$f_minute_to,0,$f_month_to,$f_day_to,$f_year_to),"Y-m-d H:i:s");

  if (($actionMode == "insert" && $apText != "") || ($actionMode == "update" && $apId != "")) :
     if ($hq_id != "" && $usr_id != "") :
	      if ($execDatetime != "" && $endDatetime != "" && $execDatetime <= $endDatetime) :
           $usrIdsParticipantsString = "";
           if ($usrIdsParticipants != "" && count($usrIdsParticipants) > 0) :
              $usrIdsParticipantsString = "," . implode(",", $usrIdsParticipants) . ",";
           endif;
           if ($actionMode == "insert") :
              // Insert values
              insertStmt("phoenix_group.appointment", array("usr_id", $usr_id, "hq_id", $hq_id, "ap_category_1", $apCat1, "ap_category_2", $apCat2,
                                                            "ap_category_3", $apCat3, "ap_category_4", $apCat4,
                                                            "ap_participants", $usrIdsParticipantsString, "ap_text", $apText, 
                                                            "ap_execdate", $execDatetime, "ap_enddate", $endDatetime, 
                                                            "ap_modifytime", $currentTime, "cs_id", $csId));
              $opCode = getLastInsertID();
           elseif ($actionMode == "update") :
              // Update values
              updateStmt("phoenix_group.appointment", "ap_id", $apId, array("ap_category_1", $apCat1, "ap_category_2", $apCat2, "ap_category_3", $apCat3,"ap_category_4", $apCat4,
                                                                            "ap_participants", $usrIdsParticipantsString, "ap_text", $apText, "ap_execdate", $execDatetime, "ap_enddate", $endDatetime, 
                                                                            "ap_modifytime", $currentTime, "cs_id", $csId));
              $opCode = $apId;
           endif;
           $sendPerMail = true;
	      endif;
	   endif;

	elseif ($actionMode == "delete") :
	   if ($apId != "") :
	      deleteStmt("phoenix_group.appointment","ap_id = ".$apId);
	      $opCode = $apId;
	      $sendPerMail = true;
	   endif;
	
	elseif ($actionMode == "confirm") :
     if ($apId != "" && $usr_id != "") :
        // Get confirmation string from appointment
        $tmpApConfirmed = getFieldValueFromId("phoenix_group.appointment", "ap_id", $apId, "ap_confirmed");
        $tmpApConfirmed = substr($tmpApConfirmed,1,-1);   // Remove commata from db-field
        $tmpApConfirmed = spliti(",", $tmpApConfirmed);   // It has to be an array
        $j = array_search($usr_id, $tmpApConfirmed);
        if ($j === FALSE) :
           if (count($tmpApConfirmed) == 1 && trim($tmpApConfirmed[0] == "")) :
              $tmpApConfirmed = array($usr_id);
           else :         
              array_push($tmpApConfirmed, $usr_id);
           endif;
           updateStmt("phoenix_group.appointment", "ap_id", $apId, array("ap_confirmed", "," . implode(",", $tmpApConfirmed) . ","));
           $opCode = $apId;
        endif;
     endif;

	elseif ($actionMode == "finish") :
     if ($apId != "") :
        updateStmt("phoenix_group.appointment", "ap_id", $apId, array("ap_category_4", "2"));
        $opCode = $apId;
     endif;
  endif;

	if (false && $sendPerMail) :
     $mailAddresses = array();
     // Get email address of the creator of the appointment
     $fromEmailAddress = getFieldValueFromId("user", "usr_id", $usr_id, "usr_email");
     if (checkEmailFormat($fromEmailAddress)) : 
        array_push($mailAddresses, $fromEmailAddress);
     endif;
     // Get data of the appointment
     if ($actionMode == "insert" || $actionMode == "update") :
        $tmpParticipants = $usrIdsParticipants;
        $tmpText = $apText;
     elseif ($actionMode == "delete") :
        $tmpExecDatetime = getFieldValueFromId("phoenix_group.appointment", "ap_id", $apId, "ap_execdate");
        $tmpText = getFieldValueFromId("phoenix_group.appointment", "ap_id", $apId, "ap_text");
        $tmpParticipants = getFieldValueFromId("phoenix_group.appointment", "ap_id", $apId, "ap_participants");
          $tmpParticipants = substr($tmpParticipants,1,-1);   // Remove commata from db-field
          $tmpParticipants = spliti(",", $tmpParticipants);   // It has to be an array
     endif;
     $lenTmp = count($tmpParticipants);
     for ($i = 0; $i < $lenTmp; $i++) :
         $toEmailAddress = getFieldValueFromId("user", "usr_id", $tmpParticipants[$i], "usr_email");
         if (checkEmailFormat($toEmailAddress)) :
            array_push($mailAddresses, $toEmailAddress);
         endif;
     endfor;      
	   $mailAddressesString = implode(",", $mailAddresses);
	   $mailObj = new htmlMimeMail();

     // Format mailtext
     $mailtext  = "<html><head><meta text/html>";
     $mailtext .= "<style type=\"text/css\">";
     $mailtext .= ".f8np1 { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; font-weight: normal; padding: 1px}";
     $mailtext .= ".f8bp1 { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; font-weight: bold; padding: 1px}";
     $mailtext .= ".f8np1_red { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; font-weight: normal; padding: 1px; color: #FF0000;}";
     $mailtext .= "</style>";
     $mailtext .= "</head><body><h4>";
     
     $mailtext .= "<div class=\"f8bp1\">" . getLngt("Sehr geehrte Damen und Herren,") . "</div><br>";
     $tmpText = str_replace("\r", '<br>', $tmpText);
     $mailtext .= "<div class=\"f8bp1\">" . $tmpText . "</div><br>";
     $mailtext .= "<div class=\"f8bp1\">" . getLngt("Mit freundlichem Gruß!") . "</div><br>";

     // Logo
     $logoName = getParameterValue("0", "IMG_LOGO_NAME", $hq_id);
     $logoHeight = getParameterValue("0", "IMG_LOGO_HEIGHT", $hq_id);
     $logoWidth = getParameterValue("0", "IMG_LOGO_WIDTH", $hq_id);
     if ($logoName != "" && $logoHeight != "" && $logoWidth != "") :
        $mailtext .= "<br><div><img src=\"../images/external/" . $logoName . "\" border=\"0\" height=\"" . $logoHeight . "\" width=\"" . $logoWidth . "\"></div><br><br>";
     endif;
     $mailtext .= "</body></html>";
     
     $mailObj->setHtml($mailtext, null, "./");

     $mailObj->setFrom($fromEmailAddress);
     // $mailObj->setCc($mailCcAddress);
     // $mailObj->setBcc($mailBccAddress);
     $mailObj->setSubject(getLngt("Termin abgesagt: ") . $tmpExecDatetime);
     $mailResult = $mailObj->send(array($mailAddressesString), 'smtp');
     if (!$mailResult) :
        $statusMessage .= getLngt("Die Nachricht konnte nicht gesendet werden!") . " ";
     endif;
     $mailObj = NULL;
	endif;
	return $opCode;
}

// Gets a report list according to a special customer
function getReportList ($fromDateRange, $toDateRange, $rpObjType = "cs", $rpObjId = "", $rpType = "") {
	global $db, $PHP_SELF;
	global $f_hq_id;
	$retArray = array();

	if (false) :
	   // $retArray = array("301","<err_no>301</err_no>\n","<err_desc>" . getLngt("Ein Suchbegriff wurde nicht eingegeben!") . "</err_desc>\n");
	else :
     // Get status of the customer according to being meta customer
     $isMeta = "0";
     $csParentIdArray = array();
     if ($rpType == "cs" && $rpObjId != "" && is_numeric($rpObjId)) :
        if (existsEntry("customer",array("cs_id_parent",$rpObjId))) :
           $isMeta = "1";
           $csParentIdArray = getColVectorFromDB2Array("customer","cs_id_parent",$rpObjId,"cs_id","");
           array_push($csParentIdArray, $rpObjId);    // meta customer inclusive
        endif;
     endif;

	   $sqlquery = getReportListStatement ($fromDateRange, $toDateRange, $rpObjType, $rpObjId, $rpType, $isMeta, $csParentIdArray);	   
     $result = $db->query($sqlquery);
     if (DB::isError($result)):
        $retArray = array("202","<err_no>202</err_no>\n","<err_desc>" . getLngt("Datenbankfehler") . "</err_desc>\n");
     else:
        while ($row = $result->fetch_assoc()):
              $retArray[] = array($row["rp_id"], $row["rp_reporttype"], $row["rp_text"], $row["rp_confidential"], $row["rp_createtime"], $row["usr_id"], $row["usr_name"], $row["usr_firstname"], $row["usr_phone"], $row["eid"], $row["cmp_comp"], $row["cmp_comp2"], $row["hq_id"], $row["hq_name"]);
        endwhile;
        $result->free();
     endif;
	endif;

	return $retArray;
}

// DB actions for an report
function actionReport ($actionMode, $rpId, $rpType, $rpObjType = "cs", $rpObjId, $rpText, $rpConfidential = "0", $hq_id, $usr_id) {
	global $db, $PHP_SELF;
	$opCode = "0";
	$currentTime = getDateTime("0");
	$sendPerMail = false;
	$rpText = trim($rpText);
/*	
echo "actionMode: " . $actionMode . "<br>";
echo "rpId: " . $rpId . "<br>";
echo "rpType: " . $rpType . "<br>";
echo "rpObjType: " . $rpObjType . "<br>";
echo "rpObjId: " . $rpObjId . "<br>";
echo "rpText: " . $rpText . "<br>";
echo "rpConfidential: " . $rpConfidential . "<br>";
echo "hq_id: " . $hq_id . "<br>";
echo "usr_id: " . $usr_id . "<br>";
*/
/*
writeToFile("../log/mobile.log", "-----------------------------");
writeToFile("../log/mobile.log", "actionMode: " . $actionMode);
writeToFile("../log/mobile.log", "rpId: " . $rpId);
writeToFile("../log/mobile.log", "rpType: " . $rpType);
writeToFile("../log/mobile.log", "rpObjType: " . $rpObjType);
writeToFile("../log/mobile.log", "rpObjId: " . $rpObjId);
writeToFile("../log/mobile.log", "rpText: " . $rpText);
writeToFile("../log/mobile.log", "rpConfidential: " . $rpConfidential);
writeToFile("../log/mobile.log", "hq_id: " . $hq_id);
writeToFile("../log/mobile.log", "usr_id: " . $usr_id);
*/

  if (($actionMode == "insert" && $rpText != "") || ($actionMode == "update" && $rpId != "")) :
     if ($hq_id != "" && $usr_id != "") :
        if ($actionMode == "insert") :
           if ($rpObjId != "" && $rpObjType != "") :
              if ($rpText != "") :
                 // Insert values                 
                 insertStmt("phoenix_group.report_process", array("usr_id", $usr_id, "hq_id", $hq_id, "rp_reporttype", $rpType, "rp_text", $rpText,
                                                                  "rp_createtime", $currentTime, "rp_objId", $rpObjId, "rp_objtype", $rpObjType, "rp_confidential", $rpConfidential));
                 $opCode = getLastInsertID();
              endif;
           endif;
        elseif ($actionMode == "update") :
           // Update values
           if ($rpId != "" && $rpText != "") :
              updateStmt("phoenix_group.report_process", "rp_id", $rpId, array("rp_reporttype", $rpType, "rp_text", $rpText, "rp_confidential", $rpConfidential));
              $opCode = $apId;
           endif;
        endif;
	   endif;
	elseif ($actionMode == "delete") :
	   if ($rpId != "") :
        deleteStmt("phoenix_group.report_process","rp_id = ".$rpId);
	      $opCode = $rpId;
	   endif;
	endif;
	return $opCode;
}

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

// **************
// * XML Output *
// **************

$retVal = "";
$xmlOut = "";
$xmlNoErrOut .= "<err_no>0</err_no>\n<err_desc>OK</err_desc>\n";
$xmlErrOut .= "<err_no>100</err_no>\n<err_desc>Currently not implemented.</err_desc>\n";

if ($functionName == "login" || checkAccess($userSession)) :

   if ($transactionHandle != "") :
      // $xmlOut .= "<transaction_no>" . $transaction_no . "</transaction_no>\n";
   endif;

   $xmlOut .= "<data>\n";

   if (($hq_id != "" && is_numeric($hq_id)) || $functionName == "login") :

      if ($functionName != "") :
         if (function_exists($functionName) || $functionName == "getApEnvironment") :
      
            if ($functionName == "login") :
               $retVal = call_user_func_array($functionName, array($userName, $userPassword));   // Check user data
      
               if ($retVal[0] != "0") :
                  $xmlOut .= $retVal[1] . $retVal[2];
               else :
                  $usr_id = $retVal[1];
                  $hq_id = $retVal[2];
      
                  $xmlOut .= $xmlNoErrOut;
      
                  $xmlOut .= "<session>" . $retVal[3] . "</session>\n";
                  $xmlOut .= "<hqid>" . $hq_id . "</hqid>\n";
                  $xmlOut .= "<hqname><![CDATA[" . mcEncode($retVal[6]) . "]]></hqname>\n";
                  $xmlOut .= "<hqmnemonic>" . $retVal[7] . "</hqmnemonic>\n";
                  $xmlOut .= "<usrid>" . $usr_id . "</usrid>\n";
                  $xmlOut .= "<usrrealname><![CDATA[" . mcEncode($retVal[4]) . "]]></usrrealname>\n";
                  $xmlOut .= "<usrrealfirstname><![CDATA[" . mcEncode($retVal[5]) . "]]></usrrealfirstname>\n";
               endif;
      
            elseif ($functionName == "getApEnvironment") :
               if ($retVal[0] != "0") :
                  $xmlOut .= $xmlNoErrOut;
      
                  // Appointment categories
                  for ($j = 1; $j <= 4; $j++) :
                     $tmpApCatArray = getColVectorFromDB2ArrayByClause("metatype", "mt_value", "mt_type = 'appointment_category_" . $j . "'", "mt_sort", "mt_sort");
                     $tmpKeysArray = array_keys($tmpApCatArray);
                     $tmpKeysArrayLen = count($tmpKeysArray);
                     $xmlOut .= "<apcat" . $j . "_list>\n";
                     for ($i = 0; $i < $tmpKeysArrayLen; $i++) :
                         $xmlOut .= "<apcat" . $j . " id=\"" . $tmpKeysArray[$i] . "\">\n";
                         $xmlOut .= "  <name><![CDATA[" . mcEncode($tmpApCatArray[$tmpKeysArray[$i]]) . "]]></name>\n";
                         $xmlOut .= "</apcat" . $j . ">\n";
                     endfor;
                     $xmlOut .= "</apcat" . $j . "_list>\n";
                  endfor;
      
                  // Participants
                  if ($hq_id != "") :
                     $sqlquery = "SELECT usr_id, usr_firstname, usr_name FROM user WHERE usr_type = '1' AND hq_id = '" . $hq_id . "'";
                     $result = $db->query($sqlquery);
                     if (DB::isError($result)) die ("$PHP_SELF: [$sqlquery]" . $result->getMessage());
                     $xmlOut .= "<possible_participants_list>\n";
                     while ($row = $result->fetch_assoc()):
                           $xmlOut .= "<possible_participant id=\"" . $row["usr_id"] . "\">\n";
                           $xmlOut .= "  <firstname><![CDATA[" . mcEncode($row["usr_firstname"]) . "]]></firstname>\n";
                           $xmlOut .= "  <name><![CDATA[" . mcEncode($row["usr_name"]) . "]]></name>\n";
                           $xmlOut .= "</possible_participant>\n";
                     endwhile;
                     $result->free();
                     $xmlOut .= "</possible_participants_list>\n";
                  endif;
      
                  // Report types
                  $tmpApCatArray = getColVectorFromDB2ArrayByClause("metatype", "mt_value", "mt_type = 'report_type'", "mt_sort", "mt_sort");
                  $tmpKeysArray = array_keys($tmpApCatArray);
                  $tmpKeysArrayLen = count($tmpKeysArray);
                  $xmlOut .= "<reporttype_list>\n";
                  for ($i = 0; $i < $tmpKeysArrayLen; $i++) :
                      $xmlOut .= "<reporttype id=\"" . $tmpKeysArray[$i] . "\">\n";
                      $xmlOut .= "  <name><![CDATA[" . mcEncode($tmpApCatArray[$tmpKeysArray[$i]]) . "]]></name>\n";
                      $xmlOut .= "</reporttype>\n";
                  endfor;
                  $xmlOut .= "</reporttype_list>\n";
               endif;
      
            elseif ($functionName == "calLastWeekNumofYear") :
               $retVal = call_user_func_array($functionName, array($selYear));   // Gets the last calendar week (number) of a specified year
               $xmlOut .= $xmlErrOut;
            elseif ($functionName == "calFirstWeekNumofMonth") :
               $retVal = call_user_func_array($functionName, array($selMonth, $selYear));   // Gets the first calendar week (number) of a specified month and year (calendar week of the 01.01.YYYY)
               $xmlOut .= $xmlErrOut;
            elseif ($functionName == "calFirstDayNumOfMonth") :
               $retVal = call_user_func_array($functionName, array($selMonth, $selYear));   // Gets the first day (number) of a specified month and year
               $xmlOut .= $xmlErrOut;
            elseif ($functionName == "calFirstDayNumOfFirstCalendarWeekOfYear") :
               $retVal = call_user_func_array($functionName, array($selYear));   // Gets the first day (number) of the first calendar week of a specified year, it has to be a "Monday"
               $xmlOut .= $xmlErrOut;
            elseif ($functionName == "calFirstDayNumOfWeek") :
               $retVal = call_user_func_array($functionName, array($selWeek, $selYear));   // Gets the first day (number) of a specified calendar week and year
               $xmlOut .= $xmlErrOut;
            elseif ($functionName == "getDaysWithAppointments") :
               $retVal = call_user_func_array($functionName, array($selYear, $selMonth));   // Gets an array with days of a specified month (and year), where there is at least one appointment per day
               $xmlOut .= $xmlErrOut;
            elseif ($functionName == "modifyIntervalAppointments2SingleDayAppointments") :
               $retVal = call_user_func_array($functionName, array($apArray, $lowerRangeDate, $upperRangeDate));   // Modifies array according to the appointments starting and ending on different days
               $xmlOut .= $xmlErrOut;
            elseif ($functionName == "getAppointmentsOfOneDay" || $functionName == "getAppointmentsOfOneWeek" || $functionName == "getAppointmentsOfOneMonth" || $functionName == "getAppointmentsOfOneYear") :
      
               if ($functionName == "getAppointmentsOfOneDay") :
                  $retVal = call_user_func_array($functionName, array($selYear, $selMonth, $selDay, $csId));   // Gets the appointments of one day
               elseif ($functionName == "getAppointmentsOfOneWeek") :
                  $retVal = call_user_func_array($functionName, array($selWeek, $selYear, $selMonth, $selDay, $csId));   // Gets the appointments of one week
               elseif ($functionName == "getAppointmentsOfOneMonth") :
                  $retVal = call_user_func_array($functionName, array($selYear, $selMonth, $csId));   // Gets the appointments of one month
               elseif ($functionName == "getAppointmentsOfOneYear") :
                  $retVal = call_user_func_array($functionName, array($selYear, $csId));   // Gets the appointments of one year
               endif;
               $retValLen = count($retVal);
               if ($retValLen > 0) :
                  $xmlOut .= "<appointment_list id=\"APL\">\n";
                  $xmlOut .= "<yeardata>\n";
      
                  $tmpRemYear = ""; $tmpRemMonth = ""; $tmpRemDay = "";            
                  $tmpApNewYearBool = false; $tmpApNewMonthBool = false; $tmpApNewDayBool = false;
      
                  for ($i = 0; $i < $retValLen; $i++) :
                      $tmpApYear = substr($retVal[$i][2],0,4);
                      $tmpApMonth = substr($retVal[$i][2],5,2);
                      $tmpApDay = substr($retVal[$i][2],8,2);
      
                      // Closing TAGs
                      if ($tmpRemDay != "" && $tmpRemDay != $tmpApDay) :
                         $xmlOut .= "</appointments>\n";
                         $xmlOut .= "</daydata>\n";
                      endif;
                      if ($tmpRemMonth != "" && $tmpRemMonth != $tmpApMonth) :
                         $xmlOut .= "</days>\n";
                         $xmlOut .= "</monthdata>\n";
                      endif;
                      // if ($tmpRemYear != "" && $tmpRemYear != $tmpApYear) :
                         // ...
                      // endif;
      
                      // Opening TAGs
                      if ($tmpRemYear == "" || $tmpRemYear != $tmpApYear) :
                         $tmpRemYear = $tmpApYear;
                         $xmlOut .= "<year>" . $tmpApYear . "</year>\n";
                      endif;
                      if ($tmpRemMonth == "" || $tmpRemMonth != $tmpApMonth) :
                         $tmpRemMonth = $tmpApMonth;
                         $tmpApNewMonthBool = true;
                         $xmlOut .= "<monthdata>\n";
                         $xmlOut .= "<month>" . $tmpApMonth . "</month>\n";
                         $xmlOut .= "<days>\n";
                      endif;
                      if ($tmpRemDay == "" || $tmpRemDay != $tmpApDay) :
                         $tmpRemDay = $tmpApDay;
                         $tmpApNewDayBool = true;
                         $xmlOut .= "<daydata>\n";
                         $xmlOut .= "<day>" . $tmpApDay . "</day>\n";
                         $xmlOut .= "<appointments>\n";
                      endif;
      
                      $xmlOut .= "<appointment id=\"" . $retVal[$i][0] . "\">\n";
                      $xmlOut .= "<ap_text><![CDATA[" . mcEncode($retVal[$i][1]) . "]]></ap_text>\n";
                      $xmlOut .= "<ap_execdate>" . $retVal[$i][2] . "</ap_execdate>\n";
                      $xmlOut .= "<cmp_id>" . $retVal[$i][3] . "</cmp_id>\n";
                      $xmlOut .= "<cmp_comp><![CDATA[" . mcEncode($retVal[$i][4]) . "]]></cmp_comp>\n";
                      $xmlOut .= "<cmp_comp2><![CDATA[" . mcEncode($retVal[$i][5]) . "]]></cmp_comp2>\n";
                      $xmlOut .= "<cs_eid>" . $retVal[$i][7] . "</cs_eid>\n";
                      $xmlOut .= "<ap_enddate>" . $retVal[$i][8] . "</ap_enddate>\n";
                      $xmlOut .= "<usr_id>" . $retVal[$i][9] . "</usr_id>\n";
                      $xmlOut .= "<usr_firstname><![CDATA[" . mcEncode($retVal[$i][10]) . "]]></usr_firstname>\n";
                      $xmlOut .= "<usr_name><![CDATA[" . mcEncode($retVal[$i][11]) . "]]></usr_name>\n";
                      if (false) :
                         $xmlOut .= "<ap_participants>" . $retVal[$i][12] . "</ap_participants>\n";
                      else :
                         $tmpParticipantsIDs = $retVal[$i][12];
                         // Remove commas at the beginning and at the end if do exist
                         if (substr($tmpParticipantsIDs, 0, 1) == ",") : $tmpParticipantsIDs = substr($tmpParticipantsIDs, 1); endif;
                         if (substr($tmpParticipantsIDs, -1) == ",") : $tmpParticipantsIDs = substr($tmpParticipantsIDs, 0, strlen($tmpParticipantsIDs)-1); endif;
                         $xmlOut .= "<ap_participants>\n";
                         if ($tmpParticipantsIDs != "") :
                            $tmpParticipantsArray = spliti(",", $tmpParticipantsIDs);
                            $tmpParticipantsArrayLen = count($tmpParticipantsArray);
                            for ($j = 0; $j < $tmpParticipantsArrayLen; $j++) :
                                $usrRealName = getFieldValueFromId("user", "usr_id", $tmpParticipantsArray[$j], "usr_name");
                                $usrRealFirstname = getFieldValueFromId("user", "usr_id", $tmpParticipantsArray[$j], "usr_firstname");
                                $xmlOut .= "<ap_participant id=\"" . $tmpParticipantsArray[$j] . "\">\n";
                                $xmlOut .= "  <name><![CDATA[" . mcEncode($usrRealName) . "]]></name>\n";
                                $xmlOut .= "  <firstname><![CDATA[" . mcEncode($usrRealFirstname) . "]]></firstname>\n";
                                $xmlOut .= "</ap_participant>\n";
                            endfor;
                         endif;
                         $xmlOut .= "</ap_participants>\n";
                      endif;
                      $xmlOut .= "<ap_confirmed>" . $retVal[$i][13] . "</ap_confirmed>\n";
                      $xmlOut .= "<cs_usr_name><![CDATA[" . mcEncode($retVal[$i][14]) . "]]></cs_usr_name>\n";
                      $xmlOut .= "<cs_usr_firstname><![CDATA[" . mcEncode($retVal[$i][15]) . "]]></cs_usr_firstname>\n";
                      $xmlOut .= "<cs_usr_phone>" . $retVal[$i][16] . "</cs_usr_phone>\n";
                      $xmlOut .= "<cs_usr_phone2>" . $retVal[$i][17] . "</cs_usr_phone2>\n";
                      $xmlOut .= "<ap_category_1>" . $retVal[$i][18] . "</ap_category_1>\n";
                      $xmlOut .= "<ap_category_2>" . $retVal[$i][19] . "</ap_category_2>\n";
                      $xmlOut .= "<ap_category_3>" . $retVal[$i][20] . "</ap_category_3>\n";
                      $xmlOut .= "<ap_category_4>" . $retVal[$i][21] . "</ap_category_4>\n";      
                      $xmlOut .= "</appointment>\n";
                  endfor;
      
                  // Final closing TAGs
                  if ($tmpApNewDayBool) :
                     $xmlOut .= "</appointments>\n";
                     $xmlOut .= "</daydata>\n";
                  endif;
                  if ($tmpApNewMonthBool) :
                     $xmlOut .= "</days>\n";
                     $xmlOut .= "</monthdata>\n";
                  endif;
      
                  $xmlOut .= "</yeardata>\n";
                  $xmlOut .= "</appointment_list>\n";
               endif;
      
            elseif ($functionName == "getAppointmentHeader") :
               $retVal = call_user_func_array($functionName, array($viewMode, $selYear, $selMonth, $selDay, $selWeek));   // Gets the headline with the current day
               $xmlOut .= $xmlErrOut;
      
            elseif ($functionName == "getAppointmentTitle") :
               $retVal = call_user_func_array($functionName, array($viewMode));   // Gets the title of the output table
               $xmlOut .= $xmlErrOut;
      
            elseif ($functionName == "actionAppointment") :
               $retVal = call_user_func_array($functionName, array($actionMode, $apId, $apText, $execDatetime, $endDatetime, $hq_id, $usr_id, $csId, $usrIdsParticipants, $apCat1, $apCat2, $apCat3, $apCat4));   // DB actions for an appointment
               $xmlOut .= "<appointments>\n";
               $xmlOut .= "<appointment>\n";
               $xmlOut .= "<action>" . $actionMode . "</action>\n";
               $xmlOut .= "<ap_id>" . $apId . "</ap_id>\n";
               $xmlOut .= "<state>" . $retVal . "</state>\n";
               $xmlOut .= "</appointment>\n";
               $xmlOut .= "</appointments>\n";
      
            elseif ($functionName == "getCustomerList") :
               $retVal = call_user_func_array($functionName, array($search));   // Gets the customer list
               $retValLen = count($retVal);
      
               if (!is_array($retVal[0]) && $retVal[0] != "0") :
                  $xmlOut .= $retVal[1] . $retVal[2];
               else :
                  // if ($retValLen > 0) :
                     $xmlOut .= "<customer_list>\n";
                     for ($i = 0; $i < $retValLen; $i++) :
                         $xmlOut .= "<customer id=\"" . $retVal[$i][0] . "\">\n";
                         // $xmlOut .= "  <type>" . $retVal[$i][1] . "</type>\n";
                         $xmlOut .= "  <eid>" . $retVal[$i][2] . "</eid>\n";
                         $xmlOut .= "  <comp><![CDATA[" . mcEncode($retVal[$i][3]) . "]]></comp>\n";
                         $xmlOut .= "  <comp2><![CDATA[" . mcEncode($retVal[$i][4]) . "]]></comp2>\n";
                         $xmlOut .= "  <name><![CDATA[" . mcEncode($retVal[$i][5]) . "]]></name>\n";
                         $xmlOut .= "  <firstname><![CDATA[" . mcEncode($retVal[$i][6]) . "]]></firstname>\n";
                         $xmlOut .= "  <phone>" . $retVal[$i][7] . "</phone>\n";
                         $xmlOut .= "  <phone2>" . $retVal[$i][8] . "</phone2>\n";
                         // $xmlOut .= "  <street><![CDATA[" . mcEncode($retVal[$i][9]) . "]]></street>\n";
                         // $xmlOut .= "  <houseno>" . $retVal[$i][10] . "</houseno>\n";
                         // $xmlOut .= "  <zipcode>" . $retVal[$i][11] . "</zipcode>\n";
                         $xmlOut .= "  <city><![CDATA[" . mcEncode($retVal[$i][12]) . "]]></city>\n";
                         $xmlOut .= "</customer>\n";
                     endfor;
                     $xmlOut .= "</customer_list>\n";
                  // endif;
               endif;
               
            elseif ($functionName == "getCustomerSpecial") :
               $retVal = call_user_func_array($functionName, array($csId));   // Gets a single customer
               $retValLen = count($retVal);
      
               if (!is_array($retVal[0]) && $retVal[0] != "0") :
                  $xmlOut .= $retVal[1] . $retVal[2];
               else :
                  // if ($retValLen > 0) :
                     $xmlOut .= "<customer_special>\n";
                     for ($i = 0; $i < $retValLen; $i++) :
                         $xmlOut .= "<customer id=\"" . $retVal[$i][0] . "\">\n";
                         $xmlOut .= "  <type>" . $retVal[$i][1] . "</type>\n";
                         $xmlOut .= "  <eid>" . $retVal[$i][2] . "</eid>\n";
                         $xmlOut .= "  <comp><![CDATA[" . mcEncode($retVal[$i][3]) . "]]></comp>\n";
                         $xmlOut .= "  <comp2><![CDATA[" . mcEncode($retVal[$i][4]) . "]]></comp2>\n";
                         $xmlOut .= "  <name><![CDATA[" . mcEncode($retVal[$i][5]) . "]]></name>\n";
                         $xmlOut .= "  <firstname><![CDATA[" . mcEncode($retVal[$i][6]) . "]]></firstname>\n";
                         $xmlOut .= "  <phone>" . $retVal[$i][7] . "</phone>\n";
                         $xmlOut .= "  <phone2>" . $retVal[$i][8] . "</phone2>\n";
                         $xmlOut .= "  <street><![CDATA[" . mcEncode($retVal[$i][9]) . "]]></street>\n";
                         $xmlOut .= "  <houseno>" . $retVal[$i][10] . "</houseno>\n";
                         $xmlOut .= "  <zipcode>" . $retVal[$i][11] . "</zipcode>\n";
                         $xmlOut .= "  <city><![CDATA[" . mcEncode($retVal[$i][12]) . "]]></city>\n";
                         $xmlOut .= "</customer>\n";
                     endfor;
                     $xmlOut .= "</customer_special>\n";
                  // endif;
               endif;
      
            elseif ($functionName == "getReportList") :
               $retVal = call_user_func_array($functionName, array($fromDateRange, $toDateRange, $rpObjType, $rpObjId, $rpType));   // Gets the report list
               $retValLen = count($retVal);
      
               if (!is_array($retVal[0]) && $retVal[0] != "0") :
                  $xmlOut .= $retVal[1] . $retVal[2];
               else :
                  // if ($retValLen > 0) :
                     $xmlOut .= "<report_list>\n";
                     for ($i = 0; $i < $retValLen; $i++) :
                         $xmlOut .= "<report id=\"" . $retVal[$i][0] . "\">\n";
                         $xmlOut .= "  <type>" . $retVal[$i][1] . "</type>\n";
                         $xmlOut .= "  <text><![CDATA[" . mcEncode($retVal[$i][2]) . "]]></text>\n";
                         $xmlOut .= "  <confidential>" . $retVal[$i][3] . "</confidential>\n";
                         $xmlOut .= "  <createtime>" . $retVal[$i][4] . "</createtime>\n";
                         $xmlOut .= "  <usrid>" . $retVal[$i][5] . "</usrid>\n";
                         $xmlOut .= "  <name><![CDATA[" . mcEncode($retVal[$i][6]) . "]]></name>\n";
                         $xmlOut .= "  <firstname><![CDATA[" . mcEncode($retVal[$i][7]) . "]]></firstname>\n";
                         $xmlOut .= "  <phone>" . $retVal[$i][8] . "</phone>\n";
                         $xmlOut .= "  <eid>" . $retVal[$i][9] . "</eid>\n";
                         $xmlOut .= "  <comp><![CDATA[" . mcEncode($retVal[$i][10]) . "]]></comp>\n";
                         $xmlOut .= "  <comp2><![CDATA[" . mcEncode($retVal[$i][11]) . "]]></comp2>\n";
                         $xmlOut .= "  <hqid>" . $retVal[$i][12] . "</hqid>\n";
                         $xmlOut .= "  <hqname><![CDATA[" . mcEncode($retVal[$i][13]) . "]]></hqname>\n";
                         $xmlOut .= "</report>\n";
                     endfor;
                     $xmlOut .= "</report_list>\n";
                  // endif;
               endif;
      
            elseif ($functionName == "actionReport") :
               $retVal = call_user_func_array($functionName, array($actionMode, $rpId, $rpType, $rpObjType, $rpObjId, $rpText, $rpConfidential, $hq_id, $usr_id));   // DB actions for a report
               $xmlOut .= "<reports>\n";
               $xmlOut .= "<report>\n";
               $xmlOut .= "<action>" . $actionMode . "</action>\n";
               $xmlOut .= "<rp_id>" . $rpId . "</rp_id>\n";
               $xmlOut .= "<state>" . $retVal . "</state>\n";
               $xmlOut .= "</report>\n";
               $xmlOut .= "</reports>\n";

            elseif ($functionName == "getCsStatistic") :
               $retVal = call_user_func_array($functionName, array($csId, $fromDateRange, $toDateRange));   // Special customer statistic: Business volume 
               $xmlOut .= "<customer_statistic>\n";
               $xmlOut .= "<csid>" . $csId . "</csid>\n";
               $xmlOut .= "<cseid>" . $csEid . "</cseid>\n";
               $xmlOut .= "<statistic_value>" . $retVal . "</statistic_value>\n";
               $xmlOut .= "</customer_statistic>\n";

            else :
               $xmlOut .= "<err_no>103</err_no>\n";
               $xmlOut .= "<err_desc>Function does not exist in API.</err_desc>\n";
            endif;
         else :
            $xmlOut .= "<err_no>102</err_no>\n";
            $xmlOut .= "<err_desc>Specified function does not exist.</err_desc>\n";
         endif;
      else :
         $xmlOut .= "<err_no>101</err_no>\n";
         $xmlOut .= "<err_desc>No function specified.</err_desc>\n";
      endif;
   else :
      $xmlOut .= "<err_no>104</err_no>\n";
      $xmlOut .= "<err_desc>No headquarters defined.</err_desc>\n";
   endif;

   $xmlOut .= "</data>\n";
endif;

echo $xmlOut;
?>
