<?php

use function mysqli_real_escape_string as myesc;

require __DIR__.'/transiten.php';
require __DIR__.'/grace.php';
require __DIR__.'/text2html.php';

function tc($key) {
	global $english, $cols;
	if (!$english)
		return($cols[$key]['name']);
	else
		return($cols[$key]['nameEN']);
}

function nully($val,$fem,$filter,$ntext=null) {
	if (!is_null($val)) {
		if ($filter=='strip') {
			return(strip_tags($val,'<a><br><ol><ul><li><p><i><b><strong><em><small>'));
		} elseif ($filter=='htmlchars') {
			return(hspech($val));
		} elseif ($filter=='timestamp') {
			return(gmdate('d/m/Y',round($val)));
		} elseif ($filter=='email') {
			return('<a href="mailto:'.strip_tags($val).'">'.strip_tags($val).'</a>');
		} elseif ($filter=='url') {
			return('<a href="'.strip_tags($val).'" target="_blank">'.strip_tags($val).'</a>');
		} elseif ($filter=='image') {
			return('<img src="'.str_replace('"','\\"',strip_tags($val)).'">');
		} elseif ($filter=='boolt') {
			if ($val)
				return('<span class="good">'.t('Si','Yes').'</span>');
			else
				return('<span class="bad">No</span>');
		} elseif ($filter=='boolf') {
			if ($val)
				return('<span class="bad">'.t('Si','Yes').'</span>');
			else
				return('<span class="good">No</span>');
		} else {
			return($val);
		}
	} else {
		if (is_null($ntext)) {
			if ($fem)
				return('<span class="nully">'.t('Non definita','Not defined').'</span>');
			else
				return('<span class="nully">'.t('Non definito','Not defined').'</span>');
			}
		else {
			return('<span class="nully">'.$ntext.'</span>');
		}
	}
}

function booly($pre,$val,$nottoobad=false,$invcol=false) {
	if ($val) {
		if (!$invcol) {
			$p='<p class="good">';
		} else {
			if (!$nottoobad) {
				$p='<p class="bad">';
			} else {
				$p='<p class="neut">';
			}
		}
		return($p.$pre.t('SI','YES').'</p>');
	} else {
		if (!$invcol) {
			if (!$nottoobad) {
				$p='<p class="bad">';
			} else {
				$p='<p class="neut">';
			}
		} else {
			$p='<p class="good">';
		}
		return($p.$pre.'NO</p>');
	}
}

function trimname($str) {
	return(substr($str,1,strlen($str)-2));
}

