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


include_once ("../include/mcglobal.inc.php");
include_once ("../include/inc_parseXML.inc.php");
include_once ("../include/inc_filters.inc.php");


// Write logdata into log file
$currentTime = getDateTime("0");
$currentDate = getDateTime("3");

$debug = false;
$debugOut = "";

// $filterReq = file_get_contents('php://input');

// Check HTTP-Parameters
getSecHttpVars("1",array("f_act", "filterReq", "selectedLanguage"));

if ($filterReq == "") :
   if (isset($argv[1])) : 
      $filterReq = $argv[1];
   endif;
endif;

function filterRequestLogFile ($msg, $logLevel = 0) {
  XMLRequestLogFile($msg, $logLevel, $logFile = "filterReq.log");
}


$filterReq = urldecode($filterReq);
$filterReq = str_replace("'", "", $filterReq);
$filterReq = mcEncode($filterReq);
$filterReq = str_replace("'", "", $filterReq);
echo $filterReq . "<br><br>";

filterRequestLogFile($currentTime);
filterRequestLogFile($filterReq);


if ($selectedLanguage == "" || !is_numeric($selectedLanguage)) : $selectedLanguage = "1"; endif;  // Default in English
$languageSelected = $selectedLanguage;

getLanguage(__FILE__);
getCurrentScript(__FILE__);

$err = array();
$filterResponse = "";
$xmlFilter = "";


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

// *** Parse request ***
$filterArray = xml2array($filterReq);
if ($debug) :
   print_r($filterArray); echo "<br><br><br>";
endif;

// *** Convert result array to usable parameters ***
// Authentication data
$sessionId      = convertSpecial($filterArray["xml"]["filter"]["auth"]["session_id"]);
$passPhrase     = convertSpecial($filterArray["xml"]["filter"]["auth"]["passphrase"]);

$debugOut .= "sessionId: " . $sessionId . "<br>\n";
$debugOut .= "passphrase: " . $passphrase . "<br>\n";

if (checkRequestAuthenticationData2($sessionId, $passPhrase)) :

   $debugOut .= "Authentication okay!<br><br>\n";


   // Get job or filter data
   $operation  = convertSpecial($filterArray["xml"]["filter"]["operation"]);
   $debugOn    = convertSpecial($filterArray["xml"]["filter"]["debug_on"]);

   $debugOut .= "operation: " . $operation . "<br>\n";


   // Init
   $currentTimestamp = getDateTime("0");
   $currentDay = getDateTime("3");   // "Y-m-d"
   $currentTime = getDateTime("4");  // Current time ("H:i:s")
   $currYear = getDateTime("year");  // Current year

   if (!$debug && ($debugOn == "ON" || $debugOn == "YES")) :
      $debug = true;
   endif;

   if ($operation == "SET") :

      // TO BE DONE!


   else :

      $crfArr = array();

      $filter_no = "";
      $filter_name = "";
      $sqlquery = "SELECT crf_id, crf_type, crf_short, crf_text, crf_status, vht_id FROM phoenix.courierfilter ORDER BY crf_id";
      $result = $db->query($sqlquery);
      if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
      $count = 0;
      while ($row = $result->fetch_assoc()):
            $crfArr[$count] = $row;
            $count++;
      endwhile;
      $result->free();
      $crfArrLen = count($crfArr);

      // Check for ERRORS
      if ($crfArrLen > 0) :
         // Filters found => Generate output
         $xmlFilter .= "<filters>";
         for ($i = 0; $i < $crfArrLen; $i++) :
             $xmlFilter .= "<filter>";
             $xmlFilter .= "<crf_id><![CDATA["     . mcEncode($crfArr[$i]["crf_id"])     . "]]></crf_id>";
             $xmlFilter .= "<crf_type><![CDATA["   . mcEncode($crfArr[$i]["crf_type"])   . "]]></crf_type>";
             $xmlFilter .= "<crf_short><![CDATA["  . mcEncode($crfArr[$i]["crf_short"])  . "]]></crf_short>";
             $xmlFilter .= "<crf_text><![CDATA["   . mcEncode($crfArr[$i]["crf_text"])   . "]]></crf_text>";
             $xmlFilter .= "<crf_status><![CDATA[" . mcEncode($crfArr[$i]["crf_status"]) . "]]></crf_status>";
             $xmlFilter .= "<vht_id><![CDATA["     . mcEncode($crfArr[$i]["vht_id"])     . "]]></vht_id>";
             $xmlFilter .= "</filter>";
         endfor;
         $xmlFilter .= "</filters>";
      else :
         // $err[] = array("102", getLngt("Keine Filter im Suchergebnis!"));
      endif;
      $debugOut .= "<br><br>xmlFilter: " . $xmlFilter . "<br>\n";
   endif;

