SchoolSettings + adminpanel filtrato per scuola

This commit is contained in:
2026-10-03 19:15:11 +02:00
parent 8441cc702c
commit e27413880a
9 changed files with 1460 additions and 194 deletions
+106
View File
@@ -0,0 +1,106 @@
<?php
/**
* SchoolSettings
* Impostazioni della scuola (tabella `option`, una riga per scuola).
* Sostituisce tutti i "SELECT * FROM `option` LIMIT 1".
*
* Uso:
* $timetocancel = (int) SchoolSettings::get('maxbeforetimecancell', 24);
* $all = SchoolSettings::all();
* SchoolSettings::save(['show_teacher' => 'Y']);
*
* Nei cron (senza sessione) passare l'idschool esplicito:
* SchoolSettings::get('show_teacher', 'N', $idschool);
*/
if (!class_exists('DBHandlerSelect')) {
require_once __DIR__ . '/db-functions.php';
}
class SchoolSettings
{
/** @var array cache per scuola: idschool => riga option */
private static $cache = [];
/** Colonne che non si possono modificare con save() */
const PROTECTED_COLUMNS = ['idption', 'idschool'];
/** Tutte le impostazioni della scuola (riga creata se mancante) */
public static function all(?int $idschool = null): array
{
$idschool = self::schoolId($idschool);
if (!isset(self::$cache[$idschool])) {
$pdo = self::pdo();
$st = $pdo->prepare("SELECT * FROM `option` WHERE idschool = ? LIMIT 1");
$st->execute([$idschool]);
$row = $st->fetch();
if (!$row) {
// Nuova scuola: crea la riga con i default delle colonne
try {
$pdo->prepare("INSERT INTO `option` (idschool) VALUES (?)")->execute([$idschool]);
$st->execute([$idschool]);
$row = $st->fetch();
} catch (PDOException $e) {
error_log('SchoolSettings: impossibile creare option per scuola ' . $idschool . ': ' . $e->getMessage());
$row = [];
}
}
self::$cache[$idschool] = $row ?: [];
}
return self::$cache[$idschool];
}
/** Singola impostazione, con default se mancante o NULL */
public static function get(string $key, $default = null, ?int $idschool = null)
{
$all = self::all($idschool);
return (array_key_exists($key, $all) && $all[$key] !== null) ? $all[$key] : $default;
}
/**
* Salva una o più impostazioni. Accetta solo colonne esistenti in `option`
* (le altre chiavi vengono ignorate).
*/
public static function save(array $data, ?int $idschool = null): void
{
$idschool = self::schoolId($idschool);
$current = self::all($idschool);
$set = [];
$params = [];
foreach ($data as $col => $val) {
if (!array_key_exists($col, $current) || in_array($col, self::PROTECTED_COLUMNS, true)) {
continue;
}
$set[] = "`$col` = ?";
$params[] = $val;
}
if (empty($set)) {
return;
}
$params[] = $idschool;
self::pdo()->prepare("UPDATE `option` SET " . implode(', ', $set) . " WHERE idschool = ?")
->execute($params);
unset(self::$cache[$idschool]);
}
private static function schoolId(?int $idschool): int
{
if ($idschool !== null && $idschool > 0) {
return $idschool;
}
return SchoolContext::id();
}
private static function pdo(): PDO
{
return DBHandlerSelect::getInstance()->getConnection();
}
}