<?php

if (!defined('N')) {
	echo('You probably meant <a href="'.preg_replace('/\.php$/','',$_SERVER['REQUEST_URI']).'">this</a>.');
	exit(0);
}

$bt=hrtime(true);
$btu=time();

$dlanguc=strtoupper($dlang);

require '../lib/n2es.php';
require '../lib/grace.php';
require '../lib/fnum.php';
require '../lib/text2html.php';
require '../lib/realfloat.php';// had to resort to this because php 7.3 has a bug: when echoing a float, it uses the decimal separator of the locale that was set with setlocale, making a mess when the separator is different than "." with stuff expecting it to be "."

use function mysqli_real_escape_string as myesc;
/*$dlang='fr';
$dtzbl=['ca'=>'Europe/Madrid','en'=>'Europe/London','es'=>'Europe/Madrid','fr'=>'Europe/Paris','it'=>'Europe/Rome'];
date_default_timezone_set($dtzbl[$dlang]);*/

$lc=localeconv();
$lcc=['decimal_point'=>'.', 'thousands_sep'=>''];

$debug='';
debug(date('r',$btu).N,$debug);
debug('REQUEST_URI: '.$_SERVER['REQUEST_URI'].N,$debug);
debug('$_GET: '.print_r($_GET,true),$debug);
debug('LOCALE: '.setlocale(LC_ALL,0).N,$debug);

// an instance is displayed as "New" if its age, relative to the InsertTS field, is less or equal than this (currently 30 days)
$oldline=30*24*60*60;// todo: do it relative to firstseen?

if (array_key_exists('id',$_GET) && preg_match('/^\d+$/',$_GET['id'])===1) {
	$_GET['id']+=0;
	$single=true;
} else {
	$single=false;
}

//$getc=count($_GET);
//forcing $getc to 1 to never display the explanation of search engine workings
$getc=1;

$minudef=10;
$minumax=4294967295;
$maxudef=30000;
$maxumax=4294967295;
$minaudef=5;
$minaumax=4294967295;
$mincdef='';
$mincmax=16777215;

$link=mysqli_connect($conf['db_host'],$conf['db_user_name'],$conf['db_user_password'],$conf['db_name'],$conf['db_port'],$conf['db_socket']) or muorimeglio(_('Couldn’t connect to database: ').mysqli_connect_error().' ['.mysqli_connect_errno().']',false);
mysqli_set_charset($link,'utf8mb4');

// if and when ... put it soon after </nav> below
/*<div id="popupback">
<div id="fseenhelp" class="dhelp">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
</div>*/

