<?php

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

// Check if the file is accessed only via index.php if not stop the script from running
if (!defined('JAK_PREVENT_ACCESS')) die('No direct access!');

// Get the stuff for the CMS
include_once 'functions_cms.php';

// Get the important database table
$jaktable = 'cms_pages';
$jaktable1 = 'translations';

// Get the referrer URL
$referrer = JAK_rewrite::jakParseurl($page, $page1, $page2);

// Some reset
$widgethtml = $slideimg = $JAK_PAGINATE = '';
$similarart = array();

// Get the client browser
$ua = new Browser();

// Is a robot just die
if ($ua->isRobot()) die(json_encode(array('status' => false, 'error' => "Robots do not need a live chat.")));
// Is mobile
if ($ua->isMobile()) {
  $_SESSION["clientismobile"] = true;
} else {
  unset($_SESSION["clientismobile"]);
}

// Set time on site in session so we can fire the pro active at the right time
if (!isset($_SESSION['jkchatontime'])) $_SESSION['jkchatontime'] = time();

// Set the cookie
if (!isset($_COOKIE["activation"])) JAK_base::jakCookie('activation', 'visited', JAK_COOKIE_TIME, JAK_COOKIE_PATH);

if (isset($_COOKIE["activation"]) || session_id()) {

  if (!isset($_SESSION['rlbid'])) {

    if (isset($_COOKIE['rlbid'])){
      $_SESSION['rlbid'] = $_COOKIE['rlbid'];
    } else {
      $salt = rand(100, 99999);
      $rlbid = $salt.time();
      JAK_base::jakCookie('rlbid', $rlbid, 31536000, JAK_COOKIE_PATH);
      $_SESSION['rlbid'] = $rlbid;
    }

  }

  // Now get the hits and referrer into sessions
  $_SESSION['jkchathits'] = (isset($_SESSION['jkchathits']) ? $_SESSION['jkchathits'] + 1 : 1);
  $_SESSION['jkchatref'] = $referrer;

  $btstat = $jakdb->update("buttonstats", ["opid" => $_SESSION['opid'], "clientid" => JAK_CLIENTID, "hits[+]" => 1, "referrer" => $referrer, "ip" => $ipa, "lasttime" => $jakdb->raw("NOW()")], ["session" => $_SESSION['rlbid']]);

  // Update database first to see who is online!
  if (!$btstat->rowCount()) {

    // get client information
    $clientsystem = $ua->getPlatform().' - '.$ua->getBrowser(). " " . $ua->getVersion();

    // Country Stuff
    $country_name = 'Disabled';
    $country_code = 'xx';
    $city = 'Disabled';
    $country_lng = $country_lat = '';

    // A "geoData" cookie has been previously set by the script, so we will use it
    if (isset($_COOKIE['WIOgeoData'])) {
      // Always escape any user input, including cookies:
      list($city, $country_name, $country_code, $country_lat, $country_lng) = explode('|', strip_tags(base64_decode($_COOKIE['WIOgeoData'])));
    } else {

      // Now let's check if the ip is ipv4
      if (JAK_SHOW_IPS && $ipa && !$ua->isRobot()) {

        $ipc = curl_init();
        curl_setopt($ipc, CURLOPT_URL, "https://ipgeo.jakweb.ch/api/".$ipa);
        curl_setopt($ipc, CURLOPT_HEADER, false);
        curl_setopt($ipc, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ipc);
        curl_close($ipc);

        $getinfo = json_decode($response, true);

        if (isset($getinfo) && !empty($getinfo)) {

          $country_name = ucwords(strtolower(filter_var($getinfo["country"]["name"], FILTER_SANITIZE_FULL_SPECIAL_CHARS)));
          $country_code = strtolower(filter_var($getinfo["country"]["code"], FILTER_SANITIZE_FULL_SPECIAL_CHARS));
          $city = filter_var($getinfo["city"], FILTER_SANITIZE_FULL_SPECIAL_CHARS);
          $country_lng = filter_var($getinfo["location"]["longitude"], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
          $country_lat = filter_var($getinfo["location"]["latitude"], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);

        }

      }

      // Setting a cookie with the data, which is set to expire in a week:
      JAK_base::jakCookie('WIOgeoData', base64_encode($city.'|'.$country_name.'|'.$country_code.'|'.$country_lat.'|'.$country_lng), 604800, JAK_COOKIE_PATH);

    }

    $jakdb->insert("buttonstats", ["opid" => $_SESSION['opid'], "depid" => 0, "opid" => 0, "clientid" => JAK_CLIENTID, "referrer" => $referrer, "firstreferrer" => $referrer, "agent" => $clientsystem, "hits" => 1, "ip" => $ipa, "country" => $country_name, "countrycode" => $country_code, "latitude" => $country_lat, "longitude" => $country_lng, "session" => $_SESSION["rlbid"], "time" => $jakdb->raw("NOW()"), "lasttime" => $jakdb->raw("NOW()")]);

  }

  if (isset($_SESSION['jrc_userid']) && isset($_SESSION['convid'])) {

    // insert new referrer
    $jakdb->insert("transcript", ["name" => $jkl["g56"], "message" => $jkl["g55"].$referrer, "convid" => $_SESSION['convid'], "time" => $jakdb->raw("NOW()"), "class" => "notice", "plevel" => 2]);

    $jakdb->update("checkstatus", ["newo" => 1, "typec" => 0], ["convid" => $_SESSION['convid']]);
  }

  // We have already updated certain things
  if (!isset($_SESSION['jkwio']) || $_SESSION['jkwio'] == false) $_SESSION['jkwio'] = true;
}

// Get the database stuff
$JAK_CMS_PAGE = $jakdb->get($jaktable, "*", ["AND" => ["id" => $pageid, "opid" => $_SESSION['opid'], "lang" => $BT_LANGUAGE]]);

// Errors in Array
$errors = array();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  $jkp = $_POST;

  if (isset($_POST['send_email'])) {

  if (empty($jkp['gname']) || strlen(trim($jkp['gname'])) <= 2) {
    $errors['gname'] = $jkl['e'];
  }

  if (JAK_EMAIL_BLOCK) {
    $blockede = explode(',', JAK_EMAIL_BLOCK);
    if (in_array($jkp['gemail'], $blockede) || in_array(strrchr($jkp['gemail'], "@"), $blockede)) {
      $errors['gemail'] = $jkl['e10'];
    }
  }

  if (!empty(JAK_DSGVO_CONTACT)) {
    if (!isset($jkp['gdsgvo'])) {
        $errors['gdsgvo'] = $jkl['e19'];
    }
  }

    if ($jkp['gemail'] == '' || !filter_var($jkp['gemail'], FILTER_VALIDATE_EMAIL)) {
        $errors['gemail'] = $jkl['e1'];
    }

    if (empty($jkp['gmessage']) || strlen(trim($jkp['gmessage'])) <= 2) {
        $errors['gmessage'] = $jkl['e2'];
    }

    // ReCaptcha Verify if key exist.
      if (!empty(JAK_RECAP_CLIENT) && !empty(JAK_RECAP_SERVER)) {
          $rcurl = 'https://www.google.com/recaptcha/api/siteverify';
          $rcdata = array(
              'secret' => JAK_RECAP_SERVER,
              'response' => $_POST["g-recaptcha-response"]
          );
          $rcoptions = array(
              'http' => array (
                  'method' => 'POST',
                  'content' => http_build_query($rcdata)
              )
          );
          $rccontext  = stream_context_create($rcoptions);
          $rcverify = file_get_contents($rcurl, false, $rccontext);
          $captcha_success = json_decode($rcverify);
          if ($captcha_success->success == false) {
              $errorsA['recaptcha'] = $jkl['e12'].'<br>';
          }
      }

    // And we check the custom fields
     $formfields = $jakdb->select('customfields', ["title", "val_slug"], ["AND" => ["fieldlocation" => 3, "mandatory" => 1]]);
     if (isset($formfields) && !empty($formfields)) {
       foreach ($formfields as $v) {
         if (!isset($jkp[$v["val_slug"]]) || empty($jkp[$v["val_slug"]])) {
           $errors[$v["val_slug"]] = sprintf($jkl['hd31'], $v["title"]).'<br>';
         }
       }
     }

    if (count($errors) > 0) {

      /* Outputtng the error messages */
      if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {

        header('Cache-Control: no-cache');
        die(json_encode(array('status' => 0, 'errors' => $errors, 'html' => $jkl["e3"])));

      } else {

        $errors = $errors;
      }

    } else {

      // Country stuff
      $countryName = 'Disabled';
      $countryAbbrev = 'xx';
      $city = 'Disabled';
      $countryLong = $countryLat = '';

      // if ip is valid do the whole thing
      if ($ipa && !$ua->isRobot()) {

        if (isset($_COOKIE['WIOgeoData'])) {
          // A "geoData" cookie has been previously set by the script, so we will use it

          // Always escape any user input, including cookies:
          list($city, $countryName, $countryAbbrev, $countryLat, $countryLong) = explode('|', strip_tags(base64_decode($_COOKIE['WIOgeoData'])));

        }

      }

      // Get the referrer
      $rowref = '';
      if (!isset($_SESSION['rlbid'])) {

        if (isset($_COOKIE['rlbid'])){
           $_SESSION['rlbid'] = $_COOKIE['rlbid'];
        } else {
          $salt = rand(100, 99999);
          $rlbid = $salt.time();
          JAK_base::jakCookie('rlbid', $rlbid, 31536000, JAK_COOKIE_PATH);
          $_SESSION['rlbid'] = $rlbid;
        }

      } else {
        $rowref = $jakdb->get("buttonstats", "referrer", ["session" => $_SESSION['rlbid']]);
      }

      // Get the department for the contact form if set
      $op_email = JAK_SMTP_SENDER;
      $depid = 0;

      // We save the data
      $jakdb->insert("contacts", ["opid" => $_SESSION['opid'],
      "depid" => $depid,
      "name" => $jkp['gname'],
      "email" => $jkp['gemail'],
      "message" => $jkp['gmessage'],
      "ip" => $ipa,
      "city" => $city,
      "country" => $countryName,
      "countrycode" => $countryAbbrev,
      "longitude" => $countryLong,
      "latitude" => $countryLat,
      "referrer" => $rowref,
      "sent" => $jakdb->raw("NOW()")]);

      $lastid = $jakdb->id();

      $listform = $jkl["g27"].': '.$jkp['gname'].'<br />';
      $listform .= $jkl["g47"].': '.$jkp['gemail'].'<br />';

      // And we complete the custom fields jak_save_custom_fields($opid, $clientid, $ticketid, $contactid, $jkp, $fieldloc)
        jak_save_custom_fields($_SESSION['opid'], 0, 0, $lastid, $jkp, 3);

      $listform .= 'IP: '.$ipa.'<br />';
      $listform .= $jkl["g28"].': '.$jkp['gmessage'];

      // Ok, we send the email // email address, cc email address, reply to, subject, message, attachment
          if (jak_send_email($op_email, explode(',', JAK_EMAILCC), $jkp['gemail'], JAK_TITLE, $listform, "")) {

        unset($_SESSION['jrc_captcha']);
        unset($_SESSION['chatbox_redirected']);

        // Ajax Request
        if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {

          header('Cache-Control: no-cache');
          die(json_encode(array('status' => 1, 'html' => $jkl["g65"])));

        } else {

              jak_redirect($_SERVER['HTTP_REFERER']);
          }
      }
    }

  }

  if (isset($jkp['search_now'])) {

      if (empty($page1) && $jkp['smart_search'] == '' || $jkp['smart_search'] == $jkl['hd']) {
          $errors['e'] = $jkl['hd2'];
      }

      if (empty($page1) && strlen($jkp['smart_search']) < '3') {
          $errors['e1'] = $jkl['hd3'];
      }

      if (count($errors) > 0) {
          $errors = $errors;
      } else {

      }
  }
}