else :
  // Authentication data not ok
  $err[] = array("101", getLngt("Die Authentifizierungsdaten sind nicht in Ordnung."));
endif;
// print_r($err);

// Check existence of at least one error
$errLen = count($err);

// Output
$filterResponse .= "<xml>";   
if ($errLen > 0) :
   filterRequestLogFile("ERRORS", 1);
   $filterResponse .= "<state>NOT OK</state>";
   $filterResponse .= "<errors>";
   for ($i = 0; $i < $errLen; $i++) :
       $filterResponse .= "<error>";
       $filterResponse .= "<err_no>" . $err[$i][0] . "</err_no>";
       $filterResponse .= "<err_desc><![CDATA[" . mcEncode($err[$i][1]) . "]]></err_desc>";
       $filterResponse .= "</error>";
       if ($debug) :
          $filterResponse .= "<debug>" . $debugOut . "</debug>";
       endif;
       filterRequestLogFile($err[$i][0] . " : " . mcEncode($err[$i][1]), 1);
   endfor;
   $filterResponse .= "</errors>";
else :
   $filterResponse .= "<state>OK</state>" . $xmlFilter;
   if ($debug) :
      $filterResponse .= "<debug>" . $debugOut . "</debug>";
   endif;
endif;
$filterResponse .= "</xml>";

// Log entries
filterRequestLogFile($filterResponse);    // Write response into log
filterRequestLogFile("___________________________________________________________________________________");

// Return output
echo $filterResponse;



/*
// REQUEST
<xml>
  <filter>                                                    // Global filters (equipment).
    <auth>                                                    // Request authentication
      <session_id>[mdtr]</session_id>                         // Session-ID [mandatory]
      <passphrase>[mdtr]</passphrase>                         // Dynamic one-way-encryption passphrase
    </auth>                                                   

    <debug_on>...</debug_on>                                  // Activates debug output ("ON" or "YES")

    <operation>GET|SET</operation>                            // Operation (GET(s all filters) or SET filter(s), default is "GET" if emty tag)

                                                              // NEXT TAGS NEEDED FOR OPERATION "SET" ONLY (!!!!)
    <crf_id>....</crf_id>                                     // ID of the filter (UPDATE if ID does exist AND mnemonic (crf_short) is identically OR INSERT, if unique mnemonic is not empty and does not exist)
    <crf_type>....</crf_type>                                 // Type of the filter ("0" = empty = default = vehicle filter, "1" = contractor filter)
    <crf_short>....</crf_short>                               // Mnemonic (unique)
    <crf_text>....</crf_text>                                 // Description
    <crf_status>....</crf_status>                             // State of the filter ("1" = mandatory, "0" = optional)
    <vht_id>....</vht_id>                                     // Vehicle type (minimal value to be used, "0" = empty = default)
  </filter>
</xml>


// RESPONSE for GET
<xml>
  <state>OK</state>

  <filters>
    <filter>
      <crf_id>....</crf_id>                                   // ID of the filter
      <crf_type>....</crf_type>                               // Type of the filter ("0" = empty = default = vehicle filter, "1" = contractor filter)
      <crf_short>....</crf_short>                             // Mnemonic
      <crf_text>....</crf_text>                               // Description
      <crf_status>....</crf_status>                           // State of the filter ("1" = mandatory, "0" = optional)
      <vht_id>....</vht_id>                                   // Vehicle type (minimal value to be used, "0" = empty = default)
    </filter>
  </filters>
</xml>


// RESPONSE for SET
<xml>
  <state>OK</state>

  <filter>
    <crf_id>....</crf_id>                                     // ID of the filter (Empty = default = INSERT, if unique mnemonic is not empty and does not exist)
    <crf_short>....</crf_short>                               // Mnemonic (unique)
    <crf_text>....</crf_text>                                 // Description
    <crf_status>....</crf_status>                             // State of the filter ("1" = mandatory, "0" = optional)
    <vht_id>....</vht_id>                                     // Vehicle type (minimal value to be used, "0" = empty = default)
  </filter>
</xml>
*/
?>

