<?php
// all'inizio di ogni controller/vista GET
header('Cache-Control: private, max-age=0, must-revalidate');
header_remove('Pragma');      // se lo usavi per compatibilità legacy
header('Expires: 0');

const SAFE_URL_LIMIT = 1900; // sotto ~2KB sei sicuro ovunque

// Harden session handling (retrocompatibile)
$__is_https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');
@ini_set('session.use_strict_mode', '1');
@ini_set('session.use_only_cookies', '1');
@ini_set('session.use_trans_sid', '0');
if (PHP_VERSION_ID >= 70300) {
    session_set_cookie_params([
        'lifetime' => 0,
        'path' => '/',
        'secure' => $__is_https,
        'httponly' => true,
        'samesite' => 'Lax'
    ]);
} else {
    @ini_set('session.cookie_httponly', '1');
    @ini_set('session.cookie_secure', $__is_https ? '1' : '0');
}

session_start();

if (!function_exists('is_valid_msid')) {
    function is_valid_msid($value) {
        return is_string($value) && preg_match('/^[a-f0-9]{32}$/i', $value) === 1;
    }
}
if (!function_exists('normalize_msid')) {
    function normalize_msid($value) {
        if (!is_string($value)) return '';
        $value = trim($value);
        if (!is_valid_msid($value)) return '';
        return strtolower($value);
    }
}
if (!function_exists('generate_msid')) {
    function generate_msid() {
        if (function_exists('random_bytes')) {
            try {
                return bin2hex(random_bytes(16)); // 32 hex chars
            } catch (Exception $e) {
            }
        }
        if (function_exists('openssl_random_pseudo_bytes')) {
            $bytes = openssl_random_pseudo_bytes(16);
            if ($bytes !== false) return bin2hex($bytes);
        }
        $remote_addr = "";
        if (isset($_SERVER['REMOTE_ADDR'])) $remote_addr = $_SERVER['REMOTE_ADDR'];
        return md5(uniqid((string) mt_rand(), true) . microtime(true) . $remote_addr);
    }
}

$is_post = ($_SERVER['REQUEST_METHOD'] === 'POST');

$require_any = ['_toprg','srv_*'];   // metti i tuoi campi �di ricerca� 
$exists_any  = false;
foreach ($require_any as $key) {
    if (isset($_POST[$key]) && $_POST[$key] !== '') { $exists_any = true; break; }
    //se l'asterisk � presente, cerca qualsiasi chiave che inizi con il prefisso
    if (str_ends_with($key, '*')) {
        $prefix = substr($key, 0, -1);
        foreach ($_POST as $k => $v) {
            if (str_starts_with($k, $prefix) ) #&& $v !== ''
            {
                $exists_any = true;
                break 2;
            }
        }
    }
}

$should_redirect_to_get =
    $is_post
    && ($exists_any && !isset($_POST['login']));


if ($should_redirect_to_get) {

$qs = build_query_from_array(
        $_POST,
        exclude_keys: array(), // escludi quello che non vuoi in URL ['MSID']
        drop_empty: true,
        exclude_prefixes: ['__']               // opzionale: escludi chiavi che iniziano con "__"
    );
#echo strlen($qs);
    $path = 'index.php';
    $url  = $path . ($qs ? "?{$qs}" : '');
    #header('Location: ' . $url, true, 303);
    #exit;
}
/*
$_filters = $_SESSION['search_filters'] ?? [];
extract($_filters);
$_SESSION['search_filters'] = []; // reset dopo estrazione
*/
include_once("_config.php");
$_mainLdir = "./_main/";

// CONFIGURAZIONE
include_once $_mainLdir . "_inc/global.inc.php";
include_once $extincpath_hdd . "_inc/parseInputVars.inc.php"; // whitelist

$_t = time();#Date("d"); LASCIARE PER COMPATIBILITA'


$current_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
// PARAMETRI AGGIUNTIVI
foreach (['params', 'strparam'] as $paramGroup) {
    if (!empty($$paramGroup)) {
        parse_str($$paramGroup, $res);
        foreach ($res as $k => $v) {
            if (in_array($k, $A_INPUTVARS) && !isset($$k)) {
                $$k = $v;
            }
        }
        $$paramGroup = "";
    }
}

if($_SRV==""){

$request_uri = filter_input(INPUT_SERVER, "REQUEST_URI");
$request_uri = str_replace("/index.php","",$request_uri);
$request_uri = str_replace("//","/",$request_uri);

if(strstr($request_uri,"?")){
$aru = explode("?",$request_uri);
parse_str($aru[1], $res);extract($res);
$request_uri = $aru[0];
}

$sezto = "";

if(isset($sezione) && $sezione != "") $sz = trim($sezione);
if( ($request_uri=="/$_dir" || $request_uri=="/$_dir/") && !isset($sz) && !isset($sezione) ){

 	 $sz = $sezDefault;
}
if( (isset($sz) && $sz=="") || !isset($sz) ) $sz = $sezDefault;

}

// Canonical section vars for framework/login.
if (isset($sezione) && $sezione !== "") {
    $sz = $sezione;
} elseif (isset($sz) && $sz !== "") {
    $sezione = $sz;
}
if (!isset($sz) || $sz === "") $sz = $sezDefault;
if (!isset($sezione) || $sezione === "") $sezione = $sz;