// Get the custom contact fields
$custom_fields_contact = jak_get_custom_fields(3, $_SESSION['opid'], false, false, false, false, $BT_LANGUAGE, false, false, false, true, $errors);

// Now let's check the hits cookie
if (!jak_cookie_voted_hits($jaktable, $JAK_CMS_PAGE['id'], 'hits')) {

  jak_write_vote_hits_cookie($jaktable, $JAK_CMS_PAGE['id'], 'hits');
  
  // Update hits each time we have a new customer only
  $jakdb->update($jaktable, ["hits[+]" => 1], ["AND" => ["id" => $pageid, "opid" => $_SESSION['opid']]]);
}

// Get the url session
$_SESSION['jak_lastURL'] = JAK_rewrite::jakParseurl($page);

// Get the header navigation
$mheader = array(
    'items' => array(),
    'parents' => array()
);
// Builds the array lists with data from the menu table
foreach ($jakpages as $items) {

  if ($items["showheader"] == 1) {
    if ($items["ishome"] == 1) $items["url_slug"] = "";
    // Creates entry into items array with current menu item id ie. $menu['items'][1]
      $mheader['items'][$items['id']] = $items;
      // Creates entry into parents array. Parents array contains a list of all items with children
      $mheader['parents'][0][] = $items['id'];
  }
}

