<?php

const N="\n";

function dienice($msg,$ec) {
	global $link;
	if (isset($link) && $link!==false) mysqli_close($link);
	echo $msg;
	exit($ec);
}

$inifp='../conf/mastostart.ini';
$conf=@parse_ini_file($inifp);
if ($conf===false) dienice('Could not open configuration file.'.N,1);
if (!array_key_exists('instpath',$conf)) dienice('Configuration file: «instpath» is not defined.'.N,1);

$path=preg_replace('#\?.*$#','',$_SERVER['REQUEST_URI']);
$path=preg_replace('/^'.preg_quote($conf['instpath'],'/').'/','',$path);
$ndir=preg_match_all('#/#',$path)-1;
$prepath='';
for ($i=0; $i<$ndir; $i++)
	$prepath.='../';
$path=preg_replace('#/+$#','',$path);

$blang='en';
if (array_key_exists('HTTP_ACCEPT_LANGUAGE',$_SERVER)) {
	$langs=[];
	$buff=explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);
	foreach ($buff as $ent) {
		$ent=trim($ent);
		$ent=explode(';',$ent);
		(count($ent)<2) ? $ent[1]=1 : $ent[1]=preg_replace('/^q=/','',$ent[1])+0;
		$ent[0]=locale_canonicalize($ent[0]);
		//echo '<pre>'.print_r($ent,true).'</pre>';
		$langs[$ent[0]]=$ent[1];
	}
	arsort($langs);
	$blang=array_key_first($langs);
}
//echo $_SERVER['HTTP_ACCEPT_LANGUAGE'].' » '.$blang.'<br>'.N;

require '../lib/supplangs.php';
require '../lib/localemap.php';

$dlang=null;
if (preg_match('#/('.implode('|',$supplangscodes).')$#',$path,$lang)===1) {
	$dlang=$lang[1];
	$path=preg_replace('#/[^/]+$#','',$path);
} elseif (array_key_exists('HTTP_ACCEPT_LANGUAGE',$_SERVER)) {
	foreach ($langs as $lang=>$val) {
		if (in_array($lang,$supplangscodes)) {
			$dlang=$lang;
			break;
		}
	}
	if (is_null($dlang)) {
		foreach ($langs as $lang=>$val) {
			foreach ($supplangs as $slang=>$slangd) {
				if (preg_match('/^'.preg_quote($lang,'/').'/',$slang)) {
					$dlang=$slang;
					break(2);
				}
			}
		}
	}
}
if (is_null($dlang)) $dlang='en';
//echo 'dlang: '.$dlang.'<br>'.N;

$tdom='masthelp';
$locale=localemap($dlang);
//echo 'locale: '.$locale.'<br>'.N;
setlocale(LC_ALL,$locale);
bindtextdomain($tdom,'./locale');
textdomain($tdom);
bind_textdomain_codeset($tdom,'UTF-8');

$needstrans=false;

$menu=[
	'guide'=>['liadd'=>null, 'href'=>$conf['instpath'].'/'.$dlang, 'title'=>_('Guide'), 'selected'=>false, 'submenu'=>null],
	'instances'=>['liadd'=>null, 'href'=>$conf['instpath'].'/instances/'.$dlang, 'title'=>_('Instances'), 'selected'=>false, 'submenu'=>null],
	'links'=>['liadd'=>null, 'href'=>$conf['instpath'].'/links/'.$dlang, 'title'=>_('Links'), 'selected'=>false, 'submenu'=>null],
	'about'=>['liadd'=>null, 'href'=>$conf['instpath'].'/about/'.$dlang, 'title'=>_('About'), 'selected'=>false, 'submenu'=>[
			'stats'=>['liadd'=>null, 'href'=>$conf['instpath'].'/stats/'.$dlang, 'title'=>_('Statistics'), 'selected'=>false, 'submenu'=>null],
			'contribute'=>['liadd'=>null, 'href'=>$conf['instpath'].'/contribute/'.$dlang, 'title'=>_('Contribute'), 'selected'=>false, 'submenu'=>null]
		]
	],
	'language'=>['liadd'=>null, 'href'=>null, 'title'=>_('Language'), 'selected'=>false, 'submenu'=>[]]
];

foreach ($supplangs as $slang=>$slangd)
	$menu['language']['submenu'][$slang]=['liadd'=>null, 'href'=>$conf['instpath'].$path.'/'.$slang, 'title'=>$slangd['orname'], 'selected'=>false, 'submenu'=>null];