$_sz = $sz;
if (strstr($_sz, ",")) {
    $atmp = explode(",", $_sz);
    $_sz = $atmp[0];
}
if (strstr($_sz, ".")) {
    $atmp = explode(".", $_sz);
    $_sz = $atmp[0];
}

// Canonical source: sessione PHP.
// Retrocompat: se la sessione non ha ancora MSID, accetta quello da request (se valido).
$requestMSID = normalize_msid($MSID ?? '');
$sessionMSID = normalize_msid($_SESSION['MSID'] ?? '');
if ($sessionMSID !== '') {
    $MSID = $sessionMSID;
} else {
    $MSID = generate_msid();
    $_SESSION['MSID'] = $MSID;
}

$mysessionid = $mySID = $MSID;
// CLASSI E FUNZIONI ESSENZIALI
include_once $_mainLdir . "_inc/dbmanager.php";
include_once $extincpath_hdd . "_inc/usermanager.php";
include_once $extincpath_hdd."_inc/session.php";
//////////////////////////////////////////////////////////////////////////////////////////////////////
include_once $extincpath_hdd."_class/login.class.php";
include_once $extincpath_hdd."_class/user.class.php";
///////////////////////////////////////////////////////////////////////////////////////////////////////

include_once $extincpath_hdd."_inc/common.php";
include_once $extincpath_hdd."_inc/commonws.php";
include_once( $prefix."/_inc/function.php");

##############################################################################################

include_once( "./".$prefix."/_inc/config.inc.php");

include_once( $extincpath_hdd."_inc/login.php");

if(!isset($_FL)) $_FL = my_statevar_read("_FL");

##############################################################################################
if ($logged == 1) {
        
        extract($_GET);
        extract($_POST);
        if(isset($params) && $params!="") {
            parse_str($params, $res);
            extract($res);
        }
        if(isset($strparam) && $strparam!="") {
            parse_str($strparam, $res);
            extract($res);
        }

}
$params = "";
$strparam = "";

// LINGUA
$language = $_SESSION['language'] ?? 'it';
include $extincpath_hdd . "_inc/language.php";
if (file_exists($prefix . "/_inc/language.php")) {
    include_once("./" . $prefix . "/_inc/language.php");
}



if(isset($_SRV) && $_SRV !="") {

	include "./init.php";
	include "./service.php";

} else {

    include "./init.php";

    $a = Get_Contents($sz);
    $_ALL_PARAMS['layout'] = $layout = $a[2];
    $content = $a[0];
    $_ALL_PARAMS['sz'] = $sz = $a[3];


	$xparams = $a[4];parse_str($xparams,$res);extract($res);
	#$a_sezione = $a[5];

    if(isset($a[1]) && $a[1]!="" && (!isset($azione) || $azione=="")) $azione = trim($a[1]);
    if(!isset($azione)) $azione = "";

    $_ALL_PARAMS['azione'] = $azione;

    if($onlylogged==1 && $logged!=1) {
        $sz = "home";
        $a = Get_Contents($sz);
        $_ALL_PARAMS['layout'] = $layout  = $a[2];
        $content = $a[0];
        $_ALL_PARAMS['sezione']     = $sezione   = $sz   = $a[3];
        $xparams = $a[4];parse_str($xparams, $res);extract($res);
        #$a_sezione = $a[5];
        if($a[1]!="") $azione = $a[1];if(!isset($azione)) $azione = "";
        $_ALL_PARAMS['azione']     = $azione;
    }

    if (!empty($prefix)) {
        #$conn = $mydb->RefreshConnect();
        include "./" . $prefix . "/_layout/" . $layout;
    } else {
        echo "ERRORE GENERALE.<br>";
    }
}

##############################################################################################
my_statevar_create("_FL", $_FL);
/*
*************************************************************************************
 Funzioni di utilit�
*/
function is_truly_empty($v): bool {
    if ($v === null) return true;
    if (is_string($v)) return trim($v) === '';
    if (is_array($v)) {
        // se dopo il filtro è vuota, considerala vuota
        foreach ($v as $vv) { if (!is_truly_empty($vv)) return false; }
        return true;
    }
    return false;
}
/**
 * Costruisce una querystring RFC3986 da un array (tipicamente $_POST)
 * - $exclude_keys: chiavi da escludere (case sensitive)
 * - $drop_empty: rimuove valori vuoti ma mantiene 0/'0'
 * - $exclude_prefixes: esclude per prefisso (es. ["__", "tmp_"])
 */
function build_query_from_array(
    array $data,
    array $exclude_keys = [],
    bool $drop_empty = true,
    array $exclude_prefixes = []
): string {
    $filtered = [];

    $should_exclude = function(string $key) use ($exclude_keys, $exclude_prefixes): bool {
        if (in_array($key, $exclude_keys, true)) return true;
        foreach ($exclude_prefixes as $p) {
            if ($p !== '' && strncmp($key, $p, strlen($p)) === 0) return true;
        }
        return false;
    };

    foreach ($data as $k => $v) {
        if ($should_exclude($k)) continue;

        // elimina vuoti, ma conserva 0/'0'
        if ($drop_empty) {
            if ($v === 0 || $v === '0') {
                // tieni
            } else if (is_truly_empty($v)) {
                continue;
            }
        }

        $filtered[$k] = $v;
    }

    // encoding pulito, supporta array annidati stile foo[bar]=...
    return http_build_query($filtered, '', '&', PHP_QUERY_RFC3986);
}
?>