// Get the footer navigation
$mfooter = array(
    'items' => array(),
    'parents' => array()
);
// Builds the array lists with data from the menu table
foreach ($jakpages as $itemf) {

  if ($itemf["showfooter"] == 1) {
    $itemf['title'] = $itemf['title'];
    // Creates entry into items array with current menu item id ie. $menu['items'][1]
      $mfooter['items'][$itemf['id']] = $itemf;
      // Creates entry into parents array. Parents array contains a list of all items with children
      $mfooter['parents'][0][] = $itemf['id'];
  }
}

// Get the translations
$cms_text = $jakdb->select($jaktable1, ["id", "cmsid", "cmsslug", "description"], ["AND" => ["opid" => $_SESSION['opid'], "cmsid" => $pageid, "lang" => $BT_LANGUAGE, "cmsid[!]" => 0]]);
if (JAK_CLIENTID && empty($cms_text)) $cms_text = $jakdb->select($jaktable1, ["id", "cmsid", "cmsslug", "description"], ["AND" => ["cmsid" => $pageid, "lang" => JAK_LANG, "cmsid[!]" => 0]]);

// We will get certain stuff once
if (JAK_USERISLOGGED) {

  // The avatar
  $avatar_img = BASE_URL.JAK_FILES_DIRECTORY.'standard.jpg';
  if (JAK_USERID) {
    $avatar_img = BASE_URL.JAK_FILES_DIRECTORY.$jakuser->getVar("picture");
  } else {
    $avatar_img = BASE_URL.JAK_FILES_DIRECTORY.$jakclient->getVar("picture");
  }
} else {
  // Get the custom fields
  $custom_fields_register_modal = jak_get_custom_fields(1, $_SESSION['opid'], false, false, false, false, $BT_LANGUAGE, false, false, false, true, false);
}

