<?php
/*=======================================================================
 *
 * auth.inc.php
 *
 * Autor: Carsten Annacker, Marc Vollmann
 *
 =======================================================================*/


if (!isset($usr_id)) : $usr_id = ""; endif;
if ($usr_id != -1):

  if (!(isset($check_jb_permanent_flag) && $check_jb_permanent_flag == true))
    session_start();
//  if (!isset($_SESSION['usr_id']) && isset($_POST['usr_id'])) {
//    $_SESSION['usr_id'] = $_POST['usr_id'];
//    $_SESSION['hq_id'] = getOneStmt("SELECT hq_id FROM user WHERE usr_id = " . $_POST['usr_id'], "hq_id");
//    $_SESSION['emp_id'] = getOneStmt("SELECT emp_id FROM employee WHERE usr_id = " . $_POST['usr_id'], "emp_id");
//    $_SESSION['dbname'] = "phoenix";
//    $_SESSION['randomCryptionNumber'] = 0;
//    $_SESSION['chgpwd'] = 0;
//  }
  else
    $_SESSION = array();

//  if (isset($_SESSION['usr_id']))
//    $_SESSION['emp_id'] = getOneStmt("SELECT emp_id FROM employee WHERE usr_id = " . $_SESSION['usr_id'], "emp_id");
  // prevent db change on multiple installations on one server
  $HTTP_SESSION_VARS = !empty($HTTP_SESSION_VARS) ? $HTTP_SESSION_VARS : $_SESSION;
  if (!isset($HTTP_SESSION_VARS['usr_id']) || !isset($HTTP_SESSION_VARS['hq_id'])):
    if (!(isset($check_jb_permanent_flag) && $check_jb_permanent_flag == true)):
      header("Location: ../admin/login.php");
    endif;
  else:
    include_once("../include/glob_defs.inc.php");
    if (substr(phpversion(), 0, 1) >= "5") :
        $currDbName = mcArrIsSet($_SESSION, "dbname");
    else :
        $currDbName = $HTTP_SESSION_VARS['dbname'];
    endif;

    if ($currDbName != $dbname):
//print_r ($HTTP_SESSION_VARS);
//echo "'$dbname'" . "<br>";
      session_unset();
      session_destroy();
      header("Location: ../admin/login.php");
    endif;
  endif;

  if (substr(phpversion(), 0, 1) >= "5") :
     // $usr_id = $_SESSION["usr_id"];
     $usr_id = mcArrIsSet($_SESSION, "usr_id");
     if (!(isset($check_jb_permanent_flag) && $check_jb_permanent_flag == true))
       // $hq_id = $_SESSION["hq_id"];
       $hq_id = mcArrIsSet($_SESSION, "hq_id");
     // $emp_id = $_SESSION["emp_id"];
     $emp_id = mcArrIsSet($_SESSION, "emp_id");
//     if ($emp_id == "")
//       $emp_id = getFieldValueFromId("employee","usr_id",$usr_id,"emp_id");
     // $randomCryptionNumber = $_SESSION['randomCryptionNumber'];
     $randomCryptionNumber = mcArrIsSet($_SESSION, "randomCryptionNumber");
  else :
     $usr_id = $HTTP_SESSION_VARS['usr_id'];
     if (!(isset($check_jb_permanent_flag) && $check_jb_permanent_flag == true))
       $hq_id = $HTTP_SESSION_VARS['hq_id'];
     $emp_id = $HTTP_SESSION_VARS['emp_id'];
     $randomCryptionNumber = $HTTP_SESSION_VARS['randomCryptionNumber'];
  endif;

  // Check for 2FA
  if (!isset($authDoNotCheck2FA)) : 
     $authDoNotCheck2FA = false;
  endif;

if(isset($_SESSION['sso'])) {
   $authDoNotCheck2FA = true;
}

  include_once ("../include/dbglobal.inc.php");
  if (!$authDoNotCheck2FA) :
     $usrTotpSecret = getFieldValueFromId("user", "usr_id", $usr_id, "usr_totp_secret");
     $usrTotpActivated = getFieldValueFromId("user", "usr_id", $usr_id, "usr_totp_activated");
     $usrTotpSessionkey = getFieldValueFromId("user", "usr_id", $usr_id, "usr_totp_sessionkey");