$menu['language']['submenu'][$dlang]['href']=null;
$menu['language']['submenu'][$dlang]['liadd']=null;
$menu['language']['submenu'][$dlang]['selected']=true;

$cont=[];

$cont['css']=['theme.css','menu.css'];
$cont['js']=['menu.js'];
$cont['bodyadd']='';

switch($path) {

	case '':
	$cont['fp']='home.php';
	$cont['atit']=' - '._('Guide');
	$cont['desc']=_('A thorough introduction to Mastodon');
	$cont['js'][]='shsum.js';
	$cont['js'][]='guideanchors.js';
	$cont['js'][]='scrolltrack.js';
	$cont['bodyadd']=' onscroll="scrolltrack()"';
	$menu['guide']['href']=null;
	$menu['guide']['selected']=true;
	$url='home';
	if (in_array($dlang,['ca'])) $needstrans=true;
	break;

	case '/instances':
	$cont['fp']='instances.php';
	$cont['atit']=' - '._('Instances');
	$cont['desc']=_('Mastodon instances');
	$cont['css'][]='instances.css';
	$menu['instances']['href']=null;
	$menu['instances']['selected']=true;
	$url='instances';
	if (in_array($dlang,['ca','es'])) $needstrans=true;
	break;

	case '/users':
	$cont['fp']='users.php';
	$cont['atit']=' - '._('Users');
	$cont['desc']=_('Directory of Mastodon users');
	$cont['css'][]='instances.css';
	/*$menu['instances']['href']=null;
	$menu['instances']['selected']=true;*/
	$url='users';
	break;

	case '/links':
	$cont['fp']='links.php';
	$cont['atit']=' - '._('Links');
	$cont['desc']=_('Useful Mastodon and Fediverse related links');
	$menu['links']['href']=null;
	$menu['links']['selected']=true;
	$url='links';
	break;

	case '/about':
	$cont['fp']='about.php';
	$cont['atit']=' - '._('About');
	$cont['desc']=_('Info about Mastodon Help’s authors, contributors, license');
	$menu['about']['href']=null;
	$menu['about']['selected']=true;
	$url='about';
	if (in_array($dlang,['ca','es'])) $needstrans=true;
	break;

	case '/stats':
	$cont['fp']='stats.php';
	$cont['atit']=' - '._('Statistics');
	$cont['desc']=_('Statistics about Mastodon Help');
	$cont['css'][]='stats.css';
	$menu['about']['selected']=true;
	$menu['about']['submenu']['stats']['href']=null;
	$menu['about']['submenu']['stats']['selected']=true;
	$url='stats';
	if (in_array($dlang,['ca','es'])) $needstrans=true;
	break;

	case '/contribute':
	$cont['fp']='contribute.php';
	$cont['atit']=' - '._('Contribute');
	$cont['desc']=_('Contribute to Mastodon Help development');
	$menu['about']['selected']=true;
	$menu['about']['submenu']['contribute']['href']=null;
	$menu['about']['submenu']['contribute']['selected']=true;
	$url='contribute';
	if (in_array($dlang,['ca','es'])) $needstrans=true;
	break;

	default:
	http_response_code(404);
	$cont['fp']='404.php';
	$cont['atit']=' - '._('Resource not found');
	$cont['desc']=_('Resource not found');
	$url='404';
	/*$nffp='404.log';
	$nff=@fopen($nffp,'a');
	if ($nff) {
		fwrite($nff,$_SERVER['REQUEST_URI'].N);
		fclose($nff);
	} else {
		echo 'Mannaggia!';
	}*/
	if (in_array($dlang,['ca','es'])) $needstrans=true;
	break;
}
$cont['mtit']=substr($cont['atit'],3);

$uid=[];
$uid[]=$_SERVER['REMOTE_ADDR'];
if (array_key_exists('HTTP_USER_AGENT',$_SERVER)) $uid[]=$_SERVER['HTTP_USER_AGENT'];
if (array_key_exists('HTTP_ACCEPT',$_SERVER)) $uid[]=$_SERVER['HTTP_ACCEPT'];
if (array_key_exists('HTTP_ACCEPT_LANGUAGE',$_SERVER)) $uid[]=$_SERVER['HTTP_ACCEPT_LANGUAGE'];
if (array_key_exists('HTTP_ACCEPT_ENCODING',$_SERVER)) $uid[]=$_SERVER['HTTP_ACCEPT_ENCODING'];
$uid=md5(implode('|',$uid));

