<?php

$indexlangs = array(
    "en" => "index-en.html",
    "pt" => "pt/",
    "fr" => "fr/",
    );

function sortAccept($header)
    {
        $matches = array();
        foreach (explode(',', $header) as $option) {
            $option = array_map('trim', explode(';', $option));

            $l = strtolower($option[0]);
            if (isset($option[1])) {
                $q = (float) str_replace('q=', '', $option[1]);
            } else {
                $q = null;
                // Assign default low weight for generic values
                if ($l == '*/*') {
                    $q = 0.01;
                } elseif (substr($l, -1) == '*') {
                    $q = 0.02;
                }
            }
            // Unweighted values, get high weight by their position in the
            // list
            $matches[$l] = isset($q) ? $q : 1000 - count($matches);
        }
        arsort($matches, SORT_NUMERIC);
        return $matches;
    }

function matchAccept($header, $supported)
    {
        $matches = sortAccept($header);
        foreach ($matches as $key => $q) {
            if (isset($supported[$key])) {
                return $supported[$key];
            }
        }
        foreach ($matches as $key => $q) {
	    $key = substr($key,0,2);
            if (isset($supported[$key])) {
                return $supported[$key];
            }
        }
        // If any (i.e. "*") is acceptable, return the first supported format
        if (isset($matches['*'])) {
            return array_shift($supported);
        }
        return null;
    }

function negotiateLanguage($supported, $default = 'pt')
    {
        $supp = array();
        foreach ($supported as $lang => $isSupported) {
            if ($isSupported) {
                $supp[strtolower($lang)] = $lang;
            }
        }
        if (!count($supp)) {
            return $default;
        }

        if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
            $match = matchAccept(
                $_SERVER['HTTP_ACCEPT_LANGUAGE'],
                $supp
            );
            if (!is_null($match)) {
                return $match;
            }
        }

        if (isset($_SERVER['REMOTE_HOST'])) {
            $lang = strtolower(end($h = explode('.', $_SERVER['REMOTE_HOST'])));
            if (isset($supp[$lang])) {
                return $supp[$lang];
            }
        }

        return $default;
    }
$supported = array("fr" => true, "pt" => true, "en" => true);

$lang = negotiateLanguage($supported);
// Finally redirect to desired location
header('Location: ' . $indexlangs[$lang]);
?>
