<?
  define('NOREDIR', true);
  $sessionrequired=0;
  $nologsessionstart=1;
  require "includes/sessionhandler.php";
  
  $DEBUG = 0;
  
  // bad as in used by the scraper on my outlinks
  $badcountries = ['BR','AR','EC','PY','CO','MX','CL','UY','VE','VN','ID','SG','ZA','BD','PK','IN','JO','MA','PA','CR','PH','DZ'];
  
  $url = "/";
  $siteid=intval($_REQUEST['siteid']);
  
  $setid=intval($_REQUEST['setid']);
  $tag=$_REQUEST['tag'] ?? NULL;
  $target=$_REQUEST['target'] ?? NULL;
  $entrytag = $_SESSION['entrytag'] ?? NULL;
  $extratrack = 'u'; // Unknown
  if ($entrytag)
  {
    // search-replace the tracking id if needed
    if      (stripos($entrytag, 'email|') !== false)         { $extratrack = 'e'; }
    else if (stripos($entrytag, 'email_extra|') !== false)   { $extratrack = 'x'; }
    else if (stripos($entrytag, 'email_toppicks|') !== false){ $extratrack = 'a'; } // was adwords, but we dont use them anymore, so 'a' for amazon toppicks email
    else if (stripos($entrytag, 'facebook|') !== false)      { $extratrack = 'f'; }
    else if (stripos($entrytag, 'googlesearch|') !== false)  { $extratrack = 'g'; }
    else if (stripos($entrytag, 'twitter|') !== false)       { $extratrack = 't'; }
    // and now for the non-amazon-tracked sources
    else if (stripos($entrytag, '|https://www.bing.com/') !== false)   { $extratrack = 'b'; }
    else if (stripos($entrytag, '|https://duckduckgo.com/') !== false) { $extratrack = 'd'; }
    else if (stripos($entrytag, '|https://nl.pepper.com/') !== false)  { $extratrack = 'p'; }
    else if (stripos($entrytag, 'tweakers|') !== false)                { $extratrack = 'w'; }
  }
  
  $nolog = false;
  $haslogo = false;
  $jump = false;
  $usefetchurl = false;
  $hitquery  = "";
  
  $params = array();
  if ($tag)   { $params['{tpl:tag}'] = urlencode(str_replace('_', '-', $tag)); } else { $params['{tpl:tag}'] = 'unknown'; }
  if ($_POST['jump'] == 'true') { 
    $jump = true;
  }
  if (!$jump && $setid) { $params['{tpl:tag}'] .= "_".$setid; }
  $params['{tpl:locale}'] = LOCALE;
  // Tracking 
  $loggedin = (isset($_SESSION['userid']) && intval(isset($_SESSION['userid'])));
  $params['{tpl:track}'] = (($loggedin) ? 'r' : 'u').$extratrack;
  // Setid to 0 for direct links
  $params['{tpl:id}'] = 0;
  
  // Stop immediatly on this
  if (isBotNet())
  {
    http_response_code(500);
print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">
<html><head>
<title>500 Internal Server Error</title>
</head><body>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error or
misconfiguration and was unable to complete
your request.</p>
<p>Please contact the server administrator at
 [no address given] to inform them of the time this error occurred,
 and the actions you performed just before this error.</p>
<p>More information about this error may be available
in the server error log.</p>
</body></html>";
    return;
  }
  
  // Do we have the out-link scraper?
  // - New session
  // - Referer www.brickwatch.net or empty
  // - From BR/AR c.s.
  // Do not scan for tag, else we might not be able to recognize them later on when they fix this
  $geopipcountry = geoip_country_code_by_name($_SERVER['REMOTE_ADDR']);
  if ($newguid && (in_array($_SERVER['HTTP_REFERER'], ['', 'https://www.speelwatch.com/', 'https://www.google.com/']))
    && in_array($geopipcountry, $badcountries))
  {
    Header('Referrer-Policy: no-referrer-when-downgrade');
    Header("Location: /b?u=stop", TRUE, 301);
    return;
  } 
  else // It WAS a new guid, and we had a previous IP. And we are from bad country
  if (
    !$newguid && isset($_SESSION['newguid']) && isset($_SESSION['OLDIP'])
    && in_array($geopipcountry, $badcountries)
  )
  {
    Header('Referrer-Policy: no-referrer-when-downgrade');
    Header("Location: /b?u=stop", TRUE, 301);
    return;
  }
  
  // Do not log on these extremes
  if (!$tag && !isset($_SESSION['userid']) && !$entrytag) // 
  {
    $nolog=true;
  }
  else if (!$tag && !isset($_SESSION['userid']) && ($newguid || isset($_SESSION['newguid']))) // We have an entry tag (likely googlesearch), but a new guid on the out
  {
    $nolog=true;
  }
  
  // if we came here, log the entrytag when no nolog
  if ($delayedsessionstartlogging && !$nolog) {
    log_session_start($entrytag);
  }
  
  // Jump or showsplashscreen?
  if (
    (!$jump && (stripos($_SERVER['HTTP_REFERER'], 'speelwatch.com') === false))
    ||
    (!$jump && $newguid)
  )
  {
    $url = "/go/$siteid/$setid/".urlencode($tag)."?jump=true";
    // Iff set, prefix with locale
    if ($_REQUEST['lang'])
    {
      $url = '/'.LOCALE.$url;
    }
    // chop the first '/' because of b-redirection
    $b_url = substr($url, 1);
    // Try to fetch language from session
    if ($_REQUEST['lang']) { $lang = $_REQUEST['lang']; } else if ($_SESSION['lang']) { $lang = $_SESSION['lang']; } else { $lang = 'en'; }
    // Get site title
    if (is_valid($siteid)) {
      $query = "select title from sites where siteid=".intval($siteid);
      $row = getCachedRow($query, 3600);
      $sitetitle = $row['title'];
    }
    // Show splash
    require "includes/out.php";
    return;
  }
  
  $ssiok = true; // Assume it's correct
  if (!isset($dbQuery)) { $dbQuery = new \Kiobi\Database\Query(); }
  // Here not instructions  
  if (is_valid($siteid) && is_valid($setid)) 
  { 
    $query = "select itemurl, url , ss.title, localid, s.status, s.title as sitetitle, s.haslogo, s.fetchurl, ssi.availability, ssi.status as ssistatus from sites s join sites_sets ssi on s.siteid=ssi.siteid join sets ss on ssi.setid=ss.setid where s.siteid=$siteid and ssi.setid=$setid";
    $result = $dbQuery->doQuery($query);
    if ($result && $row=$dbQuery->fetchNext($result))
    {
      $url = $row['itemurl'];
      $params['{tpl:id}'] = $setid;
      $params['{tpl:title}'] =  $row['title'];
      $params['{tpl:title_esc}'] = escape($row['title']);
      // Amazon workarounds
      $ssiok = (($row['ssistatus'] == 'ok') || (strpos($row['ssistatus'], 'fetchIDA') !== false));
      // On amazon, remove the #'s from the localid
      if (in_array($siteid, [20,21,22,23,24,25,26]) && (strpos($row['localid'], '#') !== false))
      {
        $ssiok = false; // This will remove the 'm' parameter from the outlink
        $row['localid'] = str_replace('#', '', $row['localid']);
      }
      $params['{tpl:localid}'] = $row['localid'];
      if (in_array($siteid, array(1,2,3,4,5)))
      {
        if (empty($params['{tpl:localid}'])) { $params['{tpl:localid}'] = escape(strtolower($row['title'])).'-'.$setid; }
      }
      $haslogo = ($row['haslogo'] == 'Y');
      $sitetitle = $row['sitetitle'];
      $availability=$row['availability'];
      $ssistatus = $row['ssistatus'];
      $fetchurl = $row['fetchurl'];
  
      // No longer redirect to expired links
      // status check for the main site as the site has become inactive, availability for site_set  if there was a fuckup or alike. 
      if ( ($row['status'] == 'I') || ($row['availability'] == 'U') ) 
      {
        // Redirect to 
        $url = "/set/$setid/".escape($row['title']).'.html?expired&src='.$siteid;
        $nolog = true;
      }
  
      // Also makes sure localid_1 exists
      list($params['{tpl:localid_1}'], $params['{tpl:localid_2}']) = explode('|', $row['localid'], 2);
      
      // And the urldecoded variant
      $params['{tpl:localid_d}'] = urldecode($row['localid']);
      
      if ($DEBUG || (shouldLog() && !$nolog))
      {
        $hitquery = "insert into popularity (setid, siteid, date, hits) values ($setid, $siteid, NOW(), 1) on duplicate key update hits=hits+1";
      }
    }
    else // Fallback to site
    {
      $query = "select url, status, title as sitetitle, haslogo from sites where siteid=$siteid";
      $res = $dbQuery->doQuery($query);
      if ($res && $row = $dbQuery->fetchNext($res))
      {
        if ($row['status'] == 'I')
        {
          $url = '/sites?expired&src='.$siteid;
          $nolog = true;
        }
        else
        {
          $url = $row['url'];
          $sitetitle = $row['sitetitle'];
          $haslogo = ($row['haslogo'] == 'Y');
        }
      }
      
      if ($DEBUG || (shouldLog() && !$nolog))
      {
        $hitquery = "insert into popularity (setid, siteid, date, hits) values (0, $siteid, NOW(), 1) on duplicate key update hits=hits+1";
      }
      
    }
  }
  else if (is_valid($siteid))
  {
    $query = "select url, status, title as sitetitle, haslogo from sites where siteid=$siteid";
    $res = $dbQuery->doQuery($query);
    if ($res && $row = $dbQuery->fetchNext($res))
    {
      if ($row['status'] == 'I')
      {
        $url = '/sites?expired&src='.$siteid;
        $nolog = true;
      }
      else
      {
        $url = $row['url'];
        $sitetitle = $row['sitetitle'];
        $haslogo = ($row['haslogo'] == 'Y');
        if (in_array($siteid, array(1,2,3,4,5)) && $target)
        {
          // Only these sites, only normal chars
          $url .= preg_replace('/[^A-Za-z0-9\-\/ \?\=]/', '', $target);
        }
      }
    }
    
    if ($DEBUG || (shouldLog() && !$nolog)) 
    {
      $hitquery = "insert into popularity (setid, siteid, date, hits) values (0, $siteid, NOW(), 1) on duplicate key update hits=hits+1";
    }
  }
  
  // Go jump
  // We should be able to detect it here!
  // - jump=true
  // - method=GET
  // - newguid is set
  
  // Search & replace
  $url = str_replace(array_keys($params), array_values($params), $url);
  if ($siteid == 110) // bol be
  {
    if ($_REQUEST['lang']) { $lang = $_REQUEST['lang']; } else if ($_SESSION['lang']) { $lang = $_SESSION['lang']; } else { $lang = 'nl'; } // default nl
    if ($lang == 'fr') { $url = str_replace('be%2Fnl', 'be%2Ffr', $url); }
  }
  else if ($siteid == 111) // Alternate.be
  {
    if ($_REQUEST['lang']) { $lang = $_REQUEST['lang']; } else if ($_SESSION['lang']) { $lang = $_SESSION['lang']; } else { $lang = 'nl'; } // default nl
    if ($lang == 'fr') { $url = str_replace('li=1552940', 'li=1578985', $url); }
  }
  else if (!$ssiok && in_array($siteid, array(20,21,22,23,24,25)))
  {
    // Remove the m= link in the amazon URL
    $i = strpos($url, '&m=');
    if ($i) { $url = substr($url, 0, $i); }
  }
  
  // Add lang tag to amazon de
  if ($siteid == 20)
  {
    if ($_REQUEST['lang']) { $lang = $_REQUEST['lang']; } else if ($_SESSION['lang']) { $lang = $_SESSION['lang']; } else { $lang = 'en'; }
    if ($lang == 'nl') { $url .= '&language=nl_NL'; }
  }
  
  // hitquery ?
  if ($hitquery) { $dbQuery->doQuery($hitquery); }
  // Log hit
  log_hit($siteid, $setid, $tag, $entrytag, $nolog);
  // And redirect immediatly (302, as we always want to go through this!)
  Header('Referrer-Policy: no-referrer-when-downgrade');
  Header("Location: $url", TRUE, 302);
    
?>