try { $link=mysqli_connect($conf['db_host'],$conf['db_user_name'],$conf['db_user_password'],$conf['db_name'],$conf['db_port'],$conf['db_socket']); }
catch (Exception $error) { dienice(_('Couldn’t connect to database: ').mysqli_connect_error().' ['.mysqli_connect_errno().'].',2,false); }
if ($link===false) dienice(_('Couldn’t connect to database: ').mysqli_connect_error().' ['.mysqli_connect_errno().'].',2,false);
mysqli_set_charset($link,'utf8mb4');
mysqli_query($link,'INSERT INTO ZHits (UID,URL,Lang,TS) VALUES ("'.$uid.'","'.$url.'","'.$dlang.'",'.time().')') or dienice(__LINE__.': '.mysqli_error($link),2,true);
mysqli_close($link);

$menuout='';

function buildmenu($menu,$submenu=false) {
	global $menuout;
	foreach ($menu as $key=>$arr) {
		$liclasses=[];
		$menuout.='<li';
		if (!is_null($arr['liadd'])) $menuout.=' '.$arr['liadd'];
		if ($arr['selected']) $liclasses[]='hil';
		if (!is_null($arr['submenu'])) {
			$menuout.=' onmouseover="chulsh(this,true)" onmouseout="chulsh(this,false)"';
			($submenu) ? $liclasses[]='lipr' : $liclasses[]='lipd';
		}
		if (count($liclasses)>0) $menuout.=' class="'.implode(' ',$liclasses).'"';
		$menuout.='>';
		if (!is_null($arr['href'])) {
			$menuout.='<a href="'.$arr['href'].'">'.$arr['title'].'</a>';
		} else {
			$menuout.=$arr['title'];
		}
		if (!is_null($arr['submenu'])) {
			//$menuout.='<img src="/imgs/icona-32.png" width="5" height="5" style="float:right;">';
			($submenu) ? $class='ulb' : $class='ula';
			$menuout.=N.'<ul class="'.$class.'" onmouseover="ulsh(this,true)" onmouseout="ulsh(this,false)">'.N;
			buildmenu($arr['submenu'],true);
			$menuout.='</ul>'.N;
		}
		$menuout.='</li>'.N;
	}
}

buildmenu($menu);

//echo htmlentities($menuout);

$cjrand=rand(0,999999);
//$cjrand='0.1';

echo '<!DOCTYPE HTML>
<html lang="'.$dlang.'">
<head>
<title>Mastodon Help'.$cont['atit'].'</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="description" content="'.$cont['desc'].'">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta property="og:image" content="'.$prepath.'imgs/ogimage03.png">
<link rel="icon" type="image/png" href="'.$prepath.'imgs/icona-32.png" sizes="32x32">
<link rel="icon" type="image/png" href="'.$prepath.'imgs/icona-192.png" sizes="192x192">
<link rel="icon" type="image/png" href="'.$prepath.'imgs/icona-512.png" sizes="512x512">
<link rel="apple-touch-icon-precomposed" href="'.$prepath.'imgs/icona-180.png">'.N;

foreach ($cont['css'] as $val)
	echo '<link rel="stylesheet" type="text/css" href="'.$prepath.'css/'.$val.'?v='.$cjrand.'">'.N;
foreach ($cont['js'] as $val)
	echo '<script language="JavaScript" src="'.$prepath.'js/'.$val.'?v='.$cjrand.'"></script>'.N;

echo '</head>
<body'.$cont['bodyadd'].'>
<nav>
<div id="hmenu">
<img src="'.$prepath.'imgs/menuicon_inactive.svg" id="menuicon" onclick="swmenu()">
<div id="menutit">Mastodon Help'.$cont['atit'].'</div>
<div id="menu">
<ul>
'.$menuout.'
</ul>
</div>
</div>'.N;

require $cont['fp'];

//if ($needstrans) printf('<div id="transd">'._('This translation is missing, incomplete or not up-to-date. Please click <a href="/contribute/%s">here</a> if you’d like to help, or <span class="transc" onclick="document.getElementById(\'transd\').style.display=\'none\'">here</span> to close this message').'</div>'.N,$dlang);

echo '<a class="invisible" href="https://kolektiva.social/@jones_" rel="me">...</a>
</body>
</html>'.N;

?>
