<?php

require '../../lib/glob.php';
require '../../lib/muoribene.php';
require '../../lib/sessionstart.php';
require '../../lib/myconn.php';
require '../../lib/getadmacc.php';
if ($account['Level']=='guest')
	muoribene('Sorry, you are not authorized.',true);
require '../../lib/jsencode.php';
require '../../lib/menu.php';
$menu['menu']['selected']=true;
$menu['menu']['submenu']['instances']['selected']=true;
buildmenu($menu);

$dbg='';

use function mysqli_real_escape_string as myesc;

// praticamente una macro
function hspech($str) {
	return(htmlspecialchars($str,ENT_QUOTES|ENT_HTML5,'UTF-8'));
}

require '../../lib/randstr.php';

function parsetempline($line,$substarr) {
	$patterns=array('/%guestinsturi/','/%guestname/','/%guestemail/','/%guestpassword/','/%ourdomain/');
	return(preg_replace($patterns,$substarr,$line));
}

if (array_key_exists('id',$_GET) && preg_match('/^[0-9]+$/',$_GET['id'])===1) {
	$_GET['id']+=0;
	$res=mysqli_query($link,'SELECT * FROM Instances WHERE ID='.$_GET['id'])
		or muoribene(__LINE__.': '.mysqli_error($link),true);
	if (mysqli_num_rows($res)!=1)
		muoribene('Non esiste alcuna istanza con ID='.$_GET['id'].'.',true);
	$inst=mysqli_fetch_assoc($res);
	if (trim($inst['Email'])=='')
		muoribene('Nessun indirizzo email è definito per questa istanza.',true);
	$createacc='false';
	if (!is_null($inst['GuestID'])) {
		$res=mysqli_query($link,'SELECT * FROM Admins WHERE ID='.$inst['GuestID'])
			or muoribene(__LINE__.': '.mysqli_error($link),true);
		if (mysqli_num_rows($res)==0)
			muoribene('Non esiste alcun account con ID='.$inst['GuestID'].'.',true);
		$templfp='mailtemplates/reminder';
	} else {
		$res=mysqli_query($link,'SELECT * FROM Admins WHERE Email=\''.myesc($link,$inst['Email']).'\'')
			or muoribene(__LINE__.': '.mysqli_error($link),true);
		if (mysqli_num_rows($res)==0) {
			$templfp='mailtemplates/first_invitation';
			$createacc='true';
		} else {
			$templfp='mailtemplates/more_instances';
		}
	}
	$templ=file($templfp,FILE_IGNORE_NEW_LINES);
	if ($templ===false)
		muoribene('Impossibile aprire «'.$templfp.'».',true);

	$out='<form action="invite.php" method="post" id="f" onsubmit="return send();">'.N;
	$out.='<table class="bigtab">'.N;
	$out.='<tbody>'.N;
	$out.='<tr><td class="insthead">Email di invito</td></tr>'.N;
	$out.='<tr><td>'.N;
	if (is_null($inst['AdmDisplayName']))
		$admname='';
	elseif (trim($inst['AdmDisplayName'])!='')
		$admname=$inst['AdmDisplayName'];
	elseif (trim($inst['AdmAccount'])!='')
		$admname=$inst['AdmAccount'];
	else
		$admname='';
	$haddress=$inst['Email'];
	if ($admname!='') $haddress=$admname.' <'.$haddress.'>';
	$madmname='';
	if ($admname!='') $madmname=' '.$admname;
	if ($admname=='') $admname='Unknown';
	$password=randstr(16);
	define('RN',"\r\n");
	//('/%guestinsturi/','/%guestname/','/%guestemail/','/%guestpassword/','/%ourdomain/')
	$subj=parsetempline($templ[0],array($inst['URI'],$madmname,$inst['Email'],$password,$iniarr['site_domain']));
	$message='';
	for ($i=2; $i<count($templ); $i++)
		$message.=parsetempline($templ[$i],array($inst['URI'],$madmname,$inst['Email'],$password,$iniarr['site_domain'])).RN;

	$out.='<div class="mailheader"><strong>Mittente:</strong> '.hspech($iniarr['ref_name']).' '.hspech('<'.$iniarr['ref_email'].'>').'</div>'.N;
	$out.='<div class="mailheader"><strong>Destinatario:</strong> '.hspech($haddress).'</div>'.N;
	$out.='<div class="mailheader"><strong>Oggetto:</strong> <input type="text" id="subject" name="subject" class="mailsubj" value="'.hspech($subj).'"></div>'.N;
	$out.='<textarea id="message" name="message" rows="20" class="mailmsg">'.hspech($message).'</textarea>'.N;
	$out.='<input type="button" value="Invia" class="mailbut" onclick="send();">'.N;
	$out.='<input type="hidden" name="id" value="'.$inst['ID'].'">'.N;
	$out.='<input type="hidden" name="insturi" value="'.hspech($inst['URI']).'">'.N;
	$out.='<input type="hidden" name="password" value="'.hspech($password).'">'.N;
	$out.='<input type="hidden" name="to" value="'.hspech($haddress).'">'.N;
	$out.='<input type="hidden" name="guestname" value="'.hspech($admname).'">'.N;
	$out.='<input type="hidden" name="guestaddr" value="'.hspech($inst['Email']).'">'.N;
	$out.='<input type="hidden" name="createacc" value="'.$createacc.'">'.N;
	$out.='</td></tr>'.N;
	$out.='</tbody>'.N;
	$out.='</table>'.N;
	$out.='</form>'.N;
	$insturi=$inst['URI'];
} elseif (array_key_exists('id',$_POST) && preg_match('/^[0-9]+$/',$_POST['id'])===1 && array_key_exists('insturi',$_POST) && trim($_POST['insturi'])!='' && array_key_exists('subject',$_POST) && trim($_POST['subject'])!='' && array_key_exists('to',$_POST) && trim($_POST['to'])!='' && array_key_exists('message',$_POST) && trim($_POST['message'])!='' && array_key_exists('password',$_POST) && trim($_POST['password'])!='' && array_key_exists('guestaddr',$_POST) && trim($_POST['guestaddr'])!='' && array_key_exists('createacc',$_POST) && preg_match('/^true|false$/',$_POST['createacc'])===1) {
	$_POST['id']+=0;
	$from=$iniarr['ref_name'].' <'.$iniarr['ref_email'].'>';
	//questo per far provette d'invio mail senza toccare il db
	if ($iniarr['mail_test_to']!=false && trim($iniarr['mail_test_to'])!='') {
		$test=true;
		$to=$iniarr['mail_test_to'];
	} else {
		$test=false;
		$to=$_POST['to'];
	}
	$mail=mail($to,'=?utf-8?B?'.base64_encode($_POST['subject']).'?=',wordwrap($_POST['message'],76,"\r\n",false),array('From'=>$from,'Content-Type'=>'text/plain; charset=UTF-8','Content-Transfer-Encoding'=>'8bit'));
	if (!$mail)	{
		$out='<div class="message">Errori nell’invio della mail.<br>Puoi <a href="invite.php?id='.$_POST['id'].'">riprovare</a>.</div>'.N;
	} elseif (!$test) {
		if ($_POST['createacc']=='true') {
			mysqli_query($link,'INSERT INTO Admins (ID, Username, Email, Password, Level, Page, MaxLocalities, MaxLanguages, MaxFinancing, MaxPolicies, MaxTags, Enabled) VALUES (NULL, \''.myesc($link,$_POST['guestname']).'\', \''.myesc($link,$_POST['guestaddr']).'\', \''.myesc($link,password_hash($_POST['password'],PASSWORD_DEFAULT)).'\', \'guest\', \'0\', \'1\', \'0\', \'3\', \'3\', \'3\', \'1\')')
				or muoribene(__LINE__.': '.mysqli_error($link),true);
			$accid=mysqli_insert_id($link);
		} else {
			$res=mysqli_query($link,'SELECT * FROM Admins WHERE Email=\''.myesc($link,$_POST['guestaddr']).'\'')
				or muoribene(__LINE__.': '.mysqli_error($link),true);
			if (mysqli_num_rows($res)==0)
				muoribene(__LINE__.': Non esiste alcun account con Email=“'.$_POST['guestaddr'].'”.',true);
			$row=mysqli_fetch_assoc($res);
			$accid=$row['ID'];
		}
		mysqli_query($link,'UPDATE Instances SET GuestID='.$accid.' WHERE ID='.$_POST['id'])
			or muoribene(__LINE__.': '.mysqli_error($link),true);
		$out='<div class="message">La mail è stata inviata correttamente all’indirizzo «'.$to.'».<br>L’account relativo è stato creato/aggiornato correttamente.</div>'.N;
	} else {
		$out='<div class="message">La mail è stata inviata correttamente all’indirizzo di test «'.$to.'».<br>Nessun account è stato creato/aggiornato.<br>Se vuoi abilitare l’invio ai destinatari reali e la creazione o l’aggiornamento degli account relativi devi editare il file di configurazione di Mustard.</div>'.N;
	}
	$insturi=$_POST['insturi'];
} else {
	muoribene('Malformed input.',true);
}

mysqli_close($link);

?>
<!DOCTYPE HTML>
<html lang="it">
<head>
<title>Mustard - Invito admin di «<?php echo(hspech($insturi)); ?>»</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="description" content="Admin pages for Mastodon Help">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link rel="icon" type="image/png" href="imgs/icona-32.png" sizes="32x32">
<link rel="icon" type="image/png" href="imgs/icona-192.png" sizes="192x192">
<link rel="icon" type="image/png" href="imgs/icona-512.png" sizes="512x512">
<link rel="apple-touch-icon-precomposed" href="imgs/icona-180.png">
<link rel="stylesheet" type="text/css" href="css/theme.css?v=<?php echo($cjrand); ?>">
<script language="JavaScript" src="js/menu.js?v=<?php echo($cjrand); ?>"></script>
<script language="JavaScript" src="js/alerta.js?v=<?php echo($cjrand); ?>"></script>
<script language="JavaScript">
<!--
function send() {
	var errors='';
	if (document.getElementById('subject').value.trim()=='') errors+='<li>Destinatario non definito</li>';
	if (document.getElementById('message').value.trim()=='') errors+='<li>Il messaggio è vuoto</li>';
	if (errors!='') {
		alerta('Errore','<ul>'+errors+'</ul>');
		return(false);
	} else {
		document.getElementById('f').submit();
	}
}
//-->
</script>
</head>
<body>

<nav>
<div id="hmenu">
<ul>
<?php echo($menuout); ?>
</ul>
<div class="mtit">Invito admin di «<?php echo(hspech($insturi)); ?>»</div>
<div id="rightdiv">
<img src="imgs/esci.svg" class="rlinks" title="Esci" onclick="document.location.href='logout.php';">
</div>
</div>
</nav>

<div id="popup">
<div id="inpopup">
<div id="popupcont">
...
</div>
</div>
</div>

<!-- <div id="footer">
</div> -->

<div id="fullscreen">
<div id="middlerow">
<?php
echo($out);
?>
</div>
</div>

<div id="debug">
<?php echo($dbg); ?>
</div>

</body>
</html>
