<?php

use function mysqli_real_escape_string as myesc;

// serve per i vari strftime - quando ci sarà versione inglese andrebbe impostata a en_EN.utf8, alla bisogna
setlocale(LC_ALL,'it_IT.utf8');

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(strftime('%c',$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">Si</span>');
			else
				return('<span class="bad">No</span>');
		} elseif ($filter=='boolf') {
			if ($val)
				return('<span class="bad">Si</span>');
			else
				return('<span class="good">No</span>');
		} else {
			return($val);
		}
	} else {
		if (is_null($ntext)) {
			if ($fem)
				return('<span class="nully">Non definita</span>');
			else
				return('<span class="nully">Non definito</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.'SI</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) {
	$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="Edita" 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 (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(trimname($cols['Instances.Blacklisted']['name']).': ',$row['Blacklisted'],false,true).N;
	$attr.=booly(trimname($cols['Instances.New']['name']).': ',$row['New'],true).N;
	$attr.=booly(trimname($cols['Instances.Good']['name']).': ',$row['Good']).N;
	$attr.=booly(trimname($cols['Instances.Chosen']['name']).': ',$row['Chosen']).N;
	$attr.=booly(trimname($cols['Instances.Visible']['name']).': ',$row['Visible']).N;
	/*$attr.=booly($cols['Instances.RegOpen']['name'].': ',$row['RegOpen']).N;
	$attr.=booly($cols['Instances.RegReqApproval']['name'].': ',$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">Percentuale di risposta ai nostri check ('.$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">Ultimo check '.strftime('%e %b %Y, %T',$srow['Time']).': '.(($srow['Status']) ? '<span class="good">OK</span>' : '<span class="bad">KO</span>').'</div>';
	} else {
		$attr.='<div class="colsectheader">Percentuale di risposta ai nostri check</div>'.N;
		$attr.='<div class="colsectcont nully">Non disponibile (?!?!?!)</div>'.N;
	}
	$attr.='<div class="colsectheader">Attività delle ultime 12 settimane</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">Stati: '.$tot['tstatuses'].'<br>Accessi: '.$tot['tlogins'].'<br>Registrazioni: '.$tot['tregs'].'</div>'.N;
		while ($srow=mysqli_fetch_assoc($sres)) {
			$attr.='<div class="colsectcontb">'.strftime('%e %b %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;stati</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;accessi</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;registrazioni</div>'.N;
		}
	} else {
		$attr.='<div class="colsectcont nully">Non disponibile</div>'.N;
	}
	$attr.='<div class="colsectheader">Hashtags più usati durante l’ultima settimana</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">Non disponibili</div>'.N;
	}
	$out.='<tr><td class="tdattr">'.$attr.'</td><td>'.N;
	if ($row['Blacklisted']>0) {
		$sres=mysqli_query($link,'SELECT * FROM Blacklist WHERE Domain=\''.myesc($link,$row['URI']).'\'')
			or muoribene(mysqli_error($link),true);
		if (mysqli_num_rows($sres)>0) {
			$srow=mysqli_fetch_assoc($sres);
			if (!is_null($srow['PublicComment']) && preg_match('/^\s*$/',$srow['PublicComment'])!==1) {
				$out.='<div class="baloo">Questa istanza è blacklistata per questo motivo: '.hspech($srow['PublicComment']).'</div>'.N;
			} else {
				$out.='<div class="baloo">Questa istanza è blacklistata, ma nella blacklist non è specificato il motivo.</div>'.N;
			}
		} else {
			$out.='<div class="baloo">Questa istanza risulta blacklistata nella tabella delle istanze, ma nella tabella “Blacklist” non è presente: probabilmente è stata rimossa dalla tabella “Blacklist” e il crawler non l’ha ancora aggiornata.</div>'.N;
		}
	}
	$out.='<div class="baloo"><span class="field">'.$cols['Instances.URI']['name'].':</span> <a href="https://'.$row['URI'].'" target="_blank">'.$row['URI'].'</a></div>'.N;
	$out.='<div class="baloo"><span class="field">'.$cols['Instances.Title']['name'].':</span> '.nully($row['Title'],false,'strip').'</div>'.N;
	$out.='<div class="baloo"><span class="field">'.$cols['Instances.Thumb']['name'].':</span> '.nully($row['Thumb'],true,'image').'</div>'.N;
	$out.='<div class="baloo"><span class="field">'.$cols['Instances.ShortDesc']['name'].':</span> '.nully($row['ShortDesc'],true,'strip').'</div>'.N;
	$out.='<div class="baloo"><span class="field">'.$cols['Instances.LongDesc']['name'].':</span> '.nully($row['LongDesc'],true,'strip').'</div>'.N;
// 'strip' o 'htmlent' per la descrizione nostra?
	$out.='<div class="baloo"><span class="ourfield">'.trimname($cols['Instances.OurDesc']['name']).':</span> '.nully($row['OurDesc'],true,'strip').'</div>'.N;
	$out.='<div class="baloo"><span class="ourfield">'.trimname($cols['Instances.OurDescEN']['name']).':</span> '.nully($row['OurDescEN'],true,'strip').'</div>'.N;
	$out.='<div class="baloo"><span class="ourfield">'.trimname($cols['Localities.Name']['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">Non definita</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);
	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.='<div class="baloo"><span class="field">'.$cols['InstLangs']['name'].':</span> '.implode('; ',$buf).'</div>'.N;
	} else {
		$out.='<div class="baloo"><span class="field">'.$cols['InstLangs']['name'].':</span> <span class="nully">Non definite</span></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);
	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.='<div class="baloo"><span class="ourfield">'.trimname($cols['InstOurLangs']['name']).':</span> '.implode('; ',$buf);
	} else {
		$out.='<div class="baloo"><span class="ourfield">'.trimname($cols['InstOurLangs']['name']).':</span> <span class="nully">Non definite</span>';
	}
	($row['OurLangsLock']>0) ? $out.=' <strong>(bloccate)</strong>' : $out.=' <strong>(non bloccate)</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);
	if (mysqli_num_rows($sres)>0) {
		$i=0;
		$buf=array();
		while ($srow=mysqli_fetch_assoc($sres)) {
			$i++;
			$buf[]=$i.': '.hspech($srow['Type']);
		}
		$out.='<div class="baloo"><span class="ourfield">'.trimname($cols['InstFinancing']['name']).':</span> '.implode('; ',$buf).'</div>'.N;
	} else {
		$out.='<div class="baloo"><span class="ourfield">'.trimname($cols['InstFinancing']['name']).':</span> <span class="nully">Non definite</span></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);
	if (mysqli_num_rows($sres)>0) {
		$i=0;
		$buf=array();
		while ($srow=mysqli_fetch_assoc($sres)) {
			$i++;
			$buf[]=$i.': '.hspech($srow['Name']);
		}
		$out.='<div class="baloo"><span class="ourfield">'.trimname($cols['InstPolicies']['name']).':</span> '.implode('; ',$buf).'</div>'.N;
	} else {
		$out.='<div class="baloo"><span class="ourfield">'.trimname($cols['InstPolicies']['name']).':</span> <span class="nully">Non definite</span></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);
	if (mysqli_num_rows($sres)>0) {
		$i=0;
		$buf=array();
		while ($srow=mysqli_fetch_assoc($sres)) {
			$i++;
			$buf[]=$i.': '.hspech($srow['Name']);
		}
		$out.='<div class="baloo"><span class="ourfield">'.trimname($cols['InstTags']['name']).':</span> '.implode('; ',$buf).'</div>'.N;
	} else {
		$out.='<div class="baloo"><span class="ourfield">'.trimname($cols['InstTags']['name']).':</span> <span class="nully">Non definite</span></div>'.N;
	}
	if (!is_null($row['GuestID'])) {
		$guestinf='<span class="good">SI</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">Admin invitat*?</span> '.$guestinf.'</div>'.N;
	$out.='<div class="baloo"><span class="ourfield">'.trimname($cols['Instances.LastGuestEdit']['name']).':</span> '.nully($row['LastGuestEdit'],true,'timestamp').'</div>'.N;
	$out.='<div class="baloo"><span class="field">'.$cols['Instances.Email']['name'].':</span> '.nully($row['Email'],true,'email').'</div>'.N;
	$out.='<div class="baloo"><span class="field">'.$cols['Instances.Software']['name'].':</span> '.nully($row['Software'],false,'strip').'</div>'.N;
	$out.='<div class="baloo"><span class="field">'.$cols['Instances.Version']['name'].':</span> '.nully($row['Version'],true,'strip').'</div>'.N;
	$out.='<div class="baloo"><span class="field">'.$cols['Instances.UserCount']['name'].':</span> '.nully($row['UserCount'],false,'strip').'</div>'.N;
	$out.='<div class="baloo"><span class="field">'.$cols['Instances.StatusCount']['name'].':</span> '.nully($row['StatusCount'],false,'strip').'</div>'.N;
	$out.='<div class="baloo"><span class="field">'.$cols['Instances.DomainCount']['name'].':</span> '.nully($row['DomainCount'],false,'strip').'</div>'.N;
	$out.='<div class="baloo"><span class="field">'.$cols['Instances.ActiveUsersMonth']['name'].':</span> '.nully($row['ActiveUsersMonth'],false,'strip').'</div>'.N;
	$out.='<div class="baloo"><span class="field">'.$cols['Instances.ActiveUsersHalfYear']['name'].':</span> '.nully($row['ActiveUsersHalfYear'],false,'strip').'</div>'.N;
	$out.='<div class="baloo"><span class="field">'.$cols['Instances.RegOpen']['name'].':</span> '.nully($row['RegOpen'],false,'boolt').'</div>'.N;
	$out.='<div class="baloo"><span class="field">'.$cols['Instances.RegReqApproval']['name'].':</span> '.nully($row['RegReqApproval'],false,'boolf').'</div>'.N;
	$out.='<div class="baloo"><span class="field">'.$cols['Instances.MaxTootChars']['name'].':</span> '.nully($row['MaxTootChars'],false,'strip','500').'</div>'.N;
	$out.='<div class="baloo"><span class="field">'.$cols['Instances.AdmAccount']['name'].':</span> '.nully($row['AdmAccount'],false,'strip').'</div>'.N;
	$out.='<div class="baloo"><span class="field">'.$cols['Instances.AdmDisplayName']['name'].':</span> '.nully($row['AdmDisplayName'],false,'strip').'</div>'.N;
	$out.='<div class="baloo"><span class="field">'.$cols['Instances.AdmCreatedAt']['name'].':</span> '.nully($row['AdmCreatedAt'],true,'timestamp').'</div>'.N;
	$out.='<div class="baloo"><span class="field">'.$cols['Instances.AdmURL']['name'].':</span> '.nully($row['AdmURL'],true,'url').'</div>'.N;
	$out.='<div class="baloo"><span class="field">'.$cols['Instances.AdmAvatar']['name'].':</span> '.nully($row['AdmAvatar'],false,'image').'</div>'.N;
	$out.='<div><span class="field">'.$cols['Instances.AdmNote']['name'].':</span> '.nully($row['AdmNote'],false,'strip').'</div>'.N;
	$out.='</td></tr>'.N;
	$out.='</tbody>'.N;
	$out.='</table>'.N;
	return($out);
}

?>