// echo "usrTotpSecret = " . $usrTotpSecret . "<br>";
// echo "usrTotpActivated = " . $usrTotpActivated . "<br>";
// echo "usrTotpSessionkey = " . $usrTotpSessionkey . "<br>";
// echo "SESSION[sessionkey_2fa] = " . $_SESSION["sessionkey_2fa"] . "<br>";
     if ($usrTotpSecret != "" && $usrTotpActivated == "1" && ($usrTotpSessionkey == "" || $_SESSION["sessionkey_2fa"] == "" || $_SESSION["sessionkey_2fa"] != $usrTotpSessionkey)) :
        session_unset();
        session_destroy();
        header("Location: ../admin/login.php");
     endif;
  endif;

  // Load HQ specific constants
  if (!isset($noExecGlobDefs) || $noExecGlobDefs != "1") :
     if (!isset($hq_id_job)) : $hq_id_job = ""; endif;
     defineGlobalParameters($hq_id_job);
  endif;
  
  if ($emp_id != "" && $hq_id != "") :
     // Get employee settings according to the system language
     $constLanguageSelected = getParameterValue($emp_id, "SYSTEM_LANGUAGE_DEFAULT", $hq_id);
     if ($constLanguageSelected != "") :
        $languageSelected = $constLanguageSelected;
     endif;
  endif;
  
  // Init associative array for accessing scripts
  $usrAccessArray = array();
  
  // Get global mandator ID
  $md_id = getFieldValueFromId("mandatorheadquarters", "hq_id", $hq_id, "md_id");
  if ($md_id == "" || !is_numeric($md_id)) : die(); endif;   // Has to exist
  
  // Init parameter for the global master right ("menu right") of the current employee and the current script
  // The value will be associated in function "authCheckEmployeeRights (....)"
  $empGlobalMasterRights = array();

  if (!(isset($check_jb_permanent_flag) && $check_jb_permanent_flag == true)):
    // Check whether a new password must be chosen
    $tries = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'usr' AND gdc_obj_id = " . $usr_id . " AND gdc_gen_fieldname = 'set_new_pwd'" );
    if ($tries != "" && $_SESSION['chgpwd'] == '1'):
      header("Location: ../admin/chgpwd.php");  
    endif;
  endif;
endif;


// Redirection to a special page
function gotoReferer($refererPage = "") {
  if ($refererPage == "") : $refererPage = "../admin/start.php"; endif;
  if ($refererPage == "1") : $refererPage = "../admin/start.php"; endif;
  if (!headers_sent()) :
     header("Location: " . $refererPage);
  else :
     exit('<meta http-equiv="refresh" content="0; url=' . urldecode($refererPage) . '"/>');
  endif;
  die();
}

// Checks the authentication of a special employee (ONLY customer-employee) logged in according
// to the existence of his/her customer- and costcenter-entry
// $hq_id       : Id of the headquarter the customer is associated to
// $usr_id      : Id of the user unique to the employee-id (stored in cookie)
// $emp_id      : Id of the employee (stored in cookie)
// $csc_id      : Id of the costcenter the employee is associated
// $emp_id      : Id of the employee (stored in cookie)
// $csc_id_act  : Id of the current costcenter to be in the subtree-path of the individual "root"-costcenter of the employee
function authCheck($hq_id,$usr_id,$emp_id,$csc_id,$cs_id,$csc_id_act = "",$referer = "") {
   $hasAccess = FALSE;	

   // Check hq_id and usr_id
   if ($hq_id == getFieldValueFromId("user","usr_id",$usr_id,"hq_id")) :

      // Check usr_id and emp_id
      if ($usr_id == getFieldValueFromId("employee","emp_id",$emp_id,"usr_id")) :

         // Check existence of customer- and costcenter-parameters
         if ($emp_id != "" && $csc_id != "" && $cs_id != "") :
            // Get the "root"-costcenter of the employee   

            $cscId = getFieldValueFromId("employee","emp_id",$emp_id,"csc_id");
            // Check the value with the parameter

            if ($cscId != "" && $cscId == $csc_id) :
               // Get fields of the costcenter
               $tmpFields = getFieldsValueFromId("costcenter","csc_id",$csc_id,array("cs_id","csc_path","csc_name"));
               $csId = $tmpFields[0];
               $cscPath = $tmpFields[1];
               $cscName = $tmpFields[2];

               // Check customer-entry
               if ($csId != "" && $csId == $cs_id) :

                  if ($csc_id_act != "") :         
                     $tmpFields = getFieldsValueFromId("costcenter","csc_id",$csc_id_act,array("cs_id","csc_path","csc_name"));
                     $csIdAct = $tmpFields[0];
                     $cscPathAct = $tmpFields[1];
                     $cscNameAct = $tmpFields[2];

                     // Check for the actual costcenter being a child of the "root"-costcenter
                     $existsInPath = strpos($cscPathAct, $cscName);

                     if ($csIdAct == $csId && ($csc_id == $csc_id_act || !($existsInPath === FALSE))) :
                        // Authentication ok
                        $hasAccess = TRUE;
                     endif;
                  endif;
               endif;
            endif;
         endif;
      endif;
   endif;

   if (!$hasAccess && $referer != "") :
      gotoReferer();
   endif;

   return $hasAccess;
}

// Checks the authentication of a special employee (ONLY customer-employee) logged in according
// to the existence of his/her customer- and costcenter-entry
// Compatible to authCheck(...)
function authCheckCS($hq_id,$usr_id,$emp_id,$csc_id,$cs_id,$csc_id_act = "",$referer = "") {
	 return authCheck($hq_id,$usr_id,$emp_id,$csc_id,$cs_id,$csc_id_act,$referer);
}