// 404 needs to be covered
if ($page == '404') {
  include_once APP_PATH.'template/business/404.php';
// User is banned
} elseif ($page == 'banned') {
  include_once APP_PATH.'template/business/banned.php';
} else {

  // Make sure the page is available for everyone.
  if ($JAK_CMS_PAGE["access"] == 3 && !JAK_USERISLOGGED) {
    include_once APP_PATH.'template/business/client.php';
  } elseif (isset($JAK_CMS_PAGE["external_url"]) && !empty($JAK_CMS_PAGE["external_url"])) {
    jak_redirect($JAK_CMS_PAGE["external_url"]);
  } else {
    // Get the correct page
    if ($JAK_CMS_PAGE["prepage"] == JAK_CLIENT_URL) {
      include_once APP_PATH.'template/business/client.php';
    } elseif ($JAK_CMS_PAGE["prepage"] == JAK_SEARCH_URL) {
      include_once APP_PATH.'template/business/search.php';
    } elseif ($JAK_CMS_PAGE["prepage"] == JAK_SUPPORT_URL) {
      include_once APP_PATH.'template/business/support.php';
    } elseif ($JAK_CMS_PAGE["prepage"] == JAK_FAQ_URL) {
      include_once APP_PATH.'template/business/faq.php';
    } elseif ($JAK_CMS_PAGE["prepage"] == JAK_BLOG_URL) {
      include_once APP_PATH.'template/business/blog.php';
    } elseif ($JAK_CMS_PAGE["prepage"] == JAK_CONTACT_URL) {
      // Load the template
      include_once APP_PATH.'template/business/tplblocks/contact_tpl/contact.php';
    } else {
      // Load the template
      if (isset($JAK_CMS_PAGE["main_tpl"]) && !empty($JAK_CMS_PAGE["main_tpl"])) {
          include_once APP_PATH.'template/business/tplblocks/page_tpl/'.$JAK_CMS_PAGE["main_tpl"];
      } else {
          include_once APP_PATH.'template/business/tplblocks/page_tpl/page.php';
      }
    }
  }
}
?>
