Selettore scuola in tutte le pagine

This commit is contained in:
2026-10-03 19:02:07 +02:00
parent 28222ee7f1
commit 8441cc702c
34 changed files with 587 additions and 334 deletions
+171 -42
View File
@@ -1,13 +1,17 @@
<?php
/**
* SchoolContext
* Determina la scuola corrente dell'utente loggato e la rende disponibile
* a tutte le pagine (via headscript).
* SchoolContext v2
* Determina la scuola corrente dell'utente loggato, il suo ruolo nella scuola
* e le scuole tra cui può passare (owner multi-scuola, superadmin).
*
* Uso:
* $school = SchoolContext::resolve((int)$iduserlogin);
* $idschool = SchoolContext::id();
* Uso (nella headscript):
* $schoolData = SchoolContext::resolve((int)$iduserlogin);
* $idschool = SchoolContext::id();
*
* Ruoli scuola: owner | admin | teacher | student
* Il superadmin di piattaforma (auth_users.is_superadmin = 'Y') può entrare
* in qualsiasi scuola: se non ne è membro, il suo ruolo risulta 'superadmin'.
*/
if (!class_exists('DBHandlerSelect')) {
@@ -19,49 +23,53 @@ class SchoolContext
/** Scuola di fallback durante la fase monoscuola (Seregno) */
const DEFAULT_SCHOOL = 1;
/** @var array|null dati della scuola corrente (riga schools + school_role) */
/** @var array|null scuola corrente (riga schools + school_role) */
private static $school = null;
/**
* Risolve la scuola corrente per l'utente indicato.
* Chiamare una sola volta per richiesta (nella headscript).
*/
/** @var int */
private static $userId = 0;
/** @var bool */
private static $superadmin = false;
/** @var array scuole di cui l'utente è membro */
private static $memberships = [];
/* ------------------------------------------------------------------ */
public static function resolve(int $userId): array
{
if (self::$school !== null) {
return self::$school;
}
$pdo = DBHandlerSelect::getInstance()->getConnection();
$pdo = self::pdo();
self::$userId = $userId;
$schools = self::userSchools($pdo, $userId);
$st = $pdo->prepare("SELECT is_superadmin FROM auth_users WHERE id = ?");
$st->execute([$userId]);
self::$superadmin = ($st->fetchColumn() === 'Y');
self::$memberships = self::loadMemberships($userId);
// TEMPORANEO (fase monoscuola): utente senza scuola -> agganciato a Seregno
if (empty($schools)) {
$stmt = $pdo->prepare(
if (empty(self::$memberships) && !self::$superadmin) {
$ins = $pdo->prepare(
"INSERT IGNORE INTO school_user (user_id, idschool, school_role)
VALUES (?, ?, 'student')"
);
$stmt->execute([$userId, self::DEFAULT_SCHOOL]);
$schools = self::userSchools($pdo, $userId);
$ins->execute([$userId, self::DEFAULT_SCHOOL]);
self::$memberships = self::loadMemberships($userId);
}
if (empty($schools)) {
$requested = isset($_SESSION['idschool']) ? (int) $_SESSION['idschool'] : 0;
$selected = self::pick($requested);
if ($selected === null) {
http_response_code(403);
die('Nessuna scuola attiva associata a questo account.');
}
// Scuola richiesta in sessione: accettata solo se l'utente ne fa parte
$requested = isset($_SESSION['idschool']) ? (int) $_SESSION['idschool'] : 0;
$selected = $schools[0];
foreach ($schools as $row) {
if ((int) $row['idschool'] === $requested) {
$selected = $row;
break;
}
}
$selected['idschool'] = (int) $selected['idschool'];
$_SESSION['idschool'] = $selected['idschool'];
@@ -69,16 +77,55 @@ class SchoolContext
return self::$school;
}
/** ID della scuola corrente */
public static function id(): int
/**
* Cambia scuola corrente. Ritorna false se l'utente non può accedervi.
*/
public static function switchTo(int $idschool): bool
{
if (self::$school === null) {
throw new RuntimeException('SchoolContext::resolve() non ancora chiamato');
if ($idschool <= 0) {
return false;
}
return self::$school['idschool'];
foreach (self::available() as $s) {
if ((int) $s['idschool'] === $idschool) {
$_SESSION['idschool'] = $idschool;
self::$school = null;
self::resolve(self::$userId);
return true;
}
}
return false;
}
/**
* Scuole tra cui l'utente può scegliere (per il selettore in topbar).
* Superadmin: tutte le scuole. Altri: solo quelle di cui è membro.
*/
public static function available(): array
{
if (!self::$superadmin) {
return self::$memberships;
}
$roles = [];
foreach (self::$memberships as $m) {
$roles[(int) $m['idschool']] = $m['school_role'];
}
$all = self::pdo()->query("SELECT * FROM schools ORDER BY name")->fetchAll();
foreach ($all as &$s) {
$s['school_role'] = $roles[(int) $s['idschool']] ?? 'superadmin';
}
unset($s);
return $all;
}
/* --------------------------- getter -------------------------------- */
public static function id(): int
{
return self::get()['idschool'];
}
/** Dati completi della scuola corrente */
public static function get(): array
{
if (self::$school === null) {
@@ -87,25 +134,107 @@ class SchoolContext
return self::$school;
}
/** Ruolo dell'utente nella scuola corrente: student|teacher|admin|owner */
/** owner | admin | teacher | student | superadmin */
public static function role(): string
{
return self::get()['school_role'];
}
/** Scuole attive a cui l'utente è iscritto */
private static function userSchools(PDO $pdo, int $userId): array
public static function isSuperadmin(): bool
{
$stmt = $pdo->prepare(
return self::$superadmin;
}
public static function isOwner(): bool
{
return self::role() === 'owner';
}
/** Può gestire la scuola: owner, admin o superadmin */
public static function isSchoolAdmin(): bool
{
return self::$superadmin || in_array(self::role(), ['owner', 'admin'], true);
}
/** Staff della scuola: amministratori + insegnanti */
public static function isStaff(): bool
{
return self::isSchoolAdmin() || self::role() === 'teacher';
}
/** Blocca la pagina se l'utente non è amministratore della scuola */
public static function requireSchoolAdmin(): void
{
if (!self::isSchoolAdmin()) {
http_response_code(403);
die('Accesso non autorizzato.');
}
}
/** Blocca la pagina se l'utente non è superadmin */
public static function requireSuperadmin(): void
{
if (!self::$superadmin) {
http_response_code(403);
die('Accesso non autorizzato.');
}
}
/* --------------------------- interni ------------------------------- */
private static function pick(int $requested): ?array
{
// 1) scuola richiesta e l'utente ne è membro
foreach (self::$memberships as $m) {
if ((int) $m['idschool'] === $requested) {
return $m;
}
}
// 2) superadmin: può entrare in qualunque scuola esistente
if (self::$superadmin) {
$pdo = self::pdo();
if ($requested > 0) {
$st = $pdo->prepare("SELECT * FROM schools WHERE idschool = ?");
$st->execute([$requested]);
$row = $st->fetch();
if ($row) {
$row['school_role'] = 'superadmin';
return $row;
}
}
if (!empty(self::$memberships)) {
return self::$memberships[0];
}
$row = $pdo->query("SELECT * FROM schools ORDER BY idschool LIMIT 1")->fetch();
if ($row) {
$row['school_role'] = 'superadmin';
return $row;
}
return null;
}
// 3) prima scuola di cui è membro
return self::$memberships[0] ?? null;
}
private static function loadMemberships(int $userId): array
{
$st = self::pdo()->prepare(
"SELECT s.*, su.school_role
FROM school_user su
JOIN schools s ON s.idschool = su.idschool
WHERE su.user_id = ?
AND su.active = 'Y'
AND s.status <> 'suspended'
ORDER BY su.idschool"
ORDER BY s.name"
);
$stmt->execute([$userId]);
return $stmt->fetchAll();
$st->execute([$userId]);
return $st->fetchAll();
}
private static function pdo(): PDO
{
return DBHandlerSelect::getInstance()->getConnection();
}
}