Modelli Eloquent di base

Aggiunti i modelli Eloquent per la gestione delle strutture di base del database.
Utilizzi da implementare.
This commit is contained in:
Thomas Zilio 2018-08-10 17:14:09 +02:00
parent a97fac4cba
commit 6f70484c41
31 changed files with 585 additions and 205 deletions

View File

@ -7,10 +7,10 @@ if (isset($id_record)) {
$posizione .= ', '.$id_record; $posizione .= ', '.$id_record;
} }
$dbo->query('UPDATE zz_semaphores SET updated = NOW() WHERE id_utente = '.prepare(Auth::user()['id_utente']).' AND posizione = '.prepare($posizione)); $dbo->query('UPDATE zz_semaphores SET updated = NOW() WHERE id_utente = '.prepare(Auth::user()['id']).' AND posizione = '.prepare($posizione));
$dbo->query('DELETE FROM zz_semaphores WHERE DATE_ADD(updated, INTERVAL '.(setting('Timeout notifica di presenza (minuti)') * 2).' SECOND) <= NOW()'); $dbo->query('DELETE FROM zz_semaphores WHERE DATE_ADD(updated, INTERVAL '.(setting('Timeout notifica di presenza (minuti)') * 2).' SECOND) <= NOW()');
$datas = $dbo->fetchArray('SELECT DISTINCT username FROM zz_semaphores INNER JOIN zz_users ON zz_semaphores.id_utente=zz_users.id WHERE zz_semaphores.id_utente != '.prepare(Auth::user()['id_utente']).' AND posizione = '.prepare($posizione)); $datas = $dbo->fetchArray('SELECT DISTINCT username FROM zz_semaphores INNER JOIN zz_users ON zz_semaphores.id_utente=zz_users.id WHERE zz_semaphores.id_utente != '.prepare(Auth::user()['id']).' AND posizione = '.prepare($posizione));
$result = []; $result = [];
foreach ($datas as $data) { foreach ($datas as $data) {

View File

@ -60,7 +60,7 @@ if (!API::isAPIRequest()) {
$handlers[] = new StreamHandler($docroot.'/logs/setup.log', Monolog\Logger::EMERGENCY); $handlers[] = new StreamHandler($docroot.'/logs/setup.log', Monolog\Logger::EMERGENCY);
// Impostazioni di debug // Impostazioni di debug
if (!empty($debug)) { if (App::debug()) {
// Ignora gli avvertimenti e le informazioni relative alla deprecazione di componenti // Ignora gli avvertimenti e le informazioni relative alla deprecazione di componenti
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE & ~E_USER_DEPRECATED); error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE & ~E_USER_DEPRECATED);
@ -86,20 +86,20 @@ if (!API::isAPIRequest()) {
} }
// Disabilita la segnalazione degli errori (se il debug è disabilitato) // Disabilita la segnalazione degli errori (se il debug è disabilitato)
if (empty($debug)) { if (!App::debug()) {
error_reporting(0); error_reporting(0);
} }
// Imposta il formato di salvataggio dei log // Imposta il formato di salvataggio dei log
$pattern = '[%datetime%] %channel%.%level_name%: %message%'; $pattern = '[%datetime%] %channel%.%level_name%: %message%';
if (!empty($debug)) { if (App::debug()) {
$pattern .= ' %context%'; $pattern .= ' %context%';
} }
$pattern .= PHP_EOL.'%extra% '.PHP_EOL; $pattern .= PHP_EOL.'%extra% '.PHP_EOL;
$monologFormatter = new Monolog\Formatter\LineFormatter($pattern); $monologFormatter = new Monolog\Formatter\LineFormatter($pattern);
if (!empty($debug)) { if (App::debug()) {
$monologFormatter->includeStacktraces(true); $monologFormatter->includeStacktraces(true);
} }
@ -111,6 +111,9 @@ foreach ($handlers as $handler) {
// Imposta Monolog come gestore degli errori // Imposta Monolog come gestore degli errori
Monolog\ErrorHandler::register($logger); Monolog\ErrorHandler::register($logger);
// Database
$dbo = $database = Database::getConnection();
// Inizializzazione della sessione // Inizializzazione della sessione
if (!API::isAPIRequest()) { if (!API::isAPIRequest()) {
// Sicurezza della sessioni // Sicurezza della sessioni
@ -119,6 +122,20 @@ if (!API::isAPIRequest()) {
session_set_cookie_params(0, $rootdir, null, isHTTPS(true)); session_set_cookie_params(0, $rootdir, null, isHTTPS(true));
session_start(); session_start();
// Barra di debug (necessario per loggare tutte le query)
if (App::debug()) {
$debugbar = new DebugBar\DebugBar();
$debugbar->addCollector(new DebugBar\DataCollector\MemoryCollector());
$debugbar->addCollector(new DebugBar\DataCollector\PhpInfoCollector());
$debugbar->addCollector(new DebugBar\DataCollector\RequestDataCollector());
$debugbar->addCollector(new DebugBar\DataCollector\TimeDataCollector());
$debugbar->addCollector(new DebugBar\Bridge\MonologCollector($logger));
$debugbar->addCollector(new Extension\EloquentCollector($dbo->getCapsule()));
}
} }
// Istanziamento del gestore delle traduzioni del progetto // Istanziamento del gestore delle traduzioni del progetto
@ -133,8 +150,6 @@ $translator->setLocale($lang, $formatter);
$version = Update::getVersion(); $version = Update::getVersion();
$revision = Update::getRevision(); $revision = Update::getRevision();
$dbo = Database::getConnection();
// Controllo sulla presenza dei permessi di accesso basilari // Controllo sulla presenza dei permessi di accesso basilari
$continue = $dbo->isInstalled() && !Update::isUpdateAvailable() && (Auth::check() || API::isAPIRequest()); $continue = $dbo->isInstalled() && !Update::isUpdateAvailable() && (Auth::check() || API::isAPIRequest());
@ -156,20 +171,6 @@ if (!API::isAPIRequest()) {
// Impostazioni di Content-Type e Charset Header // Impostazioni di Content-Type e Charset Header
header('Content-Type: text/html; charset=UTF-8'); header('Content-Type: text/html; charset=UTF-8');
// Barra di debug
if (App::debug()) {
$debugbar = new DebugBar\DebugBar();
$debugbar->addCollector(new DebugBar\DataCollector\MemoryCollector());
$debugbar->addCollector(new DebugBar\DataCollector\PhpInfoCollector());
$debugbar->addCollector(new DebugBar\DataCollector\RequestDataCollector());
$debugbar->addCollector(new DebugBar\DataCollector\TimeDataCollector());
$debugbar->addCollector(new DebugBar\Bridge\MonologCollector($logger));
$debugbar->addCollector(new Extension\EloquentCollector($dbo->getCapsule()));
}
// Controllo CSRF // Controllo CSRF
csrfProtector::init(); csrfProtector::init();

View File

@ -18,9 +18,9 @@ echo '{( "name": "widgets", "id_module": "'.$id_module.'", "id_record": "'.$id_r
$advanced_sessions = setting('Attiva notifica di presenza utenti sul record'); $advanced_sessions = setting('Attiva notifica di presenza utenti sul record');
if ($advanced_sessions) { if ($advanced_sessions) {
$dbo->query('DELETE FROM zz_semaphores WHERE id_utente='.prepare(Auth::user()['id_utente']).' AND posizione='.prepare($id_module.', '.$id_record)); $dbo->query('DELETE FROM zz_semaphores WHERE id_utente='.prepare(Auth::user()['id']).' AND posizione='.prepare($id_module.', '.$id_record));
$dbo->query('INSERT INTO zz_semaphores (id_utente, posizione, updated) VALUES ('.prepare(Auth::user()['id_utente']).', '.prepare($id_module.', '.$id_record).', NOW())'); $dbo->query('INSERT INTO zz_semaphores (id_utente, posizione, updated) VALUES ('.prepare(Auth::user()['id']).', '.prepare($id_module.', '.$id_record).', NOW())');
echo ' echo '
<div class="box box-warning box-solid text-center info-active hide"> <div class="box box-warning box-solid text-center info-active hide">

View File

@ -31,7 +31,7 @@ echo '
if (Auth::admin()) { if (Auth::admin()) {
$q = 'SELECT * FROM `zz_logs` ORDER BY `created_at` DESC LIMIT 0, 100'; $q = 'SELECT * FROM `zz_logs` ORDER BY `created_at` DESC LIMIT 0, 100';
} else { } else {
$q = 'SELECT * FROM `zz_logs` WHERE `id_utente`='.prepare(Auth::user()['id_utente']).' ORDER BY `created_at` DESC LIMIT 0, 100'; $q = 'SELECT * FROM `zz_logs` WHERE `id_utente`='.prepare(Auth::user()['id']).' ORDER BY `created_at` DESC LIMIT 0, 100';
} }
$rs = $dbo->fetchArray($q); $rs = $dbo->fetchArray($q);
$n = sizeof($rs); $n = sizeof($rs);

View File

@ -137,7 +137,7 @@ foreach ($modules as $module) {
</tr>'; </tr>';
// Prima di cambiare modulo verifico se ci sono sottomoduli // Prima di cambiare modulo verifico se ci sono sottomoduli
echo submodules($module['children']); echo submodules($module['all_children']);
} }
echo ' echo '

View File

@ -72,7 +72,7 @@ function submodules($list, $depth = 1)
</td> </td>
</tr>'; </tr>';
$result .= submodules($sub['children'], $depth + 1); $result .= submodules($sub['all_children'], $depth + 1);
} }
return $result; return $result;

View File

@ -5,7 +5,7 @@ include_once __DIR__.'/../../core.php';
switch (post('op')) { switch (post('op')) {
case 'delete-bulk': case 'delete-bulk':
if ($debug) { if (App::debug()) {
$id_azienda = $dbo->fetchArray("SELECT idtipoanagrafica FROM an_tipianagrafiche WHERE descrizione='Azienda'")[0]['idtipoanagrafica']; $id_azienda = $dbo->fetchArray("SELECT idtipoanagrafica FROM an_tipianagrafiche WHERE descrizione='Azienda'")[0]['idtipoanagrafica'];
foreach ($id_records as $id) { foreach ($id_records as $id) {

View File

@ -128,7 +128,7 @@ switch (post('op')) {
case 'delete-bulk': case 'delete-bulk':
if ($debug) { if (App::debug()) {
foreach ($id_records as $id) { foreach ($id_records as $id) {
$dbo->query('DELETE FROM dt_ddt WHERE id = '.prepare($id).Modules::getAdditionalsQuery($id_module)); $dbo->query('DELETE FROM dt_ddt WHERE id = '.prepare($id).Modules::getAdditionalsQuery($id_module));
$dbo->query('DELETE FROM dt_righe_ddt WHERE idddt='.prepare($id).Modules::getAdditionalsQuery($id_module)); $dbo->query('DELETE FROM dt_righe_ddt WHERE idddt='.prepare($id).Modules::getAdditionalsQuery($id_module));

View File

@ -49,7 +49,7 @@ switch (post('op')) {
case 'delete-bulk': case 'delete-bulk':
if ($debug) { if (App::debug()) {
foreach ($id_records as $id) { foreach ($id_records as $id) {
$dbo->query('DELETE FROM co_documenti WHERE id = '.prepare($id).Modules::getAdditionalsQuery($id_module)); $dbo->query('DELETE FROM co_documenti WHERE id = '.prepare($id).Modules::getAdditionalsQuery($id_module));
$dbo->query('DELETE FROM co_righe_documenti WHERE iddocumento='.prepare($id).Modules::getAdditionalsQuery($id_module)); $dbo->query('DELETE FROM co_righe_documenti WHERE iddocumento='.prepare($id).Modules::getAdditionalsQuery($id_module));

View File

@ -155,21 +155,27 @@ switch (filter('op')) {
$idmodulo = filter('idmodulo'); $idmodulo = filter('idmodulo');
// Verifico che ci sia il permesso per questo gruppo // Verifico che ci sia il permesso per questo gruppo
if ($permessi != '-') {
$rs = $dbo->fetchArray('SELECT * FROM zz_permissions WHERE idgruppo='.prepare($id_record).' AND idmodule='.prepare($idmodulo)); $rs = $dbo->fetchArray('SELECT * FROM zz_permissions WHERE idgruppo='.prepare($id_record).' AND idmodule='.prepare($idmodulo));
if (count($rs) == 0) { if (empty($rs)) {
$query = 'INSERT INTO zz_permissions(idgruppo, idmodule, permessi) VALUES('.prepare($id_record).', '.prepare($idmodulo).', '.prepare($permessi).')'; $query = 'INSERT INTO zz_permissions(idgruppo, idmodule, permessi) VALUES('.prepare($id_record).', '.prepare($idmodulo).', '.prepare($permessi).')';
} else { } else {
$query = 'UPDATE zz_permissions SET permessi='.prepare($permessi).' WHERE id='.prepare($rs[0]['id']); $query = 'UPDATE zz_permissions SET permessi='.prepare($permessi).' WHERE id='.prepare($rs[0]['id']);
} }
// Aggiunta dei permessi relativi alle viste // Aggiunta dei permessi relativi alle viste
$count = $dbo->fetchArray('SELECT COUNT(*) AS count FROM `zz_group_view` WHERE `id_gruppo` = '.prepare($id_record).' AND `id_vista` IN (SELECT `id` FROM `zz_views` WHERE `id_module`='.prepare($idmodulo).')'); $count = $dbo->fetchNum('SELECT * FROM `zz_group_view` WHERE `id_gruppo` = '.prepare($id_record).' AND `id_vista` IN (SELECT `id` FROM `zz_views` WHERE `id_module`='.prepare($idmodulo).')');
if (empty($count[0]['count'])) {
if (empty($count)) {
$results = $dbo->fetchArray('SELECT `id_vista` FROM `zz_group_view` WHERE `id_vista` IN (SELECT `id` FROM `zz_views` WHERE `id_module`='.prepare($idmodulo).')'); $results = $dbo->fetchArray('SELECT `id_vista` FROM `zz_group_view` WHERE `id_vista` IN (SELECT `id` FROM `zz_views` WHERE `id_module`='.prepare($idmodulo).')');
foreach ($results as $result) { foreach ($results as $result) {
$dbo->attach('zz_group_view', ['id_vista' => $result['id_vista']], ['id_gruppo' => $id_record]); $dbo->attach('zz_group_view', ['id_vista' => $result['id_vista']], ['id_gruppo' => $id_record]);
} }
} }
} else {
$query = 'DELETE FROM zz_permissions WHERE idgruppo='.prepare($id_record).' AND idmodule='.prepare($idmodulo);
}
$dbo->query($query); $dbo->query($query);

View File

@ -8,7 +8,7 @@ switch ($resource) {
$token = Auth::getInstance()->getToken(); $token = Auth::getInstance()->getToken();
// Informazioni da restituire tramite l'API // Informazioni da restituire tramite l'API
$response['user'] = $dbo->fetchArray('SELECT `ragione_sociale`, `codice`, `piva`, `codice_fiscale`, `indirizzo`, `citta`, `provincia`, (SELECT `nome` FROM `an_nazioni` WHERE `an_nazioni`.`id` = `an_anagrafiche`.`id_nazione`) AS nazione, `telefono`, `fax`, `cellulare`, `an_anagrafiche`.`email` FROM `zz_users` LEFT JOIN `an_anagrafiche` ON `an_anagrafiche`.`idanagrafica` = `zz_users`.`idanagrafica` WHERE `id` = '.prepare($user['id_utente']))[0]; $response['user'] = $dbo->fetchArray('SELECT `ragione_sociale`, `codice`, `piva`, `codice_fiscale`, `indirizzo`, `citta`, `provincia`, (SELECT `nome` FROM `an_nazioni` WHERE `an_nazioni`.`id` = `an_anagrafiche`.`id_nazione`) AS nazione, `telefono`, `fax`, `cellulare`, `an_anagrafiche`.`email` FROM `zz_users` LEFT JOIN `an_anagrafiche` ON `an_anagrafiche`.`idanagrafica` = `zz_users`.`idanagrafica` WHERE `id` = '.prepare($user['id']))[0];
$response['token'] = $token; $response['token'] = $token;
@ -30,7 +30,7 @@ switch ($resource) {
case 'logout': case 'logout':
if (!empty($request['token']) && !empty($user)) { if (!empty($request['token']) && !empty($user)) {
// Cancellazione della chiave // Cancellazione della chiave
$database->query('DELETE FROM `zz_tokens` WHERE `token` = '.prepare($request['token']).' AND `id_utente` = '.prepare($user['id_utente'])); $database->query('DELETE FROM `zz_tokens` WHERE `token` = '.prepare($request['token']).' AND `id_utente` = '.prepare($user['id']));
} else { } else {
$response = [ $response = [
'status' => API::getStatus()['unauthorized']['code'], 'status' => API::getStatus()['unauthorized']['code'],

View File

@ -162,6 +162,10 @@ if ($record['editable'] == 1) {
echo ' echo '
<script> <script>
$(document).ready(function(){
$("#save").addClass("hide");
});
function update_permissions(id, value){ function update_permissions(id, value){
$.get( $.get(
globals.rootdir + "/actions.php?id_module='.$id_module.'&id_record='.$id_record.'&op=update_permission&idmodulo=" + id + "&permesso=" + value, globals.rootdir + "/actions.php?id_module='.$id_module.'&id_record='.$id_record.'&op=update_permission&idmodulo=" + id + "&permesso=" + value,

View File

@ -9,7 +9,7 @@ function menuSelection($element, $group_id, $depth, $perms_values, $perms_names)
++$depth; ++$depth;
$name = $element['title']; $name = $element['title'];
$submenus = $element['children']; $submenus = $element['all_children'];
if (!empty($submenus)) { if (!empty($submenus)) {
$temp = ''; $temp = '';

View File

@ -160,8 +160,7 @@ class AJAX
]; ];
// Database // Database
$database = Database::getConnection(); $dbo = $database = Database::getConnection();
$dbo = $database;
require $file; require $file;
@ -219,8 +218,7 @@ class AJAX
protected static function getSearchResults($file, $term) protected static function getSearchResults($file, $term)
{ {
// Database // Database
$database = Database::getConnection(); $dbo = $database = Database::getConnection();
$dbo = $database;
// Ricerca anagrafiche per ragione sociale per potere mostrare gli interventi, fatture, // Ricerca anagrafiche per ragione sociale per potere mostrare gli interventi, fatture,
// ordini, ecc della persona ricercata // ordini, ecc della persona ricercata
@ -280,8 +278,7 @@ class AJAX
protected static function getCompleteResults($file, $resource) protected static function getCompleteResults($file, $resource)
{ {
// Database // Database
$database = Database::getConnection(); $dbo = $database = Database::getConnection();
$dbo = $database;
ob_start(); ob_start();
require $file; require $file;

View File

@ -98,7 +98,7 @@ class API extends \Util\Singleton
$page = isset($request['page']) ? (int) $request['page'] : 0; $page = isset($request['page']) ? (int) $request['page'] : 0;
$length = setting('Lunghezza pagine per API'); $length = setting('Lunghezza pagine per API');
$database = Database::getConnection(); $dbo = $database = Database::getConnection();
$kind = 'retrieve'; $kind = 'retrieve';
$resources = self::getResources()[$kind]; $resources = self::getResources()[$kind];
@ -106,8 +106,6 @@ class API extends \Util\Singleton
try { try {
if (in_array($resource, array_keys($resources))) { if (in_array($resource, array_keys($resources))) {
$dbo = $database;
// Inclusione funzioni del modulo // Inclusione funzioni del modulo
include_once App::filepath(DOCROOT.'/modules/'.$resources[$resource].'|custom|', 'modutil.php'); include_once App::filepath(DOCROOT.'/modules/'.$resources[$resource].'|custom|', 'modutil.php');
@ -225,8 +223,7 @@ class API extends \Util\Singleton
} }
// Database // Database
$database = Database::getConnection(); $dbo = $database = Database::getConnection();
$dbo = $database;
$database->beginTransaction(); $database->beginTransaction();

View File

@ -135,6 +135,10 @@ class App
self::$config['debug'] = $value; self::$config['debug'] = $value;
} }
if (!isset(self::$config['debug'])) {
App::getConfig();
}
return self::$config['debug']; return self::$config['debug'];
} }

View File

@ -1,5 +1,7 @@
<?php <?php
use Models\User;
/** /**
* Classe per la gestione delle utenze. * Classe per la gestione delle utenze.
* *
@ -42,7 +44,7 @@ class Auth extends \Util\Singleton
protected static $is_brute; protected static $is_brute;
/** @var array Informazioni riguardanti l'utente autenticato */ /** @var array Informazioni riguardanti l'utente autenticato */
protected $infos = []; protected $user;
/** @var string Stato del tentativo di accesso */ /** @var string Stato del tentativo di accesso */
protected $current_status; protected $current_status;
/** @var string|null Nome del primo modulo su cui l'utente ha permessi di navigazione */ /** @var string|null Nome del primo modulo su cui l'utente ha permessi di navigazione */
@ -101,23 +103,23 @@ class Auth extends \Util\Singleton
$status = 'failed'; $status = 'failed';
$users = $database->fetchArray('SELECT id AS id_utente, password, enabled FROM zz_users WHERE username = :username LIMIT 1', [ $users = $database->fetchArray('SELECT id, password, enabled FROM zz_users WHERE username = :username LIMIT 1', [
':username' => $username, ':username' => $username,
]); ]);
if (!empty($users)) { if (!empty($users)) {
$user = $users[0]; $user = $users[0];
if (!empty($user['enabled'])) { if (!empty($user['enabled'])) {
$this->identifyUser($user['id_utente']); $this->identifyUser($user['id']);
$module = $this->getFirstModule(); $module = $this->getFirstModule();
if ( if (
$this->isAuthenticated() && $this->isAuthenticated() &&
$this->password_check($password, $user['password'], $user['id_utente']) && $this->password_check($password, $user['password'], $user['id']) &&
!empty($module) !empty($module)
) { ) {
// Accesso completato // Accesso completato
$log['id_utente'] = $this->infos['id_utente']; $log['id_utente'] = $this->user->id;
$status = 'success'; $status = 'success';
// Salvataggio nella sessione // Salvataggio nella sessione
@ -186,9 +188,11 @@ class Auth extends \Util\Singleton
protected function saveToSession() protected function saveToSession()
{ {
if (session_status() == PHP_SESSION_ACTIVE && $this->isAuthenticated()) { if (session_status() == PHP_SESSION_ACTIVE && $this->isAuthenticated()) {
foreach ($this->infos as $key => $value) { // Retrocompatibilità
foreach ($this->user as $key => $value) {
$_SESSION[$key] = $value; $_SESSION[$key] = $value;
} }
$_SESSION['id_utente'] = $this->user->id;
$identifier = md5($_SESSION['id_utente'].$_SERVER['HTTP_USER_AGENT']); $identifier = md5($_SESSION['id_utente'].$_SERVER['HTTP_USER_AGENT']);
if ((empty($_SESSION['last_active']) || time() < $_SESSION['last_active'] + (60 * 60)) && (empty($_SESSION['identifier']) || $_SESSION['identifier'] == $identifier)) { if ((empty($_SESSION['last_active']) || time() < $_SESSION['last_active'] + (60 * 60)) && (empty($_SESSION['identifier']) || $_SESSION['identifier'] == $identifier)) {
@ -208,15 +212,12 @@ class Auth extends \Util\Singleton
$database = Database::getConnection(); $database = Database::getConnection();
try { try {
$results = $database->fetchArray('SELECT id AS id_utente, idanagrafica, username, (SELECT nome FROM zz_groups WHERE zz_groups.id = zz_users.idgruppo) AS gruppo FROM zz_users WHERE id = :user_id AND enabled = 1 LIMIT 1', [ $results = $database->fetchArray('SELECT id, idanagrafica, username, (SELECT nome FROM zz_groups WHERE zz_groups.id = zz_users.idgruppo) AS gruppo FROM zz_users WHERE id = :user_id AND enabled = 1 LIMIT 1', [
':user_id' => $user_id, ':user_id' => $user_id,
], false, ['session' => false]); ], false, ['session' => false]);
if (!empty($results)) { if (!empty($results)) {
$results[0]['id'] = $results[0]['id_utente']; $this->user = User::with('group')->find($user_id);
$results[0]['is_admin'] = ($results[0]['gruppo'] == 'Amministratori');
$this->infos = $results[0];
} }
} catch (PDOException $e) { } catch (PDOException $e) {
$this->destory(); $this->destory();
@ -230,7 +231,7 @@ class Auth extends \Util\Singleton
*/ */
public function isAuthenticated() public function isAuthenticated()
{ {
return !empty($this->infos); return !empty($this->user);
} }
/** /**
@ -240,17 +241,17 @@ class Auth extends \Util\Singleton
*/ */
public function isAdmin() public function isAdmin()
{ {
return $this->isAuthenticated() && !empty($this->infos['is_admin']); return $this->isAuthenticated() && !empty($this->user->is_admin);
} }
/** /**
* Restituisce le informazioni riguardanti l'utente autenticato. * Restituisce le informazioni riguardanti l'utente autenticato.
* *
* @return array * @return User
*/ */
public function getUser() public function getUser()
{ {
return $this->infos; return $this->user;
} }
/** /**
@ -277,7 +278,7 @@ class Auth extends \Util\Singleton
$database = Database::getConnection(); $database = Database::getConnection();
$tokens = $database->fetchArray('SELECT `token` FROM `zz_tokens` WHERE `enabled` = 1 AND `id_utente` = :user_id', [ $tokens = $database->fetchArray('SELECT `token` FROM `zz_tokens` WHERE `enabled` = 1 AND `id_utente` = :user_id', [
':user_id' => $user['id_utente'], ':user_id' => $user->id,
]); ]);
// Generazione del token per l'utente // Generazione del token per l'utente
@ -285,7 +286,7 @@ class Auth extends \Util\Singleton
$token = secure_random_string(); $token = secure_random_string();
$database->insert('zz_tokens', [ $database->insert('zz_tokens', [
'id_utente' => $user['id_utente'], 'id_utente' => $user->id,
'token' => $token, 'token' => $token,
]); ]);
} else { } else {
@ -302,7 +303,7 @@ class Auth extends \Util\Singleton
public function destory() public function destory()
{ {
if ($this->isAuthenticated() || !empty($_SESSION['id_utente'])) { if ($this->isAuthenticated() || !empty($_SESSION['id_utente'])) {
$this->infos = []; $this->user = [];
$this->first_module = null; $this->first_module = null;
session_unset(); session_unset();
@ -396,7 +397,7 @@ class Auth extends \Util\Singleton
/** /**
* Restituisce le informazioni riguardanti l'utente autenticato. * Restituisce le informazioni riguardanti l'utente autenticato.
* *
* @return array * @return User
*/ */
public static function user() public static function user()
{ {

View File

@ -130,8 +130,7 @@ class Mail extends PHPMailer\PHPMailer\PHPMailer
{ {
$template = self::getTemplate($template); $template = self::getTemplate($template);
$database = Database::getConnection(); $dbo = $database = Database::getConnection();
$dbo = $database;
// Lettura delle variabili nei singoli moduli // Lettura delle variabili nei singoli moduli
$variables = include Modules::filepath($template['id_module'], 'variables.php'); $variables = include Modules::filepath($template['id_module'], 'variables.php');

28
src/Models/Clause.php Normal file
View File

@ -0,0 +1,28 @@
<?php
namespace Models;
use Illuminate\Database\Eloquent\Model;
use App;
class Clause extends Model
{
protected $table = 'zz_group_module';
/* Relazioni Eloquent */
public function groups()
{
return $this->hasMany(Group::class, 'idgruppo');
}
public function module()
{
return $this->belongsTo(Module::class, 'idmodule')->first();
}
public function getClauseAttribute($value)
{
return App::replacePlaceholder($value);
}
}

32
src/Models/Group.php Normal file
View File

@ -0,0 +1,32 @@
<?php
namespace Models;
use Auth;
use Illuminate\Database\Eloquent\Model;
class Group extends Model
{
protected $table = 'zz_groups';
/* Relazioni Eloquent */
public function users()
{
return $this->hasMany(User::class, 'idgruppo');
}
public function modules()
{
if ($this->nome == 'Amministratori') {
return Module::all();
} else {
return $this->belongsToMany(Module::class, 'zz_permissions', 'idgruppo', 'idmodule')->withPivot('permessi')->get();
}
}
public function views()
{
return $this->belongsToMany(View::class, 'zz_group_view', 'id_gruppo', 'id_vista');
}
}

17
src/Models/Log.php Normal file
View File

@ -0,0 +1,17 @@
<?php
namespace Models;
use Illuminate\Database\Eloquent\Model;
class Log extends Model
{
protected $table = 'zz_logs';
/* Relazioni Eloquent */
public function user()
{
return $this->belongsTo(User::class, 'id_utente')->first();
}
}

148
src/Models/Module.php Normal file
View File

@ -0,0 +1,148 @@
<?php
namespace Models;
use App;
use Auth;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
class Module extends Model
{
protected $table = 'zz_modules';
protected $appends = [
'permission',
'option',
];
protected $hidden = [
'options',
'options2',
];
protected static function boot()
{
parent::boot();
static::addGlobalScope('enabled', function (Builder $builder) {
$builder->where('enabled', true);
});
}
/**
* Restituisce i permessi relativi all'account in utilizzo.
*
* @return string
*/
public function getPermissionAttribute()
{
$result = Auth::user()->is_admin ? 'rw' : $this->pivot->permessi;
return !empty($result) ? $result : '-';
}
/**
* Restituisce i permessi relativi all'account in utilizzo.
*
* @return string
*/
public function getViewsAttribute()
{
$user = Auth::user();
$views = database()->fetchArray('SELECT * FROM `zz_views` WHERE `id_module` = :module_id AND
`id` IN (
SELECT `id_vista` FROM `zz_group_view` WHERE `id_gruppo` = (
SELECT `idgruppo` FROM `zz_users` WHERE `id` = :user_id
))
ORDER BY `order` ASC', [
'module_id' => $this->id,
'user_id' => $user->id,
]);
return $views;
}
public function getOptionAttribute()
{
return !empty($this->options) ? $this->options : $this->options2;
}
public function getOptionsAttribute($value)
{
return App::replacePlaceholder($value);
}
public function getOptions2Attribute($value)
{
return App::replacePlaceholder($value);
}
/* Relazioni Eloquent */
public function plugins()
{
return $this->hasMany(Plugin::class, 'idmodule_to')->active();
}
public function prints()
{
return $this->hasMany(PrintTemplate::class, 'id_module');
}
public function views()
{
return $this->hasMany(View::class, 'id_module');
}
public function groups()
{
return $this->belongsToMany(Group::class, 'zz_permissions', 'idmodule', 'idgruppo');
}
public function clauses()
{
return $this->hasMany(Clause::class, 'idmodule');
}
public function children()
{
return $this->hasMany(self::class, 'parent')
->orderBy('order');
}
public function parent()
{
return $this->belongsTo(self::class, 'parent');
}
public function allParents()
{
return $this->parent()->with('allParents');
}
public function allChildren()
{
return $this->children()->with('allChildren');
}
/* Metodi statici */
public static function getHierarchy()
{
return self::with('allChildren')
->whereNull('parent')
->orderBy('order')
->get();
}
public static function getCompleteHierarchy()
{
return self::withoutGlobalScope('enabled')
->with('allChildren')
->whereNull('parent')
->orderBy('order')
->get();
}
}

61
src/Models/Plugin.php Normal file
View File

@ -0,0 +1,61 @@
<?php
namespace Models;
use Illuminate\Database\Eloquent\Model;
use App;
class Plugin extends Model
{
protected $table = 'zz_plugins';
protected $appends = [
'option',
];
protected $hidden = [
'options',
'options2',
];
protected static function boot()
{
parent::boot();
static::addGlobalScope('enabled', function (Builder $builder) {
$builder->where('enabled', true);
});
}
public function getModuleDirAttribute()
{
return $this->originalModule()->directory;
}
public function getOptionAttribute()
{
return !empty($this->options) ? $this->options : $this->options2;
}
public function getOptionsAttribute($value)
{
return App::replacePlaceholder($value, app('parent_id'));
}
public function getOptions2Attribute($value)
{
return App::replacePlaceholder($value, app('parent_id'));
}
/* Relazioni Eloquent */
public function originalModule()
{
return $this->belongsTo(Module::class, 'idmodule_from')->first();
}
public function module()
{
return $this->belongsTo(Module::class, 'idmodule_to')->first();
}
}

View File

@ -0,0 +1,17 @@
<?php
namespace Models;
use Illuminate\Database\Eloquent\Model;
class PrintTemplate extends Model
{
protected $table = 'zz_prints';
/* Relazioni Eloquent */
public function module()
{
return $this->belongsTo(Module::class, 'id_module')->first();
}
}

56
src/Models/Setting.php Normal file
View File

@ -0,0 +1,56 @@
<?php
namespace Models;
use Illuminate\Database\Eloquent\Model;
class Setting extends Model
{
protected $table = 'zz_settings';
protected $appends = [
'description',
];
public function getDescriptionAttribute()
{
$value = $this->valore;
// Valore corrispettivo
$query = str_replace('query=', '', $this->tipo);
if ($query != $this->tipo) {
$data = $database->fetchArray($query);
if (!empty($data)) {
$value = $data[0]['descrizione'];
}
}
return $value;
}
/**
* Restituisce il valore corrente dell'impostazione ricercata.
* Se l'impostazione viene cercata più volte, il primo valore individuato viene salvato; per costringere a aggiornare i contenuto, usare l'opzione $again.
*
* @param string $nome
* @param string $section
* @param string $descrizione
* @param bool $again
*
* @return string
*/
public static function get($name, $section = null)
{
$find = [
'nome' => $name,
];
if (!empty($section)) {
$find['section'] = $section;
}
$setting = self::where($find)->first();
return $setting->valore;
}
}

71
src/Models/User.php Normal file
View File

@ -0,0 +1,71 @@
<?php
namespace Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $table = 'zz_users';
protected $appends = [
'is_admin',
'gruppo',
];
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
protected $is_admin;
protected $gruppo;
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function getIsAdminAttribute()
{
if (!isset($this->is_admin)) {
$this->is_admin = $this->getGruppoAttribute() == 'Amministratori';
}
return $this->is_admin;
}
public function getGruppoAttribute()
{
if (!isset($this->gruppo)) {
$this->gruppo = $this->group->nome;
}
return $this->gruppo;
}
/* Relazioni Eloquent */
public function group()
{
return $this->belongsTo(Group::class, 'idgruppo');
}
public function logs()
{
return $this->hasMany(Log::class, 'id_utente');
}
public function modules()
{
return $this->group->modules();
}
}

28
src/Models/View.php Normal file
View File

@ -0,0 +1,28 @@
<?php
namespace Models;
use Illuminate\Database\Eloquent\Model;
use App;
class View extends Model
{
protected $table = 'zz_views';
public function getQueryAttribute($value)
{
return App::replacePlaceholder($value);
}
/* Relazioni Eloquent */
public function groups()
{
return $this->belongsToMany(Group::class, 'zz_group_view', 'id_vista', 'id_gruppo');
}
public function module()
{
return $this->belongsTo(Module::class, 'id_module');
}
}

View File

@ -1,5 +1,7 @@
<?php <?php
use Models\Module;
/** /**
* Classe per la gestione delle informazioni relative ai moduli installati. * Classe per la gestione delle informazioni relative ai moduli installati.
* *
@ -10,19 +12,14 @@ class Modules
/** @var array Elenco dei moduli disponibili */ /** @var array Elenco dei moduli disponibili */
protected static $modules = []; protected static $modules = [];
protected static $references = []; protected static $references = [];
/** @var array Elenco delle condizioni aggiuntive disponibili */ /** @var array Elenco delle condizioni aggiuntive disponibili */
protected static $additionals = []; protected static $additionals = [];
/** @var array Elenco dei segmenti disponibili */ /** @var array Elenco dei segmenti disponibili */
protected static $segments = []; protected static $segments = [];
/** @var array Elenco delle query generiche dei moduli */
protected static $queries = [];
/** @var array Elenco gerarchico dei moduli */ /** @var array Elenco gerarchico dei moduli */
protected static $hierarchy = []; protected static $hierarchy;
/** @var array Profondità dell'elenco gerarchico */
protected static $depth;
/** @var array Struttura HTML dedicata al menu principale */
protected static $menu;
/** /**
* Restituisce tutte le informazioni di tutti i moduli installati. * Restituisce tutte le informazioni di tutti i moduli installati.
@ -32,31 +29,11 @@ class Modules
public static function getModules() public static function getModules()
{ {
if (empty(self::$modules)) { if (empty(self::$modules)) {
$database = Database::getConnection();
$user = Auth::user();
$results = $database->fetchArray('SELECT * FROM `zz_modules` LEFT JOIN (SELECT `idmodule`, `permessi` FROM `zz_permissions` WHERE `idgruppo` = (SELECT `idgruppo` FROM `zz_users` WHERE `id` = '.prepare($user['id_utente']).')) AS `zz_permissions` ON `zz_modules`.`id`=`zz_permissions`.`idmodule`');
$modules = []; $modules = [];
$references = []; $references = [];
$results = Auth::user()->modules();
foreach ($results as $result) { foreach ($results as $result) {
$result['options'] = App::replacePlaceholder($result['options']);
$result['options2'] = App::replacePlaceholder($result['options2']);
$result['option'] = empty($result['options2']) ? $result['options'] : $result['options2'];
if (empty($result['permessi'])) {
if (Auth::admin()) {
$result['permessi'] = 'rw';
} else {
$result['permessi'] = '-';
}
}
unset($result['idmodule']);
$modules[$result['id']] = $result; $modules[$result['id']] = $result;
$references[$result['name']] = $result['id']; $references[$result['name']] = $result['id'];
} }
@ -79,7 +56,7 @@ class Modules
$modules = self::getModules(); $modules = self::getModules();
foreach ($modules as $key => $module) { foreach ($modules as $key => $module) {
if ($module['permessi'] == '-') { if ($module->permission == '-') {
unset($modules[$key]); unset($modules[$key]);
} }
} }
@ -92,7 +69,7 @@ class Modules
* *
* @param string|int $module * @param string|int $module
* *
* @return array * @return Module
*/ */
public static function get($module) public static function get($module)
{ {
@ -114,7 +91,7 @@ class Modules
*/ */
public static function getPermission($module) public static function getPermission($module)
{ {
return self::get($module)['permessi']; return self::get($module)->permission ?? '-';
} }
/** /**
@ -228,77 +205,15 @@ class Modules
* *
* @return array * @return array
*/ */
public static function getHierarchy($depth = 3) public static function getHierarchy()
{ {
if (empty(self::$hierarchy) || self::$depth != $depth) { if (!isset(self::$hierarchy)) {
$database = Database::getConnection(); self::$hierarchy = Module::getCompleteHierarchy()->toArray();
$depth = ($depth < 2) ? 2 : $depth;
$fields = [];
for ($i = 0; $i < $depth; ++$i) {
$fields[] = '`t'.$i."`.`id` AS 't".$i.".id'";
}
$query = 'SELECT '.implode(', ', $fields).' FROM `zz_modules` AS `t0`';
for ($i = 1; $i < $depth; ++$i) {
$query .= ' LEFT JOIN `zz_modules` AS `t'.$i.'` ON `t'.$i.'`.`parent` = `t'.($i - 1).'`.`id`';
}
$query .= ' WHERE `t0`.`parent` IS NULL ORDER BY ';
for ($i = 0; $i < $depth; ++$i) {
$query .= '`t'.$i.'`.`order` ASC, `t'.$i.'`.`id` ASC ';
if ($i != $depth - 1) {
$query .= ', ';
}
}
$modules = $database->fetchArray($query);
$hierarchy = [];
foreach ($modules as $module) {
$hierarchy = self::buildArray($module, $hierarchy);
}
self::$depth = $depth;
self::$hierarchy = $hierarchy;
} }
return self::$hierarchy; return self::$hierarchy;
} }
/**
* Restituisce l'elaborazione dell'array secondo una struttura ad albero (molteplici root).
*
* @param int $id
* @param array $data
* @param int $actual
*
* @return array
*/
protected static function buildArray($module, $data = [], $actual = 0)
{
if (!empty($module['t'.$actual.'.id'])) {
$pos = array_search($module['t'.$actual.'.id'], array_column($data, 'id'));
if ($pos === false && !empty($module['t'.$actual.'.id'])) {
$array = self::get($module['t'.$actual.'.id']);
$array['children'] = [];
$data[] = $array;
$pos = count($data) - 1;
}
if (!empty($module['t'.($actual + 1).'.id'])) {
$data[$pos]['children'] = self::buildArray($module, $data[$pos]['children'], $actual + 1);
}
}
return $data;
}
/** /**
* Restituisce il menu principale del progetto. * Restituisce il menu principale del progetto.
* *
@ -308,20 +223,17 @@ class Modules
*/ */
public static function getMainMenu($depth = 3) public static function getMainMenu($depth = 3)
{ {
if (empty(self::$menu) || self::$depth != $depth) { $menus = self::getHierarchy();
$menus = self::getHierarchy($depth);
$module_name = App::getCurrentModule()['name']; $module = App::getCurrentModule();
$module_name = isset($module) ? $module->name : '';
$result = ''; $result = '';
foreach ($menus as $menu) { foreach ($menus as $menu) {
$result .= self::sidebarMenu($menu, isset($module_name) ? $module_name : '')[0]; $result .= self::sidebarMenu($menu, $module_name, $depth)[0];
} }
self::$menu = $result; return $result;
}
return self::$menu;
} }
/** /**
@ -329,23 +241,28 @@ class Modules
* *
* @param array $element * @param array $element
* @param int $actual * @param int $actual
* @param int $max_depth
* @param int $actual_depth
* *
* @return string * @return string
*/ */
protected static function sidebarMenu($element, $actual = null) protected static function sidebarMenu($element, $actual = null, $max_depth = 3, $actual_depth = 0)
{ {
$options = ($element['options2'] != '') ? $element['options2'] : $element['options']; if ($actual_depth >= $max_depth) {
$link = ($options != '' && $options != 'menu') ? ROOTDIR.'/controller.php?id_module='.$element['id'] : 'javascript:;'; return '';
}
$link = (!empty($element['option']) && $element['option'] != 'menu') ? ROOTDIR.'/controller.php?id_module='.$element['id'] : 'javascript:;';
$title = $element['title']; $title = $element['title'];
$target = '_self'; // $target = ($element['new'] == 1) ? '_blank' : '_self'; $target = '_self'; // $target = ($element['new'] == 1) ? '_blank' : '_self';
$active = ($actual == $element['name']); $active = ($actual == $element['name']);
$show = (self::getPermission($element['id']) != '-' && !empty($element['enabled'])) ? true : false; $show = (self::getPermission($element['id']) != '-' && !empty($element['enabled'])) ? true : false;
$submenus = $element['children']; $submenus = $element['all_children'];
if (!empty($submenus)) { if (!empty($submenus)) {
$temp = ''; $temp = '';
foreach ($submenus as $submenu) { foreach ($submenus as $submenu) {
$r = self::sidebarMenu($submenu, $actual); $r = self::sidebarMenu($submenu, $actual, $actual_depth + 1);
$active = $active || $r[1]; $active = $active || $r[1];
if (!$show && $r[2]) { if (!$show && $r[2]) {
$link = 'javascript:;'; $link = 'javascript:;';
@ -410,7 +327,7 @@ class Modules
$extra .= !empty($blank) ? ' target="_blank"' : ''; $extra .= !empty($blank) ? ' target="_blank"' : '';
if (!empty($module) && in_array($module['permessi'], ['r', 'rw'])) { if (!empty($module) && in_array($module->permission, ['r', 'rw'])) {
$link = !empty($id_record) ? 'editor.php?id_module='.$module['id'].'&id_record='.$id_record : 'controller.php?id_module='.$module['id']; $link = !empty($id_record) ? 'editor.php?id_module='.$module['id'].'&id_record='.$id_record : 'controller.php?id_module='.$module['id'];
return '<a href="'.ROOTDIR.'/'.$link.'" '.$extra.'>'.$testo.'</a>'; return '<a href="'.ROOTDIR.'/'.$link.'" '.$extra.'>'.$testo.'</a>';

View File

@ -208,10 +208,7 @@ class Prints
$infos = self::get($id_print); $infos = self::get($id_print);
$options = self::readOptions($infos['options']); $options = self::readOptions($infos['options']);
$database = Database::getConnection(); $dbo = $database = Database::getConnection();
$dbo = $database;
$docroot = DOCROOT;
$user = Auth::user(); $user = Auth::user();
@ -272,10 +269,7 @@ class Prints
$infos = self::get($id_print); $infos = self::get($id_print);
$options = self::readOptions($infos['options']); $options = self::readOptions($infos['options']);
$database = Database::getConnection(); $dbo = $database = Database::getConnection();
$dbo = $database;
$docroot = DOCROOT;
$user = Auth::user(); $user = Auth::user();

View File

@ -463,8 +463,7 @@ class Update
*/ */
protected static function executeScript($script) protected static function executeScript($script)
{ {
$database = Database::getConnection(); $dbo = $database = Database::getConnection();
$dbo = $database;
// Informazioni relative a MySQL // Informazioni relative a MySQL
$mysql_ver = $database->getMySQLVersion(); $mysql_ver = $database->getMySQLVersion();

View File

@ -244,3 +244,6 @@ UPDATE `zz_modules` SET `options` = 'SELECT |select| FROM zz_smtps WHERE 1=1 AND
-- Ridenominazione enabled in visible su zz_views -- Ridenominazione enabled in visible su zz_views
ALTER TABLE `zz_views` CHANGE `enabled` `visible` BOOLEAN NOT NULL DEFAULT 1; ALTER TABLE `zz_views` CHANGE `enabled` `visible` BOOLEAN NOT NULL DEFAULT 1;
-- Rimozione permessi negati (comportamento di default)
DELETE FROM `zz_permissions` WHERE `permessi` = '-';