// $row deve essere una riga ritornata da una query tipo "SELECT *, ID AS IID FROM Instances WHERE ..."
function dispinst(&$row,&$cols,&$link,&$dlang,&$account,$showcount,$finst,$cinsts,&$graceline) {
	$out='';
	$out.='<table class="bigtab">'.N;
//		$out.='<thead><tr><th class="tdattr">Attributi</th><th>Info</th></thead>'.N;
	$out.='<tbody>'.N;
	$out.='<tr><td colspan="2" class="insthead">'.$row['URI'];
	if ($showcount) $out.=' ('.$finst.'/'.$cinsts.')';
	$out.='</td></tr>'.N;
	$out.='<tr><td colspan="2"><input type="button" value="'.t('Edita','Edit').'" class="btbut" onclick="document.location.href=\'edinst.php?id='.$row['IID'].'\'"></td></tr>'.N;
	if ($account['Level']!='guest') {
		if (!is_null($row['GuestID'])) {
			$out.='<tr><td colspan="2"><input type="button" value="Sollecita, stimola, incalza, incita admin già invitat*" class="btbut" onclick="document.location.href=\'invite.php?id='.$row['IID'].'\'"></td></tr>'.N;
		} elseif (is_null($row['Email']) || trim($row['Email'])=='') {
			$out.='<tr><td colspan="2"><input type="button" value="Impossibile invitare admin: indirizzo e-mail non definito" class="btbut" disabled></td></tr>'.N;
		} else {
			$out.='<tr><td colspan="2"><input type="button" value="Invita admin" class="btbut" onclick="document.location.href=\'invite.php?id='.$row['IID'].'\'"></td></tr>'.N;
		}
	}
	$attr=booly('Viva: ',$row['LastOkCheckTS']>=$graceline,false,false).N;
	$attr.=booly(trimname(tc('Instances.Noxious')).': ',$row['Noxious'],false,true).N;
	$attr.=booly(trimname(tc('Instances.Visible')).': ',$row['Visible']).N;
	/*$attr.=booly(tc('Instances.RegOpen')).': ',$row['RegOpen']).N;
	$attr.=booly(tc('Instances.RegReqApproval').': ',$row['RegReqApproval'],true,true).N;*/
	$sres=mysqli_query($link,'SELECT * FROM InstChecks WHERE InstID='.$row['IID'].' ORDER BY Time DESC')
		or muoribene(mysqli_error($link),true);
	$csres=mysqli_num_rows($sres);
	if ($csres>0) {
		$bene=0;
		while ($srow=mysqli_fetch_assoc($sres)) {
			if ($srow['Status']==1)
				$bene++;
		}
		$width=str_replace(',','.',100/$csres*$bene);
		$attr.='<div class="colsectheader">'.t('Percentuale di risposta ai nostri check','Percentage of response to our checks').' ('.$csres.'): '.round($width,1).'%</div>';
		$attr.='<div class="percbg"><div class="percfg" style="width:'.$width.'%;"></div></div>'.N;
		mysqli_data_seek($sres,0);
		$srow=mysqli_fetch_assoc($sres);
		$attr.='<div class="colsectcont">'.t('Ultimo check','Last check').'<br>('.gmdate('d/m/Y, H:i:s',$srow['Time']).'): '.(($srow['Status']) ? '<span class="good">OK</span>' : '<span class="bad">KO</span>').'</div>';
	} else {
		$attr.='<div class="colsectheader">'.t('Percentuale di risposta ai nostri check','Percentage of response to our checks').'</div>'.N;
		$attr.='<div class="colsectcont nully">'.t('Non disponibile','Unavailable').' (?!?!?!)</div>'.N;
	}
	$attr.='<div class="colsectheader">'.t('Attività delle ultime 12 settimane','Last 12 weeks activity').'</div>'.N;
	$sres=mysqli_query($link,'SELECT SUM(Statuses) AS tstatuses, SUM(Logins) AS tlogins, SUM(Registrations) AS tregs FROM InstActivity WHERE InstID='.$row['IID'])
		or muoribene(mysqli_error($link),true);
	$tot=mysqli_fetch_assoc($sres);
	$sres=mysqli_query($link,'SELECT * FROM InstActivity WHERE InstID='.$row['IID'].' ORDER BY Week DESC')
		or muoribene(mysqli_error($link),true);
	if (mysqli_num_rows($sres)>0) {
		$attr.='<div class="colsectcont">'.t('Stati','Statuses').': '.$tot['tstatuses'].'<br>'.t('Accessi','Logins').': '.$tot['tlogins'].'<br>'.t('Registrazioni','Registrations').': '.$tot['tregs'].'</div>'.N;
		while ($srow=mysqli_fetch_assoc($sres)) {
			$attr.='<div class="colsectcontb">'.gmdate('d/m/Y',$srow['Week']).'</div>'.N;
			($tot['tstatuses']==0) ? $width=0 : $width=str_replace(',','.',100/$tot['tstatuses']*$srow['Statuses']);
			$attr.='<div class="percstatuses" style="width:'.$width.'%;">'.$srow['Statuses'].'&nbsp;'.t('stati','statuses').'</div>'.N;
			($tot['tlogins']==0) ? $width=0 : $width=str_replace(',','.',100/$tot['tlogins']*$srow['Logins']);
			$attr.='<div class="perclogins" style="width:'.$width.'%;">'.$srow['Logins'].'&nbsp;'.t('accessi','logins').'</div>'.N;
			($tot['tregs']==0) ? $width=0 : $width=str_replace(',','.',100/$tot['tregs']*$srow['Registrations']);
			$attr.='<div class="percregs" style="width:'.$width.'%;">'.$srow['Registrations'].'&nbsp;'.t('registrazioni','registrations').'</div>'.N;
		}
	} else {
		$attr.='<div class="colsectcont nully">'.t('Non disponibile','Unavailable').'</div>'.N;
	}
	$attr.='<div class="colsectheader">'.t('Hashtags più usati durante l’ultima settimana','Most used hashtags during last week').'</div>'.N;
	$sres=mysqli_query($link,'SELECT * FROM InstTrends WHERE InstID='.$row['IID'].' ORDER BY Pos ASC')
		or muoribene(mysqli_error($link),true);
	if (mysqli_num_rows($sres)>0) {
		$attr.='<div class="colsectcont"><ol>'.N;
		while ($srow=mysqli_fetch_assoc($sres)) {
			$attr.='<li><a href="'.$srow['URL'].'">'.hspech($srow['Name']).'</a></li>'.N;
		}
		$attr.='</ol></div>'.N;
	} else {
		$attr.='<div class="colsectcont nully">'.t('Non disponibili','Unavailable').'</div>'.N;
	}
	$out.='<tr><td class="tdattr">'.$attr.'</td><td>'.N;
	if ($row['Noxious']>0) {
		if (!is_null($row['NoxReason']) && preg_match('/^\s*$/',$row['NoxReason'])!==1) {
			$out.='<div class="baloored"><p class="ptit">'.t('Questa istanza è stata marcata come nociva in data '.gmdate('d/m/Y (H:i:s)',$row['NoxLastModTS']).' per questo motivo','This instance has been marked as noxious on '.gmdate('d/m/Y (H:i:s)',$row['NoxLastModTS']).' for this reason').'</p>'.text2html($row['NoxReason'],'').'</div>'.N;
		} else {
			$out.='<div class="baloored">'.t('Questa istanza è marcata come nociva, ma il motivo non è specificato','This instance is marked as noxious, but the reason is not specified').'.</div>'.N;
		}
	}
	$out.='<div class="baloo"><span class="field">'.tc('Instances.URI').':</span> <a href="https://'.$row['URI'].'" target="_blank">'.$row['URI'].'</a></div>'.N;
	$out.='<div class="baloo"><span class="field">'.tc('Instances.Title').':</span> '.nully($row['Title'],false,'strip').'</div>'.N;
	$out.='<div class="baloo"><span class="field">'.tc('Instances.Thumb').':</span> '.nully($row['Thumb'],true,'image').'</div>'.N;
	$out.='<div class="baloo"><span class="field">'.tc('Instances.Priority').':</span> '.nully($row['Priority'],true,'strip').'</div>'.N;
	$out.='<div class="baloo"><span class="field">'.tc('Instances.ShortDesc').':</span> '.nully($row['ShortDesc'],true,'strip').'</div>'.N;
	$out.='<div class="baloo"><span class="field">'.tc('Instances.LongDesc').':</span> '.nully($row['LongDesc'],true,'strip').'</div>'.N;
// 'strip' o 'htmlent' per la descrizione nostra?
	$out.='<div class="baloo"><span class="ourfield">'.trimname(tc('Instances.OurDesc')).':</span> '.nully($row['OurDesc'],true,'strip').'</div>'.N;
	$out.='<div class="baloo"><span class="ourfield">'.trimname(tc('Instances.OurDescEN')).':</span> '.nully($row['OurDescEN'],true,'strip').'</div>'.N;
	$out.='<div class="baloo"><span class="ourfield">'.trimname(tc('Localities.Name')).':</span> ';
	if (!is_null($row['LocalityID'])) {
		$sres=mysqli_query($link,'SELECT * FROM Localities WHERE Localities.ID='.$row['LocalityID'])
			or muoribene(mysqli_error($link),true);
		$srow=mysqli_fetch_assoc($sres);
		$out.=hspech($srow['NameOrig']).'</div>'.N;
	} else {
		$out.='<span class="nully">'.t('Non definita','Undefined').'</span></div>'.N;
	}
	$sres=mysqli_query($link,'SELECT * FROM InstLangs LEFT JOIN Languages ON Languages.ID=LangID WHERE InstID='.$row['IID'].' ORDER BY Pos ASC')
		or muoribene(mysqli_error($link),true);
	$out.='<div class="baloo"><span class="field">'.tc('InstLangs').':</span> ';
	if (mysqli_num_rows($sres)>0) {
		$i=0;
		$buf=array();
		while ($srow=mysqli_fetch_assoc($sres)) {
			$i++;
			$buf[]=$i.': '.hspech($srow['Name'.$dlang].' ['.$srow['Code'].']');
		}
		$out.=implode('; ',$buf);
	} else {
		$out.='<span class="nully">'.t('Non definite','Undefined').'</span>';
	}
	$out.='</div>'.N;
	$sres=mysqli_query($link,'SELECT * FROM InstOurLangs LEFT JOIN Languages ON Languages.ID=OurLangID WHERE InstID='.$row['IID'].' ORDER BY Pos ASC')
		or muoribene(mysqli_error($link),true);
	$out.='<div class="baloo"><span class="ourfield">'.trimname(tc('InstOurLangs')).':</span> ';
	if (mysqli_num_rows($sres)>0) {
		$i=0;
		$buf=array();
		while ($srow=mysqli_fetch_assoc($sres)) {
			$i++;
			$buf[]=$i.': '.hspech($srow['Name'.$dlang].' ['.$srow['Code'].']');
		}
		$out.=implode('; ',$buf);
	} else {
		$out.='<span class="nully">'.t('Non definite','Undefined').'</span>';
	}
	($row['OurLangsLock']>0) ? $out.=' <strong>('.t('bloccate','locked').')</strong>' : $out.=' <strong>('.t('non bloccate','not locked').')</strong>';
	$out.='</div>'.N;
	$sres=mysqli_query($link,'SELECT * FROM InstFinancing LEFT JOIN Financing ON Financing.ID=FinID WHERE InstID='.$row['IID'].' ORDER BY Pos ASC')
		or muoribene(mysqli_error($link),true);
	$out.='<div class="baloo"><span class="ourfield">'.trimname(tc('InstFinancing')).':</span> ';
	if (mysqli_num_rows($sres)>0) {
		$i=0;
		$buf=array();
		while ($srow=mysqli_fetch_assoc($sres)) {
			$i++;
			$buf[]=$i.': '.hspech($srow['Type']);
		}
		$out.=implode('; ',$buf);
	} else {
		$out.='<span class="nully">'.t('Non definite','Undefined').'</span>';
	}
	$out.='</div>'.N;
	$sres=mysqli_query($link,'SELECT * FROM InstPolicies LEFT JOIN Policies ON Policies.ID=PolID WHERE InstID='.$row['IID'].' ORDER BY Pos ASC')
		or muoribene(mysqli_error($link),true);
	$out.='<div class="baloo"><span class="ourfield">'.trimname(tc('InstPolicies')).':</span> ';
	if (mysqli_num_rows($sres)>0) {
		$i=0;
		$buf=array();
		while ($srow=mysqli_fetch_assoc($sres)) {
			$i++;
			$buf[]=$i.': '.hspech($srow['Name']);
		}
		$out.=implode('; ',$buf);
	} else {
		$out.='<span class="nully">'.t('Non definite','Undefined').'</span>';
	}
	$out.='</div>'.N;
	$sres=mysqli_query($link,'SELECT * FROM InstTags LEFT JOIN Tags ON Tags.ID=TagID WHERE InstID='.$row['IID'].' ORDER BY Pos ASC')
		or muoribene(mysqli_error($link),true);
	$out.='<div class="baloo"><span class="ourfield">'.trimname(tc('InstTags')).':</span> ';
	if (mysqli_num_rows($sres)>0) {
		$i=0;
		$buf=array();
		while ($srow=mysqli_fetch_assoc($sres)) {
			$i++;
			$buf[]=$i.': '.hspech($srow['Name']);
		}
		$out.=implode('; ',$buf);
	} else {
		$out.='<span class="nully">'.t('Non definite','Undefined').'</span>';
	}
	$out.='</div>'.N;
	if (!is_null($row['GuestID'])) {
		$guestinf='<span class="good">'.t('SI','YES').'</span>';
		$sres=mysqli_query($link,'SELECT Email FROM Admins WHERE ID='.$row['GuestID'])
			or muoribene(__LINE__.': '.mysqli_error($link),true);
		$srow=mysqli_fetch_assoc($sres);
		$guestinf.=' (<a href="mailto:'.$srow['Email'].'">'.$srow['Email'].'</a>)';
	} else {
		$guestinf='<span class="bad">NO</span>';
	}
	$out.='<div class="baloo"><span class="ourfield">'.t('Admin invitat*?','Admin has been invited?').'</span> '.$guestinf.'</div>'.N;
	$out.='<div class="baloo"><span class="ourfield">'.trimname(tc('Instances.LastGuestEdit')).':</span> '.nully($row['LastGuestEdit'],true,'timestamp').'</div>'.N;
	$out.='<div class="baloo"><span class="field">'.tc('Instances.Email').':</span> '.nully($row['Email'],true,'email').'</div>'.N;
	$out.='<div class="baloo"><span class="field">'.tc('Instances.Software').':</span> '.nully($row['Software'],false,'strip').'</div>'.N;
	$out.='<div class="baloo"><span class="field">'.tc('Instances.Version').':</span> '.nully($row['Version'],true,'strip').'</div>'.N;
	$out.='<div class="baloo"><span class="field">'.tc('Instances.UserCount').':</span> '.nully($row['UserCount'],false,'strip').'</div>'.N;
	$out.='<div class="baloo"><span class="field">'.tc('Instances.StatusCount').':</span> '.nully($row['StatusCount'],false,'strip').'</div>'.N;
	$out.='<div class="baloo"><span class="field">'.tc('Instances.DomainCount').':</span> '.nully($row['DomainCount'],false,'strip').'</div>'.N;
	$out.='<div class="baloo"><span class="field">'.tc('Instances.ActiveUsersMonth').':</span> '.nully($row['ActiveUsersMonth'],false,'strip').'</div>'.N;
	$out.='<div class="baloo"><span class="field">'.tc('Instances.ActiveUsersHalfYear').':</span> '.nully($row['ActiveUsersHalfYear'],false,'strip').'</div>'.N;
	$out.='<div class="baloo"><span class="field">'.tc('Instances.RegOpen').':</span> '.nully($row['RegOpen'],false,'boolt').'</div>'.N;
	$out.='<div class="baloo"><span class="field">'.tc('Instances.RegReqApproval').':</span> '.nully($row['RegReqApproval'],false,'boolf').'</div>'.N;
	$out.='<div class="baloo"><span class="field">'.tc('Instances.MaxTootChars').':</span> '.nully($row['MaxTootChars'],false,'strip','500').'</div>'.N;
	$out.='<div class="baloo"><span class="field">'.tc('Instances.AdmAccount').':</span> '.nully($row['AdmAccount'],false,'strip').'</div>'.N;
	$out.='<div class="baloo"><span class="field">'.tc('Instances.AdmDisplayName').':</span> '.nully($row['AdmDisplayName'],false,'strip').'</div>'.N;
	$out.='<div class="baloo"><span class="field">'.tc('Instances.AdmCreatedAt').':</span> '.nully($row['AdmCreatedAt'],true,'timestamp').'</div>'.N;
	$out.='<div class="baloo"><span class="field">'.tc('Instances.AdmURL').':</span> '.nully($row['AdmURL'],true,'url').'</div>'.N;
	$out.='<div class="baloo"><span class="field">'.tc('Instances.AdmAvatar').':</span> '.nully($row['AdmAvatar'],false,'image').'</div>'.N;
	$out.='<div><span class="field">'.tc('Instances.AdmNote').':</span> '.nully($row['AdmNote'],false,'strip').'</div>'.N;
	$out.='</td></tr>'.N;
	$out.='</tbody>'.N;
	$out.='</table>'.N;
	return($out);
}

?>
