| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511 |
- <?php
- /**
- * Classe `access`
- *
- * Cette classe gère les droits d'accès des utilisateurs dans le système. Elle inclut des fonctionnalités pour :
- * - Vérifier si un utilisateur a accès à une ressource spécifique.
- * - Gérer les listes blanches et les accès hors ligne.
- * - Récupérer et manipuler les types d'accès et les rôles des utilisateurs.
- * - Enregistrer et mettre à jour les droits d'accès dans la base de données.
- * - Générer des menus déroulants et des tableaux pour la gestion des accès.
- */
- class access
- {
- /**
- * Vérifie si un élément est accessible.
- *
- * @param string $_element L'élément à vérifier.
- * @return bool TRUE si l'accès est autorisé, FALSE sinon.
- */
- public static function check(string $_element)
- {
- // Eléments autorisé sans authentification
- if (self::checkAccessWhite($_element)) {
- return TRUE;
- } else {
- if (session::isConnect("salarie") and session::isEspaceSalaries()) { // Espaces spécifiques aux Salariés
- return TRUE;
- } elseif (session::isConnect() and session::getType() == 2 and session::isEspaceControleurs()) { // Espaces spécifiques aux Contrôleurs
- return TRUE;
- } else {
- return self::ifAccesss($_element);
- }
- }
- }
- /**
- * Vérifie si un élément est accessible hors ligne.
- *
- * @param string $_string L'élément à vérifier.
- * @return bool TRUE si l'accès est autorisé hors ligne, FALSE sinon.
- */
- public static function checkAccessOffLine(string $_string)
- {
- return in_array($_string, OFF_LINE);
- }
- /**
- * Vérifie si un élément est dans la liste blanche.
- *
- * @param string $_string L'élément à vérifier.
- * @return bool TRUE si l'élément est dans la liste blanche, FALSE sinon.
- */
- public static function checkAccessWhite(string $_string)
- {
- return in_array($_string, WHITE_ACCESS);
- }
- /**
- * Récupère la liste des accès pour un type d'utilisateur donné.
- *
- * @param int|null $_idType L'ID du type d'utilisateur (optionnel).
- * @return array|bool La liste des accès ou FALSE en cas d'erreur.
- */
- public static function getAccessList(?int $_idType = NULL)
- {
- ($_idType == NULL) ? $idType = session::getType() : $idType = $_idType;
- $return["access"] = $return["noAccess"] = $return["exception"] = array();
- db::query("SELECT "
- . "" . DB_T_ACCESS . ".id, "
- . "" . DB_T_ACCESS . ".access, "
- . "" . DB_T_ACCESS . ".noAccess, "
- . "" . DB_T_ACCESS_EXCEPTION . ".exception "
- . "FROM " . DB_T_TYPE_ACCESS . " "
- . "INNER JOIN " . DB_T_ACCESS . " ON " . DB_T_TYPE_ACCESS . ".id_access = " . DB_T_ACCESS . ".id "
- . "LEFT JOIN " . DB_T_ACCESS_EXCEPTION . " ON " . DB_T_TYPE_ACCESS . ".id_exception = " . DB_T_ACCESS_EXCEPTION . ".id "
- . "WHERE " . DB_T_TYPE_ACCESS . ".id_type = :id_type ");
- db::bind(':id_type', $idType);
- try {
- $tmp = db::resultset();
- foreach ($tmp as $access) {
- $return["access"] = self::addInArray($access["access"], $return["access"]);
- $return["noAccess"] = self::addInArray($access["noAccess"], $return["noAccess"]);
- if(isset($access["exception"])) { $return["exception"] = self::addInArray($access["exception"], $return["exception"]); }
- }
- // Je supprime les restriction d'accès en fonction des accès accordés
- $return["noAccess"] = array_diff($return["noAccess"], $return["access"]);
-
- return $return;
- } catch (Exception $e) {
- return FALSE;
- }
- }
- /**
- * Récupère les types d'utilisateurs.
- *
- * @param bool $_expect TRUE pour exclure les contrôleurs, FALSE sinon.
- * @return array|bool Les types d'utilisateurs ou FALSE en cas d'erreur.
- */
- public static function getTypesUsers(bool $_expect = FALSE)
- {
- $except = ($_expect == FALSE) ? NULL : " WHERE " . DB_T_TYPE_USER . ".id != 2"; // Sauf les contrôleurs
- db::query("SELECT * FROM " . DB_T_TYPE_USER . $except);
- try {
- $tmp = db::resultset();
- return $tmp;
- } catch (Exception $e) {
- return FALSE;
- }
- }
- /**
- * Vérifie si une exception d'accès est limitée.
- *
- * @param string $_exception L'exception à vérifier.
- * @return bool TRUE si l'exception est limitée, FALSE sinon.
- */
- public static function ifLimitAccessException(string $_exception)
- {
- $accessList = self::getAccessList(session::getType());
- return in_array($_exception, $accessList["exception"]) ? TRUE : FALSE;
- }
- /**
- * Vérifie si un accès est autorisé.
- *
- * @param string $_accessAsk L'accès à vérifier.
- * @param int|null $_idType L'ID du type d'utilisateur (optionnel).
- * @return bool TRUE si l'accès est autorisé, FALSE sinon.
- */
- public static function ifAccesss(string $_accessAsk, ?int $_idType = NULL)
- {
- if (session::isConnect() == FALSE and self::checkAccessOffLine($_accessAsk)) {
- return TRUE;
- }
- // Si Admin OK
- $idType = $_idType == NULL ? session::getType() : $_idType;
- if ($idType == 1) {
- return TRUE;
- }
- // Si Admin OK
- $accessList = self::getAccessList($idType);
- $cheminGenrique = self::checkGenericAccess($_accessAsk, $accessList["access"]);
- if ($cheminGenrique != FALSE AND !in_array($_accessAsk, $accessList["noAccess"])) { // Si Accès générique
- return TRUE;
- } elseif (in_array($_accessAsk, $accessList["access"]) or self::checkAccessWhite($_accessAsk)) {
- return TRUE;
- } else {
- return FALSE;
- }
- }
- /**
- * Vérifie si un accès générique est autorisé.
- *
- * @param string $_string L'accès à vérifier.
- * @param array $_access_list La liste des accès.
- * @return string|bool Le chemin générique si autorisé, FALSE sinon.
- */
- private static function checkGenericAccess(string $_string, array $_access_list)
- {
- $string = explode("-", $_string)[0];
- $check = in_array($string."*", $_access_list);
- return ($check == TRUE) ? $string : FALSE;
- }
- /**
- * Sépare les accès à partir d'une chaîne.
- *
- * @param string $_string La chaîne à traiter.
- * @return array Les accès séparés.
- */
- private static function splitAccess(string $_string)
- {
- $return = array();
- $tmp = array_filter(explode("\n", $_string));
- foreach ($tmp as $key => $value) {
- $return[$key] = trim($value);
- }
- return $return;
- }
- /**
- * Ajoute des accès à un tableau existant.
- *
- * @param string $_string Les accès à ajouter.
- * @param array $_array Le tableau existant.
- * @return array Le tableau mis à jour.
- */
- private static function addInArray(string $_string, array $_array)
- {
- return array_unique(array_merge(self::splitAccess($_string), $_array));
- }
- /**
- * Récupère la liste des types d'utilisateurs, avec des exceptions optionnelles.
- *
- * @param array|null $_idExceptions Les IDs à exclure (optionnel).
- * @return array|bool La liste des types ou FALSE en cas d'erreur.
- */
- public static function getListTypeUser(?array $_idExceptions = NULL )
- {
- $return = array();
- db::query("SELECT id, type FROM " . DB_T_TYPE_USER);
- try {
- $return = [];
- foreach (db::resultset() as $value) {
- if(is_null($_idExceptions) OR (!is_null($_idExceptions) AND !in_array($value["id"], $_idExceptions)) ){
- $return[$value["id"]] = $value["type"];
- }
- }
- return $return;
- } catch (Exception $e) {
- return FALSE;
- }
- }
- /**
- * Affiche une ligne de tableau pour les accès.
- *
- * @param array $valueAccess Les données d'accès.
- * @return void
- */
- public static function printRenderAccessRow(array $valueAccess){
- if (!is_null($valueAccess["exception"])) {
- $tooltip = '<span class="ms-2" data-bs-toggle="tooltip" title="Possibilité d\'accès partiel avec les éléments cachés suivants : ' . htmlspecialchars($valueAccess["exception"]) . '"><i class="bi bi-info-circle-fill" style="color:#ffc107;"></i></span>';
- } else {
- $tooltip = '';
- }
- echo '<tr>';
- echo '<td style="vertical-align: middle; box-sizing: border-box;">' . $valueAccess["label"] . $tooltip . '</td>';
-
- $tmp = [];
- foreach ($valueAccess["access"] as $keyRole => $valueRole) {
- $tmp[$keyRole] = '<td style="width: 180px;"><div style="text-align:center;">';
- $tmp[$keyRole] .= self::getSelectAccess($valueAccess["access"][$keyRole], $valueAccess["exception"]);
- $tmp[$keyRole] .= '</div></td>';
- }
- echo $tmp[1]; // Administrateur
- echo $tmp[4]; // Modérateur du CMS
- echo $tmp[5]; // Bureau du CSE
- echo $tmp[6]; // Elu du CSE
- echo $tmp[7]; // Comptable
- echo $tmp[3]; // Assistance sociale
- echo '</tr>';
- }
- /**
- * Génère un menu déroulant pour les accès.
- *
- * @param array|null $_access Les données d'accès (optionnel).
- * @param string|null $_exception L'exception associée (optionnel).
- * @return string Le HTML du menu déroulant.
- */
- private static function getSelectAccess(?array $_access = NULL, ?string $_exception = NULL){
- if (!is_null($_exception)) {
- $options = [
- 1 => 'Autorisé',
- 0 => '-',
- 2 => 'Partiellement'
- ];
-
- } else {
- $options = [
- 1 => 'Autorisé',
- 0 => '-',
- ];
- }
- $bgColors = [
- 1 => 'background-color:#d4edda;',
- 0 => 'background-color:#f8d7da;',
- 2 => 'background-color:#ffeeba;'
- ];
- $disabled = ($_access["id_type"] == 1 OR $_access["id_access"] == 3) ? ' disabled' : '';
- $disabledStyle = ($_access["id_type"] == 1 OR $_access["id_access"] == 3) ? ' opacity: 0.5; cursor: not-allowed;' : '';
- $style = isset($bgColors[$_access["access"]]) ? $bgColors[$_access["access"]] : '';
- $return = '<select class="form-select form-select-sm" name="access-' . str_replace("#", "-", $_access["id_type_access"]) . '" style="' . $style . $disabledStyle . '"' . $disabled . '>';
- foreach ($options as $value => $label) {
- $selected = ($_access["access"] === $value) ? ' selected' : '';
- $return .= '<option value="' . $value . '"' . $selected . '>' . $label . '</option>';
- }
- $return .= '</select>';
- return $return;
- }
- /**
- * Complète les accès avec des valeurs par défaut.
- *
- * @param string $_idAccess L'ID de l'accès.
- * @param array|null $_access Les données d'accès existantes (optionnel).
- * @return array Les accès complétés.
- */
- private static function completeIdemAccess(string $_idAccess, ?array $_access = NULL){
- $roles = self::getListTypeUser([2]); // Tous les types sauf les contrôleurs
- foreach ($roles as $keyRole => $valueRole) {
- if(empty($_access["access"][$keyRole])){
- $tmp = [];
- $tmp["id_type_access"] = $keyRole . "#" . $_access["id_access"];
- $tmp["id_type"] = $keyRole;
- $tmp["id_access"] = $_idAccess;
- $tmp["type"] = $valueRole;
- $tmp["access"] = ($keyRole == 1) ? 1 : 0;
- $return[$keyRole] = $tmp;
- } else {
- $return[$keyRole] = $_access["access"][$keyRole];
- }
- }
- return $return;
- }
- /**
- * Récupère la liste complète des accès.
- *
- * @return array La liste complète des accès.
- */
- public static function finalCompletAccess(){
- $access = access::getTypesAccessRecording();
- $return = [];
- foreach ($access as $keyAccess => $valueAccess) {
- $completeAccess = access::completeIdemAccess($valueAccess["id_access"], $valueAccess);
- unset($valueAccess["access"]);
- $valueAccess["access"] = $completeAccess;
- $return[] = $valueAccess;
- }
- return $return;
- }
- /**
- * Récupère les types d'accès.
- *
- * @return array|bool Les types d'accès ou FALSE en cas d'erreur.
- */
- private static function getTypesAccess(){
- db::query("SELECT "
- . DB_T_ACCESS . ".id, "
- . DB_T_ACCESS . ".label, "
- . DB_T_ACCESS . ".show, "
- . DB_T_ACCESS . ".add, "
- . DB_T_TYPE_ACCESS . ".id AS id_type_access, "
- . DB_T_TYPE_ACCESS . ".id_type, "
- . "exception1.exception AS exception_type, "
- . "exception2.exception AS exception, "
- . DB_T_TYPE_USER . ".type "
- . "FROM " . DB_T_ACCESS . " "
- . "LEFT JOIN " . DB_T_ACCESS_EXCEPTION . " AS exception1 ON exception1.id_access = " . DB_T_ACCESS . ".id "
- . "LEFT JOIN " . DB_T_TYPE_ACCESS . " ON " . DB_T_TYPE_ACCESS . ".id_access = " . DB_T_ACCESS . ".id "
- . "LEFT JOIN " . DB_T_TYPE_USER . " ON " . DB_T_TYPE_ACCESS . ".id_type = " . DB_T_TYPE_USER . ".id "
- . "LEFT JOIN " . DB_T_ACCESS_EXCEPTION . " AS exception2 ON " . DB_T_TYPE_ACCESS . ".id_exception = exception2.id "
- . "ORDER BY " . DB_T_ACCESS . ".id");
- try {
- $tmp = db::resultset();
- return $tmp;
- } catch (Exception $e) {
- return FALSE;
- }
- }
- /**
- * Génère un libellé pour un accès.
- *
- * @param array $_array Les données de l'accès.
- * @return string Le libellé généré.
- */
- private static function getTitleLabel(array $_array){
- if ($_array["show"] == 1 AND $_array["add"] == 0) {
- return "Accès à <strong>" . $_array["label"] . "</strong> en lecture";
- } elseif ($_array["show"] == 0 AND $_array["add"] == 1) {
- return "Accès à <strong>" . $_array["label"] . "</strong> en écriture";
- } else {
- return "Accès à <strong>" . $_array["label"] . "</strong> en lecture et écriture";
- }
- }
- /**
- * Récupère les types d'accès pour l'enregistrement.
- *
- * @return array Les types d'accès.
- */
- public static function getTypesAccessRecording(){
- $return = [];
- foreach (self::getTypesAccess() as $valueAccess) {
- $return[$valueAccess["id"]]["id_access"] = $valueAccess["id"];
- $return[$valueAccess["id"]]["label"] = self::getTitleLabel($valueAccess);
- $return[$valueAccess["id"]]["show"] = $valueAccess["show"];
- $return[$valueAccess["id"]]["add"] = $valueAccess["add"];
- $return[$valueAccess["id"]]["exception"] = $valueAccess["exception_type"];
-
- if(!empty($valueAccess["id_type_access"])) {
- $return[$valueAccess["id"]]["access"][$valueAccess["id_type"]] = [
- "id_type_access" => $valueAccess["id_type_access"],
- "id_type" => $valueAccess["id_type"],
- "id_access" => $valueAccess["id"],
- "type" => $valueAccess["type"],
- "access" => (empty($valueAccess["exception"])) ? 1 : 2,
- ];
- }
- }
- return $return;
- }
- /**
- * Récupère les accès par rôle.
- *
- * @return array Les accès par rôle.
- */
- public static function getAccessByRole(){
- $getAccessByRole = self::getTypesAccessRecording();
- $allTypeRole = self::getTypesUsers();
- $return = [];
- foreach ($getAccessByRole as $valuesGetAccessByRole) {
- $tmp = [];
- $tmp["access"] = $valuesGetAccessByRole["label"];
- $tmp["exception"] = $valuesGetAccessByRole["exception"];
- foreach ($allTypeRole as $valueAllTypeRole) {
- if(!empty($valuesGetAccessByRole["access"][$valueAllTypeRole["id"]])){
- $tmp[$valuesGetAccessByRole["access"][$valueAllTypeRole["id"]]["type"]] = $valuesGetAccessByRole["access"][$valueAllTypeRole["id"]]["access"];
- } elseif($valueAllTypeRole["id"] == 1){
- $tmp[$valueAllTypeRole["type"]] = 1;
- } else {
- $tmp[$valueAllTypeRole["type"]] = 0;
- }
- }
- $return[] = $tmp;
- }
- return $return;
- }
- /**
- * Récupère l'ID d'une exception pour un accès donné.
- *
- * @param int $_idAccess L'ID de l'accès.
- * @return array|bool Les données de l'exception ou FALSE en cas d'erreur.
- */
- private static function getIdException(int $_idAccess){
- db::query("SELECT "
- . DB_T_ACCESS_EXCEPTION . ".id, "
- . DB_T_ACCESS_EXCEPTION . ".exception "
- . "FROM " . DB_T_ACCESS_EXCEPTION . " "
- . "WHERE " . DB_T_ACCESS_EXCEPTION . ".id_access = :id_access");
- db::bind(':id_access', $_idAccess);
- try {
- $tmp = db::single();
- return $tmp;
- } catch (Exception $e) {
- return FALSE;
- }
- }
- /**
- * Enregistre les accès dans la base de données.
- *
- * @return bool TRUE si l'enregistrement a réussi, FALSE sinon.
- */
- public static function recordAccess(){
- $post = core::getPost();
- $data = [];
-
- foreach ($post as $keyPost => $valuePost) {
- if($valuePost == 1 OR $valuePost == 2){
- $tmp = explode("-", $keyPost);
- $data[$tmp[1] . "#" . $tmp[2]]["id_access"] = $tmp[2];
- $data[$tmp[1] . "#" . $tmp[2]]["id_type"] = $tmp[1];
- if($valuePost == 2){
- $data[$tmp[1] . "#" . $tmp[2]]["id_exception"] = self::getIdException($tmp[2])["id"];
- } else {
- $data[$tmp[1] . "#" . $tmp[2]]["id_exception"] = NULL;
- }
- }
- }
- // Vide la table
- db::query("TRUNCATE TABLE " . DB_T_TYPE_ACCESS);
- db::execute();
- // Reconstruit la table
- foreach ($data as $keyData => $valueData) {
- db::query("INSERT INTO " . DB_T_TYPE_ACCESS . " (id, id_type, id_access, id_exception) VALUES (:id, :id_type, :id_access, :id_exception)");
- db::bind(':id', $keyData);
- db::bind(':id_type', $valueData["id_type"]);
- db::bind(':id_access', $valueData["id_access"]);
- db::bind(':id_exception', $valueData["id_exception"]);
- try {
- db::execute();
- } catch (Exception $ex) {
- alert::recError("Erreur à l'enregistrement des droits");
- if(debug::isFile("debug")) { alert::recError("Stack : " . $ex); }
- return FALSE;
- }
- }
- return TRUE;
- }
- }
|