<?php

/*===============================================*\
|| ############################################# ||
|| # JAKWEB.CH / Version 2.1.4                 # ||
|| # ----------------------------------------- # ||
|| # Copyright 2023 JAKWEB All Rights Reserved # ||
|| ############################################# ||
\*===============================================*/

// prevent direct php access
define('JAK_PREVENT_ACCESS', 1);

if (!file_exists('config.php')) die('[index.php] config.php not exist');
require_once 'config.php';

// Language
$BT_LANGUAGE = JAK_LANG;

// Get the language file if different from settings
if (!$maincmspage && isset($widgetlang) && !empty($widgetlang) && $widgetlang != JAK_LANG) $BT_LANGUAGE = $widgetlang;

// Import the language file
if ($BT_LANGUAGE && file_exists(APP_PATH.'lang/'.strtolower($BT_LANGUAGE).'.php')) {
    include_once(APP_PATH.'lang/'.strtolower($BT_LANGUAGE).'.php');
} else {
    include_once(APP_PATH.'lang/'.JAK_LANG.'.php');
}

// If Referer Zero go to the session url
if (!isset($_SERVER['HTTP_REFERER'])) {
  if (isset($_SESSION['jaklastURL'])) {
      $_SERVER['HTTP_REFERER'] = $_SESSION['jaklastURL'];
    } else {
      if (defined('BASE_URL')) $_SERVER['HTTP_REFERER'] = BASE_URL;
    }
}

// Get the redirect into a sessions for better login handler
if ($page && $page != '404' && $page != 'js' && !in_array($page1, array("del","status"))) $_SESSION['LCRedirect'] = $_SERVER['REQUEST_URI'];

// Lang and pages file for template
define('JAK_SITELANG', $BT_LANGUAGE);

// Assign Pages to template
define('JAK_PAGINATE_ADMIN', 0);

// Define the avatarpath in the settings
define('JAK_FILEPATH_BASE', BASE_URL.JAK_FILES_DIRECTORY);

// Define the real request
$realrequest = substr($getURL->jakRealrequest(), 1);
define('JAK_PARSE_REQUEST', $realrequest);

// Check if the ip or range is blocked, if so redirect to offline page with a message
$USR_IP_BLOCKED = false;
if (!defined("JAK_IP_BLOCK")) jak_redirect(SIGN_UP_URL);
if (JAK_IP_BLOCK) {
  $blockedips = explode(',', JAK_IP_BLOCK);
  // Do we have a range
  if (is_array($blockedips)) foreach ($blockedips as $bip) {
    $blockedrange = explode(':', $bip);
    
    if (is_array($blockedrange)) {
    
      $network=ip2long($blockedrange[0]);
      $mask=ip2long($blockedrange[1]);
      $remote=ip2long($ipa);
      
      if (($remote & $mask) == $network) {
          $USR_IP_BLOCKED = $jkl['e11'];
          $page = "banned";
      }  
    }
  }
  // Now let's check if we have another match
  if (in_array($ipa, $blockedips)) {
    $USR_IP_BLOCKED = $jkl['e11'];
    $page = "banned";
  }
}

// We have to reset the departments for the logged in operators or clients
if (JAK_USERISLOGGED) {
  $new_chat_dep = array();
  if (JAK_USERID != 0 && $jakuser->getVar("chat_dep") != 0) {

    if (isset($HD_DEPARTMENTS) && !empty($HD_DEPARTMENTS)) foreach ($HD_DEPARTMENTS as $d) {
        if (in_array($d["id"], explode(",", $jakuser->getVar("chat_dep")))) {
          $new_chat_dep[] = $d;
        }
      }

  } elseif (JAK_CLIENTID != 0 && $jakclient->getVar("chat_dep") != 0) {

    if (isset($HD_DEPARTMENTS) && !empty($HD_DEPARTMENTS)) foreach ($HD_DEPARTMENTS as $d) {
        if (in_array($d["id"], explode(",", $jakclient->getVar("chat_dep")))) {
          $new_chat_dep[] = $d;
        }
      }
  }

  if (isset($new_chat_dep) && !empty($new_chat_dep)) {
    reset($HD_DEPARTMENTS);
      $HD_DEPARTMENTS = $new_chat_dep;
  }
}

// Now get the available departments
$online_op = false;
if (JAK_HOLIDAY_MODE != 0) {
  $online_op = false;
} else {
  if (isset($widgetid) && $widgetid != 0) $online_op = online_operators($opcacheid, $HD_DEPARTMENTS, $jakwidget[$widgetid]['depid'], $jakwidget[$widgetid]['singleopid']);
}

// We need to check the CMS
$jakpages = $jakdb->select("cms_pages", ["id", "title", "url_slug", "dorder", "showheader", "ishome", "showfooter", "access"], ["AND" => ["opid" => $_SESSION['opid'], "active" => 1, "lang" => JAK_SITELANG], "ORDER" => ["dorder" => "ASC"]]);

// Set the check page to 0
$JAK_CHECK_PAGE = 0;

  // Logout
  if ($page == 'logout') {
        $checkp = 1;

        // Get the user Agent, one more time
        $valid_agent = filter_var($_SERVER['HTTP_USER_AGENT'], FILTER_SANITIZE_FULL_SPECIAL_CHARS);

        // Get the business name
        $businessname = $_SESSION['business'];

        if (JAK_CLIENTID) {

          // Write the log file each time someone login after to show success
            JAK_base::jakWhatslog('', $opcacheid, 0, JAK_CLIENTID, 6, 0, (isset($_COOKIE['WIOgeoData']) ? $_COOKIE['WIOgeoData'] : ''), $jakclient->getVar("email"), $_SERVER['REQUEST_URI'], $ipa, $valid_agent);

            $jakclientlogin->jakLogout(JAK_CLIENTID);
            $_SESSION["successmsg"] = $jkl['s'];
        } elseif (JAK_USERID) {

          // Write the log file each time someone login after to show success
            JAK_base::jakWhatslog('', $opcacheid, JAK_USERID, 0, 3, 0, (isset($_COOKIE['WIOgeoData']) ? $_COOKIE['WIOgeoData'] : ''), $jakuser->getVar("username"), $_SERVER['REQUEST_URI'], $ipa, $valid_agent);

            $jakuserlogin->jakLogout(JAK_USERID);
            $_SESSION["successmsg"] = $jkl['s'];
        }

        // Set the session again
        $_SESSION['opid'] = $opcacheid;
        $_SESSION['business'] = $businessname;

        jak_redirect(BASE_URL);
    }

  // forgot password
    if ($page == 'forgot-password') {
    
      if (JAK_CLIENTID || !is_numeric($page1) || !$jakclientlogin->jakForgotactive($page1)) jak_redirect(BASE_URL);
      
      // select user
        $row = $jakdb->get("clients", ["id", "name", "email"], ["forgot" => $page1]);
      
      // create new password
      $password = jak_password_creator();
      $passcrypt = hash_hmac('sha256', $password, DB_PASS_HASH);
      
      // update table
        $result = $jakdb->update("clients", ["password" => $passcrypt, "forgot" => 0], ["id" => $row['id']]);
      
      if (!$result) {
        
        $_SESSION["errormsg"] = $jkl["not"];
        // redirect back to home
        jak_redirect(BASE_URL);
           
      } else {

        // Ok, we send the email // email address, cc email address, reply to, subject, message, attachment
          if (jak_send_email($row["email"], "", "", JAK_TITLE.' - '.$jkl['hd25'], sprintf($jkl['hd27'], $row["name"], $password, JAK_TITLE), "")) {
            $_SESSION["infomsg"] = $jkl["hd26"];
          jak_redirect(BASE_URL);
        }
        
      }
      
      $_SESSION["errormsg"] = $jkl["sql"];
      jak_redirect(BASE_URL);
    }
  
  // Link we need a redirect
  if ($page == 'link') {
    $_SESSION['islinked'] = true;
    create_session_id($opcacheid, $jakwidget[$widgetid]['depid'], $jakwidget[$widgetid]['opid'], $ipa);
    jak_redirect(JAK_rewrite::jakParseurl('lc', 'open', $widgetid, $widgetlang));
  }
  // The chat class
  if ($page == 'lc') {
    require_once 'lc.php';
    $JAK_CHECK_PAGE = 1;
    $PAGE_SHOWTITLE = 1;
  }
  // Group Chat
  if ($page == 'groupchat') {
    require_once 'groupchat.php';
    $JAK_CHECK_PAGE = 1;
    $PAGE_SHOWTITLE = 1;
  }
  // API Request
  if ($page == 'api') {
    require_once 'api.php';
    $JAK_CHECK_PAGE = 1;
    $PAGE_SHOWTITLE = 1;
  }

  if ($JAK_CHECK_PAGE == 0) {
       // Include all the pages
    foreach($jakpages as $ca) {
          
      if ((empty($page) && $ca['ishome'] == 1) || ($page == $ca['url_slug']) || JAK_HOLIDAY_MODE == 1 || $page == '404' || $page == 'banned') {
          
        // What information should we load
        if (JAK_HOLIDAY_MODE == 1 && JAK_OFFLINE_CMS_PAGE != 0) {
          $pageid = JAK_OFFLINE_CMS_PAGE;
        } elseif ($ca['id'] > 0) {
          $pageid = $ca['id'];
        }
          
        // Include the page php file  
        require_once 'template/'.JAK_FRONT_TEMPLATE.'/index.php';
        $JAK_CHECK_PAGE = 1;
        break;
      }
    }
  }

// if page not found
if ($JAK_CHECK_PAGE == 0) jak_redirect(JAK_rewrite::jakParseurl('404'));

// Reset success and errors session for next use
unset($_SESSION["successmsg"]);
unset($_SESSION["errormsg"]);
unset($_SESSION["infomsg"]);
?>
