<?php

## Flag fuer Testumgebung
$debugip="99.99.99.99";
#$debugip="88.117.155.34";       # AMUE
#$debugip="90.146.149.163";       # Aschach
$debug=0;
if($_SERVER["REMOTE_ADDR"]==$debugip) {
   $debug=1;
}

$root=$_SERVER['DOCUMENT_ROOT'];
$url=($_SERVER['REDIRECT_URL']);
## pathnames must start with 2 letter language code
$aDir=explode("/",$url);
if(count($aDir) > 0) {
  $langpath=$aDir[1];
  debug("LANGUAGE: $langpath");
  if(strlen($langpath)>2) {
     ## invalid URL
     debug("header: send 301 Location: /\n");
     if(!$debug) {
       http_response_code(404);
       header('Location: /');
     }
     exit;
  }
  $availlang=explode(" ","de en es it fr pt zh ja kr tr");
  if (!in_array($langpath,$availlang)) {
     $redirurl=str_replace('/'.$langpath.'/','/en/',$url);
     header('Location: '.$redirurl);
  } 
}
$ext = pathinfo($url,PATHINFO_EXTENSION);
$validext = array('html','htm','php');
$basefile=dirname($url);

if(in_array($ext,$validext)) {
	$basefile = pathinfo($url,PATHINFO_BASENAME);
} else {
	$basefile = $url;
}

$aPath=explode("/",$basefile);

debug("Root: $root\nURL: $url\nEXT: $ext\nBasefile: $basefile".print_r($aPath,true));

while(count($aPath)>0) {
	$file=$root.implode("/",$aPath)."/index.html";
	if(is_file($file)) {
	   break;
			  }
	array_pop($aPath);
}
if(!is_file($file)) {
  $file=$root."index.html";
}
if($debug) {
  debug("Using file: $file");
  exit;
}
readfile($file);

function debug($msg) {
  global $debug;
  if ($debug) {
     echo $msg."\n";
  }
}

?>