// Checks the authentication of a special employee of a headquarter logged in
// $emp_id  : Id of the employee (stored in cookie)
function authCheckHQ($currentHqId,$usr_id,$emp_id,$referer = "") {
   $hasAccess = FALSE;

   // Check user ID
   if ($usr_id != "" && is_numeric($usr_id) && $usr_id > 0) :

      // Check employee ID
      if ($emp_id != "" && is_numeric($emp_id) && $emp_id > 0) :

         // Check usr_id and emp_id associated correctly
         $tmpUsrId = getFieldValueFromId("employee","emp_id",$emp_id,"usr_id");
         if ($tmpUsrId == $usr_id) :

            // Checks user-type for being a headquarter
            if (getFieldValueFromId("user","usr_id",$usr_id,"usr_type") == "1") :

               // Get original hq_id of the usr_id
               $usrHqId = getFieldValueFromId("user","usr_id",$usr_id,"hq_id");

               // Check employee state to set the rights
               $empHasMultipleHqAccess = false;
               if ($currentHqId != $usrHqId) :
                  $empHqList = getParameterValue("0", "HEADQUARTERS_MULTIPLE_ACCESS_EMPLOYEES", "0");
                  $empHqList = str_replace("|", "-,-", $empHqList);
                  $empHqArray = spliti("-,-",$empHqList);
                  $empHqArrayLen = count($empHqArray);
                  for ($i = 0; $i < $empHqArrayLen; $i++) :
                      if ($emp_id == $empHqArray[$i]) :
                         $empHasMultipleHqAccess = true;
                      endif;
                  endfor;
               endif;

               if ($currentHqId == $usrHqId || $empHasMultipleHqAccess) :
                  // Authentication ok
                  $hasAccess = TRUE;
               endif;
            endif;
         endif;
      endif;
   endif;

   if (!$hasAccess && $referer != "") :
      gotoReferer();
   endif;

   return $hasAccess;
}

// Checks the authentication of a special courier/carrier logged in
function authCheckCR($currentHqId,$usr_id,$referer = "") {
   $hasAccess = FALSE;
   // Check user ID
   if ($usr_id != "" && is_numeric($usr_id) && $usr_id > 0) :
      // Checks user-type for being a headquarter
      if (getFieldValueFromId("user","usr_id",$usr_id,"usr_type") == "3") :
         // Get original hq_id of the usr_id
         $usrHqId = getFieldValueFromId("user","usr_id",$usr_id,"hq_id");
         if ($currentHqId == $usrHqId) :
            // Authentication ok
            $hasAccess = TRUE;
         endif;
      endif;
   endif;
   if (!$hasAccess && $referer != "") :
      gotoReferer();
   endif;
   return $hasAccess;
}


function authCheckForAccess($hqId, $usrId, $empId = "", $referer = "", $customerId = "", $cscIdRoot = "", $cscIdActual = "") {
	global $userType, $userTypeName, $usrAccessArray;
	$hasAccess = FALSE;

  // Select user-type for mode of security check 
  $userType = getFieldValueFromId("user","usr_id",$usrId,"usr_type");
  $userTypeName = getUserTypeName($userType);

  if ($userTypeName != "" && $usrAccessArray[$userTypeName] == "1") :
     if ($userTypeName == "cs" && $customerId != "" && $cscIdRoot != "" && $cscIdActual != "" && authCheckCS($hqId,$usrId,$empId,$cscIdRoot,$customerId,$cscIdActual)) :
        $hasAccess = TRUE;
     endif;
     if ($userTypeName == "cr" && authCheckCR($hqId,$usrId)) :
        $hasAccess = TRUE;
     endif;
     if ($userTypeName == "hq" && authCheckHQ($hqId,$usrId,$empId)) :
        $hasAccess = TRUE;
     endif;
  endif;

  // Check authentication verifying emmployee an his/her costcenter- and customer-association
  if (!$hasAccess && $referer != "") :
     gotoReferer("1");
  endif;
  return $hasAccess; 
}


// Checks the authentication of a special employee of a headquarter logged in
// $emp_id  : Id of the employee (stored in cookie)
function authCheckEmployeeRights($emp_id, $menuModeId, $referer = "") {
	global $empGlobalMasterRights;
  $hasAccess = FALSE;	

  // Get the rights of the employee logged in
  $empRights = getRights($emp_id);
  if (substr($empRights,$menuModeId,1) == "1") :
     // Authentication ok
     $hasAccess = TRUE;
  endif;
  
  if (!$hasAccess && $referer != "") :
     gotoReferer();
  endif;

  // Important to set because of potential access restrictions regarding to create headquarters checkboxes
  // Value has to be set if "$referer" is set! This is to decide a script will be executed.
  if ($referer != "") :
     $empGlobalMasterRights[] = $menuModeId + 1;   // "Plus 1" because the array begins with "0" and the database begins with "1"
  endif;

  return $hasAccess;
}
?>