echo('</nav>
<div class="scrwide">
<div class="scrwidein">
<section class="sectcontm">'.N);

if ($single) {
	setfedipact();
	echo('<p><a href="'.$conf['instpath'].'/instances/'.$dlang.'">↑ '._('Go to search').'</a></p>'.N);
	$p=1;
	$que='SELECT * FROM Instances WHERE ID='.$_GET['id'];
} else {
	echo('<img src="'.$prepath.'imgs/helpbutti.svg" id="helpbutt" class="helpb" onmouseover="swhelpi(true);" onmouseout="swhelpi(false);" onclick="swhelp();">
<h3>'._('Instances').'</h3>
<script language="JavaScript">

let helpsh='.(($getc==0) ? 'false' : 'true').';

function swhelp() {
	let hdiv=document.getElementById("help");
	let himg=document.getElementById("helpbutt");
	if (helpsh) {
		hdiv.style.height="0px";
		himg.title="'._('Show introduction').'";
		himg.src="'.$prepath.'imgs/helpbutti.svg";
		helpsh=false;
	} else {
		hdiv.style.height=hdiv.scrollHeight+"px";
		himg.title="'._('Hide introduction').'";
		himg.src="'.$prepath.'imgs/helpbutta.svg";
		helpsh=true;
	}
}

function swhelpi(over) {
	let himg=document.getElementById("helpbutt"), ia;
	if (helpsh) {
		(over) ? ia="i" : ia="a";
	} else {
		(over) ? ia="a" : ia="i";
	}
	himg.src="'.$prepath.'imgs/helpbutt"+ia+".svg";
}

let msshow=true;

function swmetastats() {
	let msdiv=document.getElementById("metastats");
	let msswitch=document.getElementById("msswitch");
	if (msshow) {
		msdiv.style.height="0px";
		msswitch.innerText="'._('Show Threads moderation statistics').'";
		msshow=false;
	} else {
		msdiv.style.height=msdiv.scrollHeight+"px";
		msswitch.innerText="'._('Hide Threads moderation statistics').'";
		msshow=true;
	}
}

function swp(pn) {
	document.curvf.p.value=pn;
	document.curvf.submit();
}

function sethid(obj) {
	if (document.getElementById("cb"+obj).checked)
		document.getElementById(obj).value=1;
	else
		document.getElementById(obj).value=0;
}

function updord() {
	let langsel=document.getElementById("lang"), ordsel=document.getElementById("ord");
	if (langswri.indexOf(langsel.value)>=0)
		ordsel.options[0].innerHTML="'._('Random, recommended first').'";
	else
		ordsel.options[0].innerHTML="'._('Random').'";
}

function nocrit() {
	document.getElementById("lang").selectedIndex=0;
	document.getElementById("desc").value="";
	document.getElementById("minu").value="";
	document.getElementById("maxu").value="";
	document.getElementById("minau").value="";
	document.getElementById("minc").value="";
	document.getElementById("cbexnox").checked=false;
	sethid("exnox");
	document.getElementById("cbexregc").checked=false;
	sethid("exregc");
	document.getElementById("cbinths").checked=false;
	sethid("inths");
	document.getElementById("cbexappr").checked=false;
	sethid("exappr");
	document.getElementById("cbexlcko").checked=false;
	sethid("exlcko");
	updord();
}

function presub() {
	document.getElementById("p").value=1;
	if (document.getElementById("ord").value=="noxd") {
		document.getElementById("cbexnox").checked=false;
		document.getElementById("exnox").value=0;
	}
}

</script>
'.N);

	setfedipact();

	$que='SELECT COUNT(ID) AS Unknown, SUM(UserCount) AS UnknownU FROM Instances WHERE IsMastodon=1 AND Visible=1 AND LastOkCheckTS>='.$graceline.' AND Threads IS NULL';
	if ($cfedipact>0)
		$que.=' AND URI NOT IN ('.$fedipact['uris_me'].')';
	$res=tquery($que,__LINE__);
	$row=mysqli_fetch_assoc($res);
	$metastats['unknown']=['instances'=>$row['Unknown'], 'users'=>nulltozero($row['UnknownU'])];

	$que='SELECT COUNT(ID) AS Suspending, SUM(UserCount) AS SuspendingU FROM Instances WHERE IsMastodon=1 AND Visible=1 AND LastOkCheckTS>='.$graceline;
	if ($cfedipact>0)
		$que.=' AND (Threads="suspended" OR URI IN ('.$fedipact['uris_me'].'))';
	else
		$que.=' AND Threads="suspended"';
	$res=tquery($que,__LINE__);
	$row=mysqli_fetch_assoc($res);
	$metastats['suspending']=['instances'=>$row['Suspending'], 'users'=>nulltozero($row['SuspendingU'])];

	$res=tquery('SELECT COUNT(ID) AS Silencing, SUM(UserCount) AS SilencingU FROM Instances WHERE IsMastodon=1 AND Visible=1 AND LastOkCheckTS>='.$graceline.' AND Threads="limited"',__LINE__);
	$row=mysqli_fetch_assoc($res);
	$metastats['limiting']=['instances'=>$row['Silencing'], 'users'=>nulltozero($row['SilencingU'])];

	$metastats['fpsuspending']['instances']=0;
	$metastats['fpsuspending']['users']=0;
	$metastats['fpliars']['instances']=0;
	$metastats['fpliars']['users']=0;
	$metastats['fpliars']['instlist']=[];
	if ($cfedipact>0) {
		$res=tquery('SELECT COUNT(ID) AS FPSuspending, SUM(UserCount) AS FPSuspendingU FROM Instances WHERE IsMastodon=1 AND Visible=1 AND LastOkCheckTS>='.$graceline.' AND URI IN ('.$fedipact['uris_me'].')',__LINE__);
		$row=mysqli_fetch_assoc($res);
		$metastats['fpsuspending']['instances']=$row['FPSuspending'];
		$metastats['fpsuspending']['users']=nulltozero($row['FPSuspendingU']);
		$res=tquery('SELECT URI, UserCount FROM Instances WHERE IsMastodon=1 AND Visible=1 AND LastOkCheckTS>='.$graceline.' AND Threads="accessible" AND URI IN ('.$fedipact['uris_me'].')',__LINE__);
		while ($row=mysqli_fetch_assoc($res)) {
			$metastats['fpliars']['instances']++;
			$metastats['fpliars']['users']+=nulltozero($row['UserCount']);
			$metastats['fpliars']['instlist'][]=['uri'=>$row['URI'], 'usercount'=>nulltozero($row['UserCount'])];
		}
	}

	$res=tquery('SELECT COUNT(ID) AS tinsts, SUM(UserCount) AS tusers, SUM(StatusCount) AS tstatuses, SUM(ActiveUsersMonth) AS tactusers FROM Instances WHERE IsMastodon=1 AND Visible=1 AND LastOkCheckTS>='.$graceline,__LINE__);
	$row=mysqli_fetch_assoc($res);
	echo(_('<div id="help" class="hiddiv"><p class="intro">This search engine for Mastodon instances is based on a database that gets updated by our crawler every night (CET).</p><p class="intro">Instances are considered new for 30 days after they are discovered.</p><p class="intro">When an instance has not responded to our daily checks for more than 30 days it is no longer considered in statistics and searches and it gets checked only on the first of the month, rather than daily, until it possibly responds again, or until its last succesful check is one year old; in this latter case, from that moment it gets checked only on the first day of each year.</p><p class="intro">“Random ordering” of results varies daily.</p><p class="intro">Default search criteria reflect our fondness for a decentralized and egalitarian Fediverse and our attempt to exclude instances accepting fascist, racist, sexist, ableist or sovereignist contents by marking them as noxious.</p><p class="intro">To report any issue, technical or non-technical, or to suggest instances to exclude according to the above criteria, please contact us at our e-mail address, <span class="magt">masthelp[at]insicuri.net</span>.</p></div>').N);
	printf(_('<p class="intro">We currently count <span class="statd">%s</span> Mastodon instances, with <span class="statd">%s</span> users (<span class="statd">%s</span> active during last month) and <span class="statd">%s</span> published statuses. [<a id="msswitch" onclick="swmetastats();" style="cursor:pointer;">Show Threads moderation statistics</a>]</p>'), fnum($row['tinsts'],$lc), fnum($row['tusers'],$lc), fnum($row['tactusers'],$lc), fnum($row['tstatuses'],$lc));

	//echo '<pre>'.print_r($metastats,true).'</pre>'.N;

	$metastats['known']=[
		'instances'=>$row['tinsts']-$metastats['unknown']['instances'],
		'users'=>$row['tusers']-$metastats['unknown']['users']
	];
	$metastats['known']['iperc']=$metastats['known']['instances']*100/$row['tinsts'];
	$metastats['known']['uperc']=$metastats['known']['users']*100/$row['tusers'];

	$metastats['unknown']['iperc']=$metastats['unknown']['instances']*100/$row['tinsts'];
	$metastats['unknown']['uperc']=$metastats['unknown']['users']*100/$row['tusers'];

	$metastats['suspending']['iperc']=$metastats['suspending']['instances']*100/$row['tinsts'];
	$metastats['suspending']['uperc']=$metastats['suspending']['users']*100/$row['tusers'];
	$metastats['suspending']['kiperc']=$metastats['suspending']['instances']*100/$metastats['known']['instances'];
	$metastats['suspending']['kuperc']=$metastats['suspending']['users']*100/$metastats['known']['users'];

	$metastats['fpsuspending']['iperc']=$metastats['fpsuspending']['instances']*100/$row['tinsts'];
	$metastats['fpsuspending']['uperc']=$metastats['fpsuspending']['users']*100/$row['tusers'];
	$metastats['fpsuspending']['kiperc']=$metastats['fpsuspending']['instances']*100/$metastats['known']['instances'];
	$metastats['fpsuspending']['kuperc']=$metastats['fpsuspending']['users']*100/$metastats['known']['users'];

	$metastats['limiting']['iperc']=$metastats['limiting']['instances']*100/$row['tinsts'];
	$metastats['limiting']['uperc']=$metastats['limiting']['users']*100/$row['tusers'];
	$metastats['limiting']['kiperc']=$metastats['limiting']['instances']*100/$metastats['known']['instances'];
	$metastats['limiting']['kuperc']=$metastats['limiting']['users']*100/$metastats['known']['users'];

	$metastats['notsusporlim']=[
		'instances'=>$row['tinsts']-$metastats['unknown']['instances']-$metastats['suspending']['instances']-$metastats['limiting']['instances'],
		'users'=>$row['tusers']-$metastats['unknown']['users']-$metastats['suspending']['users']-$metastats['limiting']['users']
	];
	$metastats['notsusporlim']['iperc']=$metastats['notsusporlim']['instances']*100/$row['tinsts'];
	$metastats['notsusporlim']['uperc']=$metastats['notsusporlim']['users']*100/$row['tusers'];
	$metastats['notsusporlim']['kiperc']=$metastats['notsusporlim']['instances']*100/$metastats['known']['instances'];
	$metastats['notsusporlim']['kuperc']=$metastats['notsusporlim']['users']*100/$metastats['known']['users'];

	$metastats['susporlim']=[
		'instances'=>$metastats['suspending']['instances']+$metastats['limiting']['instances'],
		'users'=>$metastats['suspending']['users']+$metastats['limiting']['users']
	];
	$metastats['susporlim']['iperc']=$metastats['susporlim']['instances']*100/$row['tinsts'];
	$metastats['susporlim']['uperc']=$metastats['susporlim']['users']*100/$row['tusers'];
	$metastats['susporlim']['kiperc']=$metastats['susporlim']['instances']*100/$metastats['known']['instances'];
	$metastats['susporlim']['kuperc']=$metastats['susporlim']['users']*100/$metastats['known']['users'];

	debug('fpsuspending: instances: '.$metastats['fpsuspending']['instances'].'; users: '.$metastats['fpsuspending']['users'].N.'fpliars: instances: '.$metastats['fpliars']['instances'].'; users: '.$metastats['fpliars']['users'].N,$debug);
	if (count($metastats['fpliars']['instlist'])>0)
		foreach ($metastats['fpliars']['instlist'] as $val)
			debug($val['uri'].': '.$val['usercount'].N,$debug);

	echo
'<div id="metastats" class="hiddiv">

<script language="JavaScript">swmetastats();</script>

<h3>'._('Threads moderation statistics').'</h3>

<p class="introe">'._('These statistics on the status of Threads moderation are based on the list of moderated instances, which is accessible only on some instances, and on the list of instances adhering to the <a href="https://fedipact.online/" target="_blank">Anti-Meta Fedi Pact</a>.').'</p>

<h4>'._('Statistics on the state of Threads moderation<br>related to instances on which it is known').'</h4>

<table class="ms_leg_tab"><tr><td class="ms_suspending"></td><td class="ms_leg_td">&nbsp;'._('Instances suspending Threads').': '.fnum($metastats['suspending']['instances'],$lc).' / '.fnum($metastats['known']['instances'],$lc).' ('.fnum($metastats['suspending']['kiperc'],$lc,2).'%)</td></tr></table>
<table class="ms_leg_tab"><tr><td class="ms_limiting"></td><td class="ms_leg_td">&nbsp;'._('Instances limiting Threads').': '.fnum($metastats['limiting']['instances'],$lc).' / '.fnum($metastats['known']['instances'],$lc).' ('.fnum($metastats['limiting']['kiperc'],$lc,2).'%)</td></tr></table>
<table class="ms_leg_tab"><tr><td class="ms_suspending"></td><td class="ms_leg_td">+</td><td class="ms_limiting"></td><td class="ms_leg_td">&nbsp;'._('Instances suspending or limiting Threads').': '.fnum($metastats['suspending']['instances']+$metastats['limiting']['instances'],$lc).' / '.fnum($metastats['known']['instances'],$lc).' ('.fnum($metastats['suspending']['kiperc']+$metastats['limiting']['kiperc'],$lc,2).'%)</td></tr></table>
<table class="ms_leg_tab"><tr><td class="ms_notsusporlim"></td><td class="ms_leg_td">&nbsp;'._('Instances not suspending or limiting Threads').': '.fnum($metastats['notsusporlim']['instances'],$lc).' / '.fnum($metastats['known']['instances'],$lc).' ('.fnum($metastats['notsusporlim']['kiperc'],$lc,2).'%)</td></tr></table>

<table class="ms_cont"><tr><td class="ms_suspending" style="width:'.rf($metastats['suspending']['kiperc']).'%"></td><td class="ms_limiting" style="width:'.rf($metastats['limiting']['kiperc']).'%"></td><td class="ms_notsusporlim" style="width:'.rf($metastats['notsusporlim']['kiperc']).'%"></td></tr></table>

<div class="sep"></div>

<table class="ms_leg_tab"><tr><td class="ms_suspending_u"></td><td class="ms_leg_td">&nbsp;'._('Users on instances suspending Threads').': '.fnum($metastats['suspending']['users'],$lc).' / '.fnum($metastats['known']['users'],$lc).' ('.fnum($metastats['suspending']['kuperc'],$lc,2).'%)</td></tr></table>
<table class="ms_leg_tab"><tr><td class="ms_limiting_u"></td><td class="ms_leg_td">&nbsp;'._('Users on instances limiting Threads').': '.fnum($metastats['limiting']['users'],$lc).' / '.fnum($metastats['known']['users'],$lc).' ('.fnum($metastats['limiting']['kuperc'],$lc,2).'%)</td></tr></table>
<table class="ms_leg_tab"><tr><td class="ms_suspending_u"></td><td class="ms_leg_td">+</td><td class="ms_limiting_u"></td><td class="ms_leg_td">&nbsp;'._('Users on instances suspending or limiting Threads').': '.fnum($metastats['suspending']['users']+$metastats['limiting']['users'],$lc).' / '.fnum($metastats['known']['instances'],$lc).' ('.fnum($metastats['suspending']['kuperc']+$metastats['limiting']['kuperc'],$lc,2).'%)</td></tr></table>
<table class="ms_leg_tab"><tr><td class="ms_notsusporlim_u"></td><td class="ms_leg_td">&nbsp;'._('Users on instances not suspending or limiting Threads').': '.fnum($metastats['notsusporlim']['users'],$lc).' / '.fnum($metastats['known']['users'],$lc).' ('.fnum($metastats['notsusporlim']['kuperc'],$lc,2).'%)</td></tr></table>

<table class="ms_cont"><tr><td class="ms_suspending_u" style="width:'.rf($metastats['suspending']['kuperc']).'%"></td><td class="ms_limiting_u" style="width:'.rf($metastats['limiting']['kuperc']).'%"></td><td class="ms_notsusporlim_u" style="width:'.rf($metastats['notsusporlim']['kuperc']).'%"></td></tr></table>

<!--
<h4>'._('Statistics on the state of Threads<br>moderation related to all instances.').'</h4>

<table class="ms_leg_tab"><tr><td class="ms_suspending"></td><td class="ms_leg_td">&nbsp;'._('Instances suspending Threads').': '.fnum($metastats['suspending']['instances'],$lc).' / '.fnum($row['tinsts'],$lc).' ('.fnum($metastats['suspending']['iperc'],$lc,2).'%)</td></tr></table>
<table class="ms_leg_tab"><tr><td class="ms_limiting"></td><td class="ms_leg_td">&nbsp;'._('Instances limiting Threads').': '.fnum($metastats['limiting']['instances'],$lc).' / '.fnum($row['tinsts'],$lc).' ('.fnum($metastats['limiting']['iperc'],$lc,2).'%)</td></tr></table>
<table class="ms_leg_tab"><tr><td class="ms_suspending"></td><td class="ms_leg_td">+</td><td class="ms_limiting"></td><td class="ms_leg_td">&nbsp;'._('Instances suspending or limiting Threads').': '.fnum($metastats['suspending']['instances']+$metastats['limiting']['instances'],$lc).' / '.fnum($row['tinsts'],$lc).' ('.fnum($metastats['suspending']['iperc']+$metastats['limiting']['iperc'],$lc,2).'%)</td></tr></table>
<table class="ms_leg_tab"><tr><td class="ms_notsusporlim"></td><td class="ms_leg_td">&nbsp;'._('Instances not suspending or limiting Threads').': '.fnum($metastats['notsusporlim']['instances'],$lc).' / '.fnum($row['tinsts'],$lc).' ('.fnum($metastats['notsusporlim']['iperc'],$lc,2).'%)</td></tr></table>
<table class="ms_leg_tab"><tr><td class="ms_unknown"></td><td class="ms_leg_td">&nbsp;'._('Instances whose Threads moderation status is unknown').': '.fnum($metastats['unknown']['instances'],$lc).' / '.fnum($row['tinsts'],$lc).' ('.fnum($metastats['unknown']['iperc'],$lc,2).'%)</td></tr></table>

<table class="ms_cont"><tr><td class="ms_suspending" style="width:'.rf($metastats['suspending']['iperc']).'%"></td><td class="ms_limiting" style="width:'.rf($metastats['limiting']['iperc']).'%"></td><td class="ms_notsusporlim" style="width:'.rf($metastats['notsusporlim']['iperc']).'%"></td><td class="ms_unknown" style="width:'.$metastats['unknown']['iperc'].'%"></td></tr></table>

<div class="sep"></div>

<table class="ms_leg_tab"><tr><td class="ms_suspending_u"></td><td class="ms_leg_td">&nbsp;'._('Users on instances suspending Threads').': '.fnum($metastats['suspending']['users'],$lc).' / '.fnum($row['tusers'],$lc).' ('.fnum($metastats['suspending']['uperc'],$lc,2).'%)</td></tr></table>
<table class="ms_leg_tab"><tr><td class="ms_limiting_u"></td><td class="ms_leg_td">&nbsp;'._('Users on instances limiting Threads').': '.fnum($metastats['limiting']['users'],$lc).' / '.fnum($row['tusers'],$lc).' ('.fnum($metastats['limiting']['uperc'],$lc,2).'%)</td></tr></table>
<table class="ms_leg_tab"><tr><td class="ms_suspending_u"></td><td class="ms_leg_td">+</td><td class="ms_limiting_u"></td><td class="ms_leg_td">&nbsp;'._('Users on instances suspending or limiting Threads').': '.fnum($metastats['suspending']['users']+$metastats['limiting']['users'],$lc).' / '.fnum($row['tusers'],$lc).' ('.fnum($metastats['suspending']['uperc']+$metastats['limiting']['uperc'],$lc,2).'%)</td></tr></table>
<table class="ms_leg_tab"><tr><td class="ms_notsusporlim_u"></td><td class="ms_leg_td">&nbsp;'._('Users on instances not suspending or limiting Threads').': '.fnum($metastats['notsusporlim']['users'],$lc).' / '.fnum($row['tusers'],$lc).' ('.fnum($metastats['notsusporlim']['uperc'],$lc,2).'%)</td></tr></table>
<table class="ms_leg_tab"><tr><td class="ms_unknown_u"></td><td class="ms_leg_td">&nbsp;'._('Users on instances whose Threads mod. status is unknown').': '.fnum($metastats['unknown']['users'],$lc).' / '.fnum($row['tusers'],$lc).' ('.fnum($metastats['unknown']['uperc'],$lc,2).'%)</td></tr></table>

<table class="ms_cont"><tr><td class="ms_suspending_u" style="width:'.rf($metastats['suspending']['uperc']).'%"></td><td class="ms_limiting_u" style="width:'.rf($metastats['limiting']['uperc']).'%"></td><td class="ms_notsusporlim_u" style="width:'.rf($metastats['notsusporlim']['uperc']).'%"></td><td class="ms_unknown_u" style="width:'.rf($metastats['unknown']['uperc']).'%"></td></tr></table>

-->

</div>'.N;

	if ((array_key_exists('exnox',$_GET) && $_GET['exnox']=='1') || !array_key_exists('exnox',$_GET)) {
		$_GET['cbexnox']=' checked';
		$_GET['exnox']=1;
	} else {
		$_GET['cbexnox']='';
		$_GET['exnox']=0;
	}

	if ((array_key_exists('exregc',$_GET) && $_GET['exregc']=='1') || !array_key_exists('exregc',$_GET)) {
		$_GET['cbexregc']=' checked';
		$_GET['exregc']=1;
	} else {
		$_GET['cbexregc']='';
		$_GET['exregc']=0;
	}

//	if ((array_key_exists('inths',$_GET) && $_GET['inths']=='1') || !array_key_exists('inths',$_GET)) {
	if (array_key_exists('inths',$_GET) && $_GET['inths']=='1') {
		$_GET['cbinths']=' checked';
		$_GET['inths']=1;
	} else {
		$_GET['cbinths']='';
		$_GET['inths']=0;
	}

	if (array_key_exists('exappr',$_GET) && $_GET['exappr']=='1') {
		$_GET['cbexappr']=' checked';
		$_GET['exappr']=1;
	} else {
		$_GET['cbexappr']='';
		$_GET['exappr']=0;
	}

	if (array_key_exists('exlcko',$_GET) && $_GET['exlcko']=='1') {
		$_GET['cbexlcko']=' checked';
		$_GET['exlcko']=1;
	} else {
		$_GET['cbexlcko']='';
		$_GET['exlcko']=0;
	}

	$res=tquery('SELECT Languages.ID AS Lid, Code, CONCAT(Name'.$dlanguc.', \' [\', Code, \'] (\', COUNT(Languages.ID), \')\') AS Txt FROM InstOurLangs LEFT JOIN Instances ON Instances.ID=InstOurLangs.InstID LEFT JOIN Languages ON Languages.ID=OurLangID WHERE InstOurLangs.Pos=1 AND Instances.IsMastodon=1 AND Instances.Visible=1 AND Instances.LastOkCheckTS>='.$graceline.' GROUP BY Languages.ID ORDER BY Languages.Name'.$dlanguc.' ASC',__LINE__);
	while ($row=mysqli_fetch_assoc($res))
		$sellangs[$row['Code']]=$row;
	if (array_key_exists('lang',$_GET)) {
		if (preg_match('#^[0-9]+$#',$_GET['lang'])===1)
			($_GET['lang']+0>5000000) ? $get['lang']=0 : $_GET['lang']=$_GET['lang']+0;
		else
			$_GET['lang']=0;
	} else {
		foreach ($langs as $key=>$val)
			if (array_key_exists($key,$sellangs)) {
				debug('LANG: '.$key.N,$debug);
				$_GET['lang']=$sellangs[$key]['Lid'];
				break;
			}
		if (!isset($_GET['lang']))
			$_GET['lang']=$sellangs['en']['Lid'];
	}

	if (array_key_exists('desc',$_GET) && preg_match('#^.+$#',$_GET['desc'])===1)
		$_GET['desc']=trim(n2es($_GET['desc']));
	else
		$_GET['desc']='';
	if (mb_strlen($_GET['desc'])>64) $_GET['desc']='';

	ckgnum('minu',$minudef,$minumax);
	ckgnum('maxu',$maxudef,$maxumax);
	if (is_int($_GET['maxu']) && is_int($_GET['minu']) && $_GET['maxu']<$_GET['minu']) $_GET['maxu']=$_GET['minu'];
	ckgnum('minau',$minaudef,$minaumax);
	ckgnum('minc',$mincdef,$mincmax);

	$order=[
		'rand'=>['t'=>_('Random'), 'q'=>'Instances.RPos ASC'],
		'invold'=>['t'=>_('By users’ involvement (active users / users), descending'), 'q'=>'(Instances.ActiveUsersMonth / Instances.UserCount) DESC'],
		'invola'=>['t'=>_('By users’ involvement (active users / users), ascending'), 'q'=>'(Instances.ActiveUsersMonth / Instances.UserCount) ASC'],
		'fseend'=>['t'=>_('By date and time of first sighting, descending'), 'q'=>'Instances.FirstSeen DESC'],
		'fseena'=>['t'=>_('By date and time of first sighting, ascending'), 'q'=>'Instances.FirstSeen ASC'],
		'tusersd'=>['t'=>_('By number of users, descending'), 'q'=>'Instances.UserCount DESC'],
		'tusersa'=>['t'=>_('By number of users, ascending'), 'q'=>'Instances.UserCount ASC'],
		'ausersd'=>['t'=>_('By number of active users, descending'), 'q'=>'Instances.ActiveUsersMonth DESC'],
		'ausersa'=>['t'=>_('By number of active users, ascending'), 'q'=>'Instances.ActiveUsersMonth ASC'],
		'checksd'=>['t'=>_('By responsiveness to our checks, descending'), 'q'=>'(Instances.OkChecks / Instances.TotChecks) DESC, Instances.TotChecks DESC'],
		'checksa'=>['t'=>_('By responsiveness to our checks, ascending'), 'q'=>'(Instances.OkChecks / Instances.TotChecks) ASC, Instances.TotChecks ASC'],
		'charsd'=>['t'=>_('By available characters per post, descending'), 'q'=>'Instances.MaxTootChars DESC'],
		'charsa'=>['t'=>_('By available characters per post, ascending'), 'q'=>'Instances.MaxTootChars ASC'],
		'noxd'=>['t'=>_('Noxious first (switches off “Exclude noxious”)'), 'q'=>'Instances.Noxious DESC']
	];
	if (!array_key_exists('ord',$_GET) || !array_key_exists($_GET['ord'],$order))
		$_GET['ord']='rand';
//	$res=tquery('SELECT COUNT(Instances.ID) AS Recomm FROM Instances LEFT JOIN InstOurLangs ON InstOurLangs.InstID=Instances.ID WHERE InstOurLangs.OurLangID='.$_GET['lang'].' AND Instances.IsMastodon=1 AND Instances.Visible=1 AND Instances.LastOkCheckTS>='.$graceline.' AND InstOurLangs.Pos=1 AND Instances.Priority>127',__LINE__);
	$res=tquery('SELECT InstOurLangs.OurLangID FROM Instances LEFT JOIN InstOurLangs ON InstOurLangs.InstID=Instances.ID WHERE Instances.IsMastodon=1 AND Instances.Visible=1 AND Instances.LastOkCheckTS>='.$graceline.' AND InstOurLangs.Pos=1 AND Instances.Priority>127 GROUP BY InstOurLangs.OurLangID',__LINE__);
	$langswri=[];// langs with recommended instances
	while ($row=mysqli_fetch_assoc($res))
		$langswri[]=$row['OurLangID'];
	if (count($langswri)>0)
		array_unshift($langswri,0);
	if (in_array($_GET['lang'],$langswri))
		$order['rand']=['t'=>_('Random, recommended first'), 'q'=>'Instances.Priority DESC, Instances.RPos ASC'];

	$p=1;
	if (array_key_exists('p',$_GET) && preg_match('#^[0-9]+$#',$_GET['p'])===1) $p=$_GET['p']+0;

	echo('<h3>'._('Search instances').'</h3>
	<form method="get" id="curvf" name="curvf">
	<input name="exnox" type="hidden" value="'.$_GET['exnox'].'">
	<input name="exregc" type="hidden" value="'.$_GET['exregc'].'">
	<input name="exappr" type="hidden" value="'.$_GET['exappr'].'">
	<input name="exlcko" type="hidden" value="'.$_GET['exlcko'].'">
	<input name="inths" type="hidden" value="'.$_GET['inths'].'">
	<input name="lang" type="hidden" value="'.$_GET['lang'].'">
	<input name="desc" type="hidden" value="'.htmlentities($_GET['desc']).'">
	<input name="minu" type="hidden" value="'.$_GET['minu'].'">
	<input name="maxu" type="hidden" value="'.$_GET['maxu'].'">
	<input name="minau" type="hidden" value="'.$_GET['minau'].'">
	<input name="minc" type="hidden" value="'.$_GET['minc'].'">
	<input name="ord" type="hidden" value="'.$_GET['ord'].'">
	<input name="p" type="hidden" value="'.$p.'">
	</form>'.N);

	($_GET['lang']==0) ? $selected=' selected' : $selected='';
	echo '<form method="get" id="searchf" class="sdbox" onsubmit="presub();">
	<div class="sdtit">'._('Search criteria').'</div>
	<div class="sddesc">'._('Show instances where...').'</div>
	<div class="sdrow">
	<div class="sdlabel"><label for="lang" title="'._('Include only instances where the most used language is the one selected here').'">'._('Most used language is').'</label></div>
	<div class="sdinput">
	<select id="lang" name="lang" class="sselect" onchange="updord();">
	<option value="0"'.$selected.'>'._('Any').'</option>'.N;

	foreach ($sellangs as $row) {
		($_GET['lang']==$row['Lid']) ? $selected=' selected' : $selected='';
		echo '<option value="'.$row['Lid'].'"'.$selected.'>'.$row['Txt'].'</option>'.N;
	}

	echo '</select>
	</div>
	</div>
	<script language="JavaScript">
	let langswri=["'.implode('","',$langswri).'"];
	</script>
	<div class="sdrow">
	<div class="sdlabel"><label for="desc" title="'._('Include only instances whose URI, name or description (short or long) contains the specified expression').'">'._('URI, name or descriptions contain').'</label></div>
	<div class="sdinput"><input type="text" id="desc" name="desc" class="sinput" maxlength="64" value="'.hspech($_GET['desc']).'" autofocus></div>
	</div>

	<div class="sdrow">
	<div class="sdlabel"><label for="minu" title="'._('Include only instances which have at least this number of users [set to empty to disable this criterion]').'">'._('Users are at least').'</label></div>
	<div class="sdinput"><input type="number" id="minu" name="minu" min="0" max="'.$minumax.'" class="sinput" value="'.$_GET['minu'].'"></div>
	</div>
	<div class="sdrow">
	<div class="sdlabel"><label for="maxu" title="'._('Include only instances which have at most this number of users [set to empty to disable this criterion]').'">'._('Users are at most').'</label></div>
	<div class="sdinput"><input type="number" id="maxu" name="maxu" min="0" max="'.$maxumax.'" class="sinput" value="'.$_GET['maxu'].'"></div>
	</div>
	<div class="sdrow">
	<div class="sdlabel"><label for="minau" title="'._('Include only instances which had at least this number of active users during the last 30 days [set to empty to disable this criterion]').'">'._('Active users are at least').'</label></div>
	<div class="sdinput"><input type="number" id="minau" name="minau" min="0" max="'.$minaumax.'" class="sinput" value="'.$_GET['minau'].'"></div>
	</div>
	<div class="sdrow">
	<div class="sdlabel"><label for="minc" title="'._('Include only instances on which the number of available characters per post is at least this [set to empty to disable this criterion]').'">'._('Max. chars per post are at least').'</label></div>
	<div class="sdinput"><input type="number" id="minc" name="minc" min="0" max="'.$mincmax.'" class="sinput" value="'.$_GET['minc'].'"></div>
	</div>
	<div class="hrd"></div>
	<div class="sdrow">
	<div class="sdlabel"><label for="cbexnox" title="'._('Exclude noxious instances').'">'._('Exclude if noxious').'</label></div>
	<div class="sdinput">
	<input type="checkbox" class="sckbox" id="cbexnox" value="1"'.$_GET['cbexnox'].' onchange="sethid(\'exnox\');">
	<input type="hidden" id="exnox" name="exnox" value="'.$_GET['exnox'].'">
	</div>
	</div>
	<div class="sdrow">
	<div class="sdlabel"><label for="cbexregc" title="'._('Exclude instances which don’t accept new registrations').'">'._('Exclude if registrations are closed').'</label></div>
	<div class="sdinput">
	<input type="checkbox" class="sckbox" id="cbexregc" value="1"'.$_GET['cbexregc'].' onchange="sethid(\'exregc\');">
	<input type="hidden" id="exregc" name="exregc" value="'.$_GET['exregc'].'">
	</div>
	</div>
	<div class="sdrow">
	<div class="sdlabel"><label for="cbinths" title="'._('Include only instances which surely have Meta’s Threads *suspended*').'">'._('Include only if Threads is surely <i>suspended</i>').'</label></div>
	<div class="sdinput">
	<input type="checkbox" class="sckbox" id="cbinths" value="1"'.$_GET['cbinths'].' onchange="sethid(\'inths\');">
	<input type="hidden" id="inths" name="inths" value="'.$_GET['inths'].'">
	</div>
	</div>
	<div class="sdrow">
	<div class="sdlabel"><label for="cbexappr" title="'._('Exclude instances on which admin approval is required for registration').'">'._('Exclude if registration requires approval').'</label></div>
	<div class="sdinput">
	<input type="checkbox" class="sckbox" id="cbexappr" value="1"'.$_GET['cbexappr'].' onchange="sethid(\'exappr\');">
	<input type="hidden" id="exappr" name="exappr" value="'.$_GET['exappr'].'">
	</div>
	</div>
	<div class="sdrow">
	<div class="sdlabel"><label for="cbexlcko" title="'._('Exclude instances which didn’t respond to last check').'">'._('Exclude if offline on last check').'</label></div>
	<div class="sdinput">
	<input type="checkbox" class="sckbox" id="cbexlcko" value="1"'.$_GET['cbexlcko'].' onchange="sethid(\'exlcko\');">
	<input type="hidden" id="exlcko" name="exlcko" value="'.$_GET['exlcko'].'">
	</div>
	</div>

	<div class="sdtitb">'._('Order of results').'</div>

	<div class="sdcrow">
	<select id="ord" name="ord" class="sselect100">'.N;
	foreach ($order as $key=>$buf) {
		($key!=$_GET['ord']) ? $selected='' : $selected=' selected';
		echo '<option value="'.$key.'"'.$selected.'>'.$buf['t'].'</option>'.N;
	}
	echo('</select>
	</div>

	<div class="sdlrow">
	<input type="submit" value="'._('Search').'" class="ssubmit">
	</div>

	<div class="sdcrow">
	<input type="button" class="litbut" value="'._('Set criteria to include all instances').'" onclick="nocrit();">
	</div>

	<div class="sdlcrow">
	<input type="button" class="litbut" value="'._('Reset to default criteria').'" onclick="document.location.href=document.location.href.replace(/\\?.*$/,\'\');">
	</div>

	<input type="hidden" id="p" name="p" value="'.$p.'">
	</form>

	<script language="JavaScript">
	swhelp();
	</script>'.N);

	$joins=[];
	$wheres=[];
	$wheres[]='Instances.IsMastodon=1 AND Instances.Visible=1 AND Instances.LastOkCheckTS>='.$graceline;
	if ($_GET['exnox']==1) $wheres[]='Instances.Noxious=0';
	if ($_GET['exregc']==1) $wheres[]='Instances.RegOpen=1';
	if ($_GET['exappr']==1) $wheres[]='Instances.RegReqApproval=0';
	if ($_GET['exlcko']==1) $wheres[]='Instances.WasLastCheckOk=1';
	/*if ($_GET['exlcko']==1) {
		$joins[]='LEFT JOIN InstChecks AS InstChecks ON InstChecks.InstID=Instances.ID AND InstChecks.Time=(SELECT MAX(InstChecks.Time) AS MaxTime FROM InstChecks WHERE InstChecks.InstID=Instances.ID)';
		$wheres[]='InstChecks.Status=1';
	}*/
	if ($_GET['inths']==1) {
		if ($cfedipact>0)
			$wheres[]='Instances.Threads="suspended" OR Instances.ID IN ('.implode(', ',$fedipact['instids']).')';
		else
			$wheres[]='Instances.Threads="suspended"';
	}
	if ($_GET['lang']>0) {
		$joins[]='LEFT JOIN InstOurLangs ON InstOurLangs.InstID=Instances.ID';
		$wheres[]='(InstOurLangs.OurLangID='.$_GET['lang'].' AND InstOurLangs.Pos=1)';
	}
	$buf=preg_replace('#%#','\%',myesc($link,$_GET['desc']));
	if ($_GET['desc']!='') $wheres[]='(Instances.URI LIKE "%'.$buf.'%" OR Instances.Title LIKE "%'.$buf.'%" OR Instances.ShortDesc LIKE "%'.$buf.'%" OR Instances.LongDesc LIKE "%'.$buf.'%")';
	if ($_GET['minu']!='') $wheres[]='Instances.UserCount>='.$_GET['minu'];
	if ($_GET['maxu']!='') $wheres[]='Instances.UserCount<='.$_GET['maxu'];
	if ($_GET['minau']!='') $wheres[]='Instances.ActiveUsersMonth>='.$_GET['minau'];
	if ($_GET['minc']!='' && $_GET['minc']!='""') $wheres[]='Instances.MaxTootChars>='.$_GET['minc'];
	$joins=implode(' ',$joins);
	$wheres='WHERE '.implode(' AND ',$wheres);
	$que='SELECT * FROM Instances '.$joins.' '.$wheres.' ORDER BY '.$order[$_GET['ord']]['q'];
}

debug('MAIN QUERY: «'.$que.'»'.N,$debug);
$res=tquery($que,__LINE__);
$itot=mysqli_num_rows($res);
debug('RESULTS: '.$itot.N,$debug);
/*if ($itot==0) {
	echo(_('No instance matches with the search criteria.').N.'</section>'.N.'</div>'.N.'</div>'.N.'</body>'.N.'</html>'.N);
	exit(0);
}*/

$ipp=10;// istanze per pagina
$if=$ipp*($p-1);
if ($if>=$itot) {
	$if=0;
	$p=1;
}
$ptot=ceil($itot/$ipp);
($p!=$ptot) ? $il=$if+$ipp : $il=$itot;

$dfmt=datefmt_create($blang,IntlDateFormatter::MEDIUM,IntlDateFormatter::NONE,'UTC',IntlDateFormatter::GREGORIAN);
$defmt=datefmt_create($blang,IntlDateFormatter::SHORT,IntlDateFormatter::MEDIUM,'UTC',IntlDateFormatter::GREGORIAN);
$wrfss=1602633600;// we record FirstSeen since October 14, 2020, 0:0:0 UTC
$wrfsstxt=datefmt_format($dfmt,$wrfss).' UTC';

mysqli_data_seek($res,$if);
while ($if<$il && $row=mysqli_fetch_assoc($res)) {
	$if++;
	$out='<div class="ihead"><a href="https://'.hspech($row['URI']).'" target="_blank" title="'._('Go to instance').'">'.hspech($row['URI']).'</a>';
	if (!$single) $out.=' <a href="'.$conf['instpath'].'/instances?id='.$row['ID'].'" title="'._('Direct link to this instance’s card').'">('.$if.'/'.$itot.')</a>';
	$out.='</div>'.N;
	($if<$il) ? $out.='<div class="ibody">'.N : $out.='<div class="ibodylast">'.N;
	$rres=tquery('SELECT CONCAT(Languages.Name'.$dlanguc.'," (",Languages.Code,")") AS Lang FROM InstOurLangs LEFT JOIN Languages ON Languages.ID=InstOurLangs.OurLangID WHERE InstOurLangs.InstID='.$row['ID'].' ORDER BY InstOurLangs.Pos ASC',__LINE__);
	$buf=[];
	while ($rrow=mysqli_fetch_assoc($rres))
		$buf[]=hspech($rrow['Lang']);
	($row['Thumb']=='unavailable') ? $thumb=$prepath.'imgs/InstThumbUnavailable.svg' : $thumb=$row['Thumb'];
	$out.='<div class="iimgc"><a href="https://'.hspech($row['URI']).'" target="_blank" title="'._('Go to instance').'"><img class="iimg" src="'.$thumb.'"></a>';
//	if (!is_null($row['Priority'])) $out.='<img src="'.$prepath.'imgs/featured-it.svg" class="ifeat">';
	if (!is_null($row['Priority'])) $out.='<div class="dfeat">'._('Recommended').'</div>';
	if ($row['Thumb']=='unavailable' && $row['WasLastCheckOk']==1) $out.='<div class="unavmsg">'._('It seems like this instance’s server thumbnail’s URL points to a non existent file. This is usually easily fixable by the instance’s admin(s) by uploading again the image to their server. Note that the change won’t be displayed here before the nightly automatic update of this instance’s infos occurs.').'</div>';
	$out.='</div>'.N;
	$out.='<div class="icol">'.N;
	$out.='<div><span class="ilab">'._('Name').'</span> <a href="https://'.hspech($row['URI']).'" target="_blank" title="'._('Go to instance').'">'.nully(hspech($row['Title'])).'</a></div>'.N;
	/*$out.='<div><span class="ilab">'._('Consigliata').'</span> ';
	(!is_null($row['Priority'])) ? $out.='<span class="ivgood">'._('Si!').'</span>' : $out.=_('No');
	$out.='</div>'.N;*/
	$out.='<div><span class="ilab">'._('Languages').'</span> '.nully(implode(', ',$buf)).'</div>'.N;
	$out.='<div><span class="ilab">'._('Users').'</span> '.nully(fnum($row['UserCount'],$lc)).'</div>'.N;
	$out.='<div><span class="ilab">'._('Active users (last month)').'</span> '.nully(fnum($row['ActiveUsersMonth'],$lc)).'</div>'.N;
	$out.='<div><span class="ilab">'._('Active users (last six months)').'</span> '.nully(fnum($row['ActiveUsersHalfYear'],$lc)).'</div>'.N;
	$out.='<div><span class="ilab">'._('Characters per post (max)').'</span> ';
	if (nullemp($row['MaxTootChars']))
		$out.='<span class="null">500</span>';
	else
		$out.=fnum($row['MaxTootChars'],$lc);
	$out.='</div>'.N;
	$out.='<div><span class="ilab">'._('Known instances').'</span> '.nully(fnum($row['DomainCount'],$lc)).'</div>'.N;
	$out.='</div>'.N;

	$out.='<div class="icol">'.N;
	if (is_null($row['FirstSeen'])) {// can't currently happen, but we put it there in any event
		$fdate='<span class="null">'._('Not available{singular}').'</span>';
	} elseif ($row['FirstSeen']<$wrfss) {
		$fdate='<span class="null">'._('Before').' '.$wrfsstxt.'</span> <span class="tip" title="'._('We record this value only since').' '.$wrfsstxt.' ;-)">[?]</span>';
	} else {
		$fdate=datefmt_format($dfmt,$row['FirstSeen']).' UTC';
	}
	$out.='<div><span class="ilab">'._('First sight').'</span> '.$fdate.'</div>'.N;
	(is_null($row['LastOkCheckTS'])) ? $fdate='<span class="null">'._('Not available{singular}').'</span>' : $fdate=datefmt_format($dfmt,$row['LastOkCheckTS']).' UTC';
	$out.='<div><span class="ilab">'._('Last successful check').'</span> '.$fdate.'</div>'.N;
	$out.='<div><span class="ilab">'._('Noxious').'</span> ';
	($row['Noxious']==1) ? $out.='<span class="ibad">'._('Yes (see why below)').'</span>' : $out.='<span class="igood">'._('No').'</span>';
	$out.='</div>'.N;
	$out.='<div><span class="ilab">'._('New').'</span> ';
	($btu-$row['InsertTS']<=$oldline) ? $out.='<span class="ivgood">'._('Yes!').'</span>' : $out.=_('No');
	$out.='</div>'.N;
	$software='';
	if (!is_null($row['Software'])) $software.=ucfirst($row['Software']);
	if (!is_null($row['Version'])) $software.=' '.$row['Version'];
	$out.='<div><span class="ilab">'._('Software').'</span> '.nully(hspech($software)).'</div>'.N;

	$out.='<div><span class="ilab">'._('Registrations').'</span> ';
	($row['RegReqApproval']==1) ? $buf=' <span class="iwarn">('._('by admin approval').')</span>' : $buf='';
	if (nullemp($row['RegOpen']))
		$out.='<span class="null">'._('Not available{singular}').'</span>';
	elseif ($row['RegOpen']==1)
		$out.='<span class="igood">'._('Open').'</span>'.$buf;
	else
		$out.='<span class="iwarn">'._('Closed').'</span>';
	$out.='</div>'.N;
	$out.='<div><span class="ilab">'._('E-mail').'</span> ';
	if (nullemp($row['Email']))
		$out.='<span class="null">'._('Not available{singular}').'</span>';
	else
		$out.='<a href="mailto:'.$row['Email'].'">'.$row['Email'].'</a>';
	$out.='</div>'.N;
	$out.='</div>'.N;

	$out.='<div><span class="ilab">'._('Meta’s Threads moderation').'</span> ';
	if (in_array($row['ID'],$fedipact['instids'])) {
		$out.=_('Threads is <i>suspended</i>').', '._('according to the <a href="https://fedipact.online/" target="_blank">Anti-Meta Fedi Pact</a> list');
		if (is_null($row['Threads']))
			$out.=', '._('but it’s currently impossible to verify it because this instance’s list of moderated instances is not accessible').'.';
		elseif ($row['Threads']=='accessible')
			$out.=', '._('but it appears to be <i>accessible</i>, instead').', '._('according to this instance’s list of moderated instances').'.';
		elseif ($row['Threads']=='suspended')
			$out.=', '._('and also').' '._('according to this instance’s list of moderated instances').'.';
		elseif ($row['Threads']=='limited')
			$out.=', '._('but it appears to be only <i>limited</i>, instead').', '._('according to this instance’s list of moderated instances').'.';
		else
			$out.='.';
	} elseif (is_null($row['Threads'])) {
		$out.=_('<i>Unknown</i> (this instance is not listed in the <a href="https://fedipact.online/" target="_blank">Anti-Meta Fedi Pact</a> list), and its list of moderated instances is not accessible').'.';
	} elseif ($row['Threads']=='accessible') {
		$out.=_('Threads is neither <i>suspended</i> nor <i>limited</i>').', '._('according to this instance’s list of moderated instances').'.';
	} elseif ($row['Threads']=='suspended') {
		$out.=_('Threads is <i>suspended</i>').', '._('according to this instance’s list of moderated instances').'.';
	} elseif ($row['Threads']=='limited') {
		$out.=_('Threads is <i>limited</i>').', '._('according to this instance’s list of moderated instances').'.';
	} else {
		$out.=_('<i>Unknown value</i>').': «'.htmlentities($row['Threads']).'»; '._('please contact masthelp[at]insicuri.net').'.';
	}
	$out.='</div>'.N;

	$out.='<div><span class="ilab">'._('Most used hashtags (last week)').'</span> ';
	$rres=tquery('SELECT * FROM InstTrends WHERE InstID='.$row['ID'].' ORDER BY Pos ASC',__LINE__);
	if (mysqli_num_rows($rres)>0) {
		$buf=[];
		while ($rrow=mysqli_fetch_assoc($rres))
			$buf[]='<a href="'.hspech($rrow['URL']).'" target="_blank">'.hspech($rrow['Name']).'</a>';
		$out.=implode(', ',$buf);
	} else {
		$out.='<span class="null">'._('Not available{plural}').'</span>';
	}
	$out.='</div>'.N;

	if ($row['Noxious'])
		$out.='<div><div class="noxlab">'._('Why we consider this instance noxious').'</div><div class="noxreas">'.text2html($row['NoxReason'],'<span class="null">'._('Not available{singular}').'</span>').'</div></div>'.N;

	$out.='<div><div class="idlab">'._('Short description').'</div><div class="idesc">'.nully(text2html($row['ShortDesc'],null)).'</div></div>'.N;
	$out.='<div><div class="idlab">'._('Long description').'</div><div class="idesc">'.nully(strip($row['LongDesc'],"{$row['URI']}/about/")).'</div></div>'.N;

	$out.='<div><div class="idlab">'._('Instance rules').'</div><div class="idesc">';
	$rres=tquery('SELECT Text FROM InstRules WHERE InstID='.$row['ID'],__LINE__);
	if (mysqli_num_rows($rres)>0) {
		$out.='<ol class="nobott">'.N;
		while ($rrow=mysqli_fetch_assoc($rres))
			$out.='<li>'.hspech($rrow['Text']).'</li>'.N;// no strip, do hspech, because instance rules don’t support html nor markdown in mastodon
		$out.='</ol>'.N;
	} else {
		$out.='<span class="null">'._('Not available{plural}').'</span>';
	}
	$out.='</div></div>'.N;

	$out.='<div><div class="idlab">'._('Moderated instances').' <span class="tip" title="'._('Each instance in this list is linked to our card only if it runs Mastodon and it is not dead.').'">[?]</span></div><div class="idesc">';
	if ($row['PublicBlocksList']==1) {
		$sevmap=['silence'=>_('limited'), 'suspend'=>_('suspended')];
		$rres=tquery("SELECT Domain, Severity, Comment, ID, IsMastodon, LastOkCheckTS FROM InstBlocks LEFT JOIN Instances ON URI=Domain WHERE InstID={$row['ID']} ORDER BY Domain ASC",__LINE__);
		if (mysqli_num_rows($rres)>0) {
			$out.='<ol class="nobott">'.N;
			while ($rrow=mysqli_fetch_assoc($rres)) {
				if (!is_null($rrow['ID']) && $rrow['IsMastodon']+0==1 && $rrow['LastOkCheckTS']+0>=$graceline) {
					$aopen="<a href=\"?id={$rrow['ID']}\" target=\"_blank\">";
					$aclose='</a>';
				} else {
					$aopen='';
					$aclose='';
				}
				$out.="<li>{$aopen}<strong>{$rrow['Domain']}</strong>{$aclose}: {$sevmap[$rrow['Severity']]}";
				if (!is_null($rrow['Comment'])) $out.=' ('._('reason').': '.hspech($rrow['Comment']).')';// no strip, do hspech, because moderated instances comments don’t support html nor markdown in mastodon
				$out.='</li>'.N;
			}
			$out.='</ol>'.N;
		} else {
			$out.='<span class="null">'._('None').'</span>';
		}
	} else {
		$out.='<span class="null">'._('Not available{plural}').'</span>';
	}
	$out.='</div></div>'.N;

	$out.='<div><div class="idlab">'._('Instances certainly moderating this instance').' <span class="tip" title="'._('Each instance in this list is linked to our card only if it runs Mastodon and it is not dead.').' '._('On many instances the list of instances they moderate is not public, so it is unlikely that this list is complete.').'">[?]</span></div><div class="idesc">';
	$sevmap=['silence'=>_('limitation'), 'suspend'=>_('suspension')];
	$rres=tquery("SELECT Severity, Comment, ID, URI, IsMastodon, LastOkCheckTS FROM InstBlocks LEFT JOIN Instances ON ID=InstID WHERE Domain=\"{$row['URI']}\" ORDER BY URI ASC",__LINE__);
	if (mysqli_num_rows($rres)>0) {
		$out.='<ol class="nobott">'.N;
		while ($rrow=mysqli_fetch_assoc($rres)) {
			if ($rrow['IsMastodon']+0==1 && $rrow['LastOkCheckTS']+0>=$graceline) {
				$aopen="<a href=\"?id={$rrow['ID']}\" target=\"_blank\">";
				$aclose='</a>';
			} else {
				$aopen='';
				$aclose='';
			}
			$out.="<li>{$aopen}<strong>{$rrow['URI']}</strong>{$aclose}: {$sevmap[$rrow['Severity']]}</li>\n";
//			if (!is_null($rrow['Comment'])) $out.=' ('._('reason').': '.hspech($rrow['Comment']).')';// no strip, do hspech, because moderated instances comments don’t support html nor markdown in mastodon
//			$out.='</li>'.N;
		}
		$out.='</ol>'.N;
	} else {
		$out.='<span class="null">'._('None').'</span>';
	}
	$out.='</div></div>'.N;

	$admacc=nully(null);
	$thumb=$prepath.'imgs/AdmAccThumbUnavailable.svg';
	if (!is_null($row['AdmAccount']) && $row['AdmAccount']!='OPTED OUT') {
		$admacc='<a href="https://' . hspech($row['URI']) . '/@' . hspech($row['AdmAccount']) . '" target="_blank">' . hspech($row['AdmAccount']) . '@' . hspech($row['URI']) . '</a>';
		if ($row['AdmAvatar']!='unavailable') $thumb=$row['AdmAvatar'];
	} elseif ($row['AdmAccount']=='OPTED OUT') {
		$admacc='<span class="null">'._('Opted out of search engines indexing').'</span>';
	}
	(is_null($row['AdmCreatedAt'])) ? $fdate='<span class="null">'._('Not available{singular}').'</span>' : $fdate=datefmt_format($dfmt,$row['AdmCreatedAt']).' UTC';
	$out.='<div class="abox"><img class="aimg" src="'.$thumb.'"><div><span class="ilab">'._('Admin account').'</span> '.$admacc.'</div><div><span class="ilab">'._('Date of creation').'</span> '.$fdate.'</div><div><span class="ilab">'._('Display name').'</span> '.nully(hspech($row['AdmDisplayName'])).'</div><div><div class="idlab">'._('Bio').'</div><div class="inote">'.nully(strip($row['AdmNote'],"{$row['URI']}/@{$row['AdmAccount']}/")).'</div>'.N;
	$out.='</div></div>';

	$out.='<div class="ghost"><div class="idlab">'._('Statistics').'</div><div class="istat">';

	$rres=tquery('SELECT COUNT(InstID) AS cnt, SUM(Statuses) AS tstatuses, SUM(Logins) AS tlogins, SUM(Registrations) AS tregs FROM InstActivity WHERE InstID='.$row['ID'],__LINE__);
	$out.='<div class="dida">'._('Last 12 weeks activity');
	if (mysqli_num_rows($rres)>0) {
		$rrow=mysqli_fetch_assoc($rres);
		if ($rrow['cnt']>0)
			$out.=' ('._('totals:').' '.$rrow['tstatuses'].' '._('statuses').', '.$rrow['tlogins'].' '._('logins').', '.$rrow['tregs'].' '._('registrations').')';
	}
	$out.='</div>'.N;
	$rres=tquery('SELECT * FROM InstActivity WHERE InstID='.$row['ID'].' ORDER BY Week ASC',__LINE__);
	$out.='<table class="abar"><tr>';
	$tot=mysqli_num_rows($rres);
	if ($tot>0) {
		while ($rrow=mysqli_fetch_assoc($rres))
			// initials for Statuses, Logins, Registrations
			$out.='<td width="'.(100/$tot).'%">'._('S').': '.$rrow['Statuses'].'<br>'._('L').': '.$rrow['Logins'].'<br>'._('R').': '.$rrow['Registrations'].'</td>';
	} else {
		$out.='<td><span class="null">'._('Not available{singular}').'</span></td>';
	}
	$out.='</tr></table>'.N;

	$rres=tquery('SELECT * FROM InstChecks WHERE InstID='.$row['ID'].' ORDER BY Time DESC LIMIT 0,8',__LINE__);
	$tot=mysqli_num_rows($rres);
	$buf=[];
	while ($rrow=mysqli_fetch_assoc($rres)) $buf[]=$rrow;
	$out.='<div class="dida">'._('Last checks (green: OK; red: KO)').'</div><table class="cbar"><tr>';
	for ($i=$tot-1; $i>=0; $i--) {
		$out.='<td width="'.(100/$tot).'%"';
		if ($buf[$i]['Status']==1) $out.=' class="cbarok"';
		$out.='>'.datefmt_format($defmt,$buf[$i]['Time']).' UTC</td>';
	}
	$out.='</tr></table>'.N;
	$out.='<div class="dida100">'._('Succesful checks').': '.$row['OkChecks'].'/'.$row['TotChecks'].' ('.round($row['OkChecks']*100/$row['TotChecks'], 2).'%)</div>'.N;

	$out.='</div></div>'.N;

	$out.='</div>'.N;
	echo($out);
}
mysqli_close($link);

echo('</section>'.N);

if ($ptot>1) {
	echo('<div id="footmarg"></div>'.N);
	echo('<div id="bmenu">'.N);
	$pnav='<table id="pnav"><tr>';
	if ($p>1)
		$pnav.='<td><img src="'.$prepath.'imgs/nav_first.svg" onclick="swp(1);" class="hov" title="'._('Go to first page').'"></td><td><img src="'.$prepath.'imgs/nav_prev.svg" onclick="swp('.($p-1).');" class="hov" title="'._('Go to previous page').'"></td>';
	else
		$pnav.='<td><img src="'.$prepath.'imgs/nav_first_off.svg"></td><td><img src="'.$prepath.'imgs/nav_prev_off.svg"></td>';
	//$pnav.='<td>Page '.$p.'/'.$ptot.'</td>';
	$pnav.='<td><select id="pagesel" onchange="swp(this.value);" title="'._('Select page').'">'.N;
	for ($i=1; $i<=$ptot; $i++) {
		($i!=$p) ? $selected='' : $selected=' selected';
		$li=$i*$ipp;
		if ($li>$itot) $li=$itot;
		//page number prefix
		$pnav.='<option value="'.$i.'"'.$selected.'>'._('Page').' '.$i.' '._('of').' '.$ptot.' ('._('instances').': '.(($i-1)*$ipp+1).'-'.$li.'/'.$itot.')</option>'.N;
	}
	$pnav.='</select></td>'.N;
	if ($p<$ptot)
		$pnav.='<td><img src="'.$prepath.'imgs/nav_next.svg" onclick="swp('.($p+1).');" class="hov" title="'._('Go to next page').'"></td><td><img src="'.$prepath.'imgs/nav_last.svg" onclick="swp('.($ptot).');" class="hov" title="'._('Go to last page').'"></td>';
	else
		$pnav.='<td><img src="'.$prepath.'imgs/nav_next_off.svg"></td><td><img src="'.$prepath.'imgs/nav_last_off.svg"></td>';
	$pnav.='</tr></table>'.N;
	echo($pnav);
	echo('</div>'.N);
}

echo('</div>'.N);
echo('</div>'.N);

debug('TOTAL RENDERING TIME: '.hrte($bt).N,$debug);
if (array_key_exists('debug',$_GET) && $_GET['debug']=='1') echo('<!--'.N.'--- DEBUG INFO ---'.N.$debug.'//-->'.N);


// functions

function setfedipact() {
	global $link, $graceline, $fedipact, $cfedipact;
	$fedipact=['uris'=>[], 'uris_me'=>[], 'instids'=>[]];
	$fedipactfp='../clitools/fedipact.list';
	$fedipact['uris']=@file($fedipactfp,FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);
	if (!is_array($fedipact['uris'])) {
		debug('WARNING: could not open «'.$fedipactfp.'».'.N,$debug);
		$fedipact['uris']=[];
	}
	$cfedipact=count($fedipact['uris']);
	if ($cfedipact>0) {
		foreach ($fedipact['uris'] as $val)
			$fedipact['uris_me'][]=myesc($link,$val);
		$fedipact['uris_me']='"'.implode('", "',$fedipact['uris_me']).'"';
		//echo '<pre>'.print_r($fedipact,true).'</pre>'.N;
		$res=tquery('SELECT ID, URI FROM Instances WHERE IsMastodon=1 AND Visible=1 AND LastOkCheckTS>='.$graceline.' AND URI IN ('.$fedipact['uris_me'].')', __LINE__);
		$fedipact['uris']=[];
		$fedipact['uris_me']=[];
		while ($row=mysqli_fetch_assoc($res)) {
			$fedipact['uris'][]=$row['URI'];
			$fedipact['instids'][]=$row['ID'];
		}
		foreach ($fedipact['uris'] as $val)
			$fedipact['uris_me'][]=myesc($link,$val);
		$fedipact['uris_me']='"'.implode('", "',$fedipact['uris_me']).'"';
		$cfedipact=count($fedipact['instids']);
	} else {
		$fedipact['uris_me']='';
	}
}

function debug($msg,&$debug) {
	if (array_key_exists('debug',$_GET) && $_GET['debug']=='1')
		$debug.=$msg;
}

function ckgnum($key,$def,$max) {
	if (array_key_exists($key,$_GET)) {
		$_GET[$key]=trim($_GET[$key]);
		if (preg_match('#^\d+$#',$_GET[$key])===1) {
			$_GET[$key]=$_GET[$key]+0;
			if ($_GET[$key]>$max) $_GET[$key]=$max;
		} elseif ($_GET[$key]!='') {
			$_GET[$key]=$def;
		}
	} else {
		$_GET[$key]=$def;
	}
}

function nullemp($inp) {
	if (is_null($inp) || preg_match('/^\s*$/',$inp)===1) return true;
	return false;
}

function nulltozero($inp) {
	if (is_null($inp)) return 0;
	return $inp;
}

function hspech($str) {
	if (nullemp($str)) return(null);
	return htmlspecialchars($str,ENT_QUOTES|ENT_HTML5,'UTF-8');
}

function muorimeglio($msg,$close) {
	global $link;
	if ($close)
		mysqli_close($link);
	echo('<p>'.$msg.'</p>'.N.'</section>'.N.'</div>'.N.'</div>'.N.'</body>'.N);
	exit(2);
}

function nully($str) {
	// "Not available" in singular form - translators, please omit "{singular}" from translation,
	// it's there just to diversify this "Not available" from the next one
	if (nullemp($str)) return('<span class="null">'._('Not available{singular}').'</span>');
	return $str;
}

function nullyp($str) {
	// "Not available" in plural form - translators, please omit "{plural}" from translation,
	// it's there just to diversify this "Not available" from the previous one
	if (nullemp($str)) return('<span class="null">'._('Not available{plural}').'</span>');
	return $str;
}

function strip($str,$uri) {
	if (nullemp($str)) return(null);
	//echo '<pre>'.$str.'</pre>';
	$str=preg_replace(['#^\s*#m','#[\r\n]#'],['',' '],$str);// strip all spaces from empty lines, then all carriage return and new line chars
	$str=preg_replace('#<br\s*/>#i','<br>',$str);// convert all "<br />" to "<br>"
	$str=preg_replace('#<a\s+[^>]*></a>#i','',$str);
	$str=preg_replace('#<a\s+[^>]*href="(?![a-zA-Z]+://)([^"]+)#i','<a href="https://'.$uri.'$1',$str);// if an href is not preceded by a protocol scheme, it's relative ...
	$str=str_ireplace('</a><a','</a> <a',$str);// always put at least one space between links
	//$str=preg_replace(['#</p><br>#i','#</li><br>#i','#</ul><br>#i','#<ul><br>#i'],['</p>','</li>','</ul>','<ul>'],$str);
	$str=preg_replace(['#<b>#i','#</b>#i','#<i>#i','#</i>#i'],['<strong>','</strong>','<em>','</em>'],$str);
	$str=preg_replace(['#\s*(&nbsp;)*\s*</p>#is','#<p[^>]*>\s*</p>#is'],['</p>',''],$str);
	$str=preg_replace(['#<p[^>]*>(.*)</p>#Ui','#<div[^>]>(.*)</div>#Ui'],['<br><br>$1<br><br>','<br><br>$1<br><br>'],$str);
	$str=strip_tags($str,'<a><br><ol><ul><li><strong><em><small><img><h1><h2><h3><h4><h5><h6>');
	$str=preg_replace('#<([^>]*)\s(style|class)="[^"]*"([^>]*)>#i','<$1$3>',$str);
	$str=preg_replace(['#<h[1-6][^>]*>#i','#</h[1-6]>#i'],['<br><br><span class="exh">','</span><br><br>'],$str);
	$str=preg_replace(['#<([ou])l[^>]*>#i','#</([ou])l>#i'],['<br><br><$1l class="nobott">','</$1l><br><br>'],$str);
	$str=preg_replace(['#\s+$#','#<br>\s+<br>#i','#^(<br>)+#i','#(<br>){3,}#i','#(<br>)+$#i','#</([ou])l>\s*(<br>)+#i','#</li>\s*(<br>)+#i'],['','<br><br>','','<br><br>','','</$1l><br>','</li><br>'],$str);
	// this part below is to try and assign the css "nobott" css class to a possible closing <ol>/<ul>, to avoid the useless and UGLY last bottom-margin :-)
	$str=preg_replace(['#<ol[^>]*>(.*)</ol>$#i','#<ul[^>]*>(.*)</ul>$#i'],['<ol class="nobott">$1</ol>','<ul class="nobott">$1</ul>'],$str);
	return $str;
}

function hrte($bt) {
	if (function_exists('bcdiv'))
		return bcdiv(bcsub(hrtime(true),$bt,9),1000000000,9);
	else
		return (hrtime(true)-$bt)/1000000000;
}

function tquery($query,$line) {
	global $link, $debug;
	$bt=hrtime(true);
	//usleep(rand(10000,1050000));
	$res=mysqli_query($link,$query) or muorimeglio('Error on line '.$line.': '.mysqli_error($link),true);
	debug(sprintf('%f secs. for query «'.str_replace('%','%%',$query).'»'.N,hrte($bt)),$debug);
	return $res;
}

?>
