<?php
//-----------------------------------------------------------------------------
// Tops WWW Site scripting library
//
// Request language selection script
//
// $Header: $
//
// Copyright (c) 2003-2018 Necne (Tops), Warszawa, POLAND. All rights reserved.
//-----------------------------------------------------------------------------

// ----------------------------------------------------------------------------
// This script does automatic preselection of the language root directory
// for HTTP request based on the HTTP_ACCEPT_LANGUAGE of the internet browser.
// Depending on the language reported by the browser one of the root
// site directories is inserted into the HTTP request string.
//
// Example:
//
// The request 'http://www.tops.com.pl/smscc' issued by a browser configured
// to accept british english language (en-gb) will be turned into the request:
// 'http://www.tops.com.pl/en/smscc'.
//
// Supported language prefixes 'pl', 'en'. Default prefix is 'en'.
// ----------------------------------------------------------------------------

session_start();

$langs = array("pl", "en");

// Determine language accepted
if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) &&
    strstr($_SERVER["HTTP_ACCEPT_LANGUAGE"], "en")) {
  $root = "en";
} elseif(isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) &&
    strstr($_SERVER["HTTP_ACCEPT_LANGUAGE"], "pl")) {
  $root = "pl";
} else {
  // Default language
  $root = "en";
}

// Check wheather the URI contains the language subfolder
$found = false;
foreach($langs as $langname) {
  $pos = strpos($_SERVER["REQUEST_URI"], "/".$langname);
  if (is_integer($pos) && $pos == 0) {
    $found = true;
  }
}

if(isset($_COOKIE["language"])) {
  $root = $_COOKIE["language"];
}

if (!$found) {
  Header("Location: https://" . $_SERVER["HTTP_HOST"] . "/" . $root .
    $_SERVER["REQUEST_URI"]);
} else {
  Header("Location: https://" . $_SERVER["HTTP_HOST"] .
    $_SERVER["REQUEST_URI"]);
}
?>
