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;
}
$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()');
$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 = [];
foreach ($datas as $data) {

View File

@ -60,7 +60,7 @@ if (!API::isAPIRequest()) {
$handlers[] = new StreamHandler($docroot.'/logs/setup.log', Monolog\Logger::EMERGENCY);
// Impostazioni di debug
if (!empty($debug)) {
if (App::debug()) {
// Ignora gli avvertimenti e le informazioni relative alla deprecazione di componenti
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)
if (empty($debug)) {
if (!App::debug()) {
error_reporting(0);
}
// Imposta il formato di salvataggio dei log
$pattern = '[%datetime%] %channel%.%level_name%: %message%';
if (!empty($debug)) {
if (App::debug()) {
$pattern .= ' %context%';
}
$pattern .= PHP_EOL.'%extra% '.PHP_EOL;
$monologFormatter = new Monolog\Formatter\LineFormatter($pattern);
if (!empty($debug)) {
if (App::debug()) {
$monologFormatter->includeStacktraces(true);
}
@ -111,6 +111,9 @@ foreach ($handlers as $handler) {
// Imposta Monolog come gestore degli errori
Monolog\ErrorHandler::register($logger);
// Database
$dbo = $database = Database::getConnection();
// Inizializzazione della sessione
if (!API::isAPIRequest()) {
// Sicurezza della sessioni
@ -119,6 +122,20 @@ if (!API::isAPIRequest()) {
session_set_cookie_params(0, $rootdir, null, isHTTPS(true));
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
@ -133,8 +150,6 @@ $translator->setLocale($lang, $formatter);
$version = Update::getVersion();
$revision = Update::getRevision();
$dbo = Database::getConnection();
// Controllo sulla presenza dei permessi di accesso basilari
$continue = $dbo->isInstalled() && !Update::isUpdateAvailable() && (Auth::check() || API::isAPIRequest());
@ -156,20 +171,6 @@ if (!API::isAPIRequest()) {
// Impostazioni di Content-Type e Charset Header
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
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');
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 '
<div class="box box-warning box-solid text-center info-active hide">
@ -325,7 +325,7 @@ if ($read_only || !empty($block_edit)) {
$(".btn-success, button[type=submit]").bind("click", function() {
content_was_modified = false;
});
$( "form" ).bind( "submit", function() {
content_was_modified = false;
})
@ -339,14 +339,14 @@ if ($read_only || !empty($block_edit)) {
return dialogText;
}
};
window.addEventListener("unload", function(e) {
//console.log(e);
$("#main_loading").show();
});
<?php

View File

@ -31,7 +31,7 @@ echo '
if (Auth::admin()) {
$q = 'SELECT * FROM `zz_logs` ORDER BY `created_at` DESC LIMIT 0, 100';
} 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);
$n = sizeof($rs);

View File

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

View File

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

View File

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

View File

@ -128,7 +128,7 @@ switch (post('op')) {
case 'delete-bulk':
if ($debug) {
if (App::debug()) {
foreach ($id_records as $id) {
$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));

View File

@ -49,7 +49,7 @@ switch (post('op')) {
case 'delete-bulk':
if ($debug) {
if (App::debug()) {
foreach ($id_records as $id) {
$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));

View File

@ -155,20 +155,26 @@ switch (filter('op')) {
$idmodulo = filter('idmodulo');
// Verifico che ci sia il permesso per questo gruppo
$rs = $dbo->fetchArray('SELECT * FROM zz_permissions WHERE idgruppo='.prepare($id_record).' AND idmodule='.prepare($idmodulo));
if (count($rs) == 0) {
$query = 'INSERT INTO zz_permissions(idgruppo, idmodule, permessi) VALUES('.prepare($id_record).', '.prepare($idmodulo).', '.prepare($permessi).')';
} else {
$query = 'UPDATE zz_permissions SET permessi='.prepare($permessi).' WHERE id='.prepare($rs[0]['id']);
}
// 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).')');
if (empty($count[0]['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).')');
foreach ($results as $result) {
$dbo->attach('zz_group_view', ['id_vista' => $result['id_vista']], ['id_gruppo' => $id_record]);
if ($permessi != '-') {
$rs = $dbo->fetchArray('SELECT * FROM zz_permissions WHERE idgruppo='.prepare($id_record).' AND idmodule='.prepare($idmodulo));
if (empty($rs)) {
$query = 'INSERT INTO zz_permissions(idgruppo, idmodule, permessi) VALUES('.prepare($id_record).', '.prepare($idmodulo).', '.prepare($permessi).')';
} else {
$query = 'UPDATE zz_permissions SET permessi='.prepare($permessi).' WHERE id='.prepare($rs[0]['id']);
}
// Aggiunta dei permessi relativi alle viste
$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)) {
$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) {
$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);

View File

@ -8,7 +8,7 @@ switch ($resource) {
$token = Auth::getInstance()->getToken();
// 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;
@ -30,7 +30,7 @@ switch ($resource) {
case 'logout':
if (!empty($request['token']) && !empty($user)) {
// 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 {
$response = [
'status' => API::getStatus()['unauthorized']['code'],

View File

@ -162,6 +162,10 @@ if ($record['editable'] == 1) {
echo '
<script>
$(document).ready(function(){
$("#save").addClass("hide");
});
function update_permissions(id, value){
$.get(
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;
$name = $element['title'];
$submenus = $element['children'];
$submenus = $element['all_children'];
if (!empty($submenus)) {
$temp = '';

View File

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

View File

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

View File

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

View File

@ -1,5 +1,7 @@
<?php
use Models\User;
/**
* Classe per la gestione delle utenze.
*
@ -42,7 +44,7 @@ class Auth extends \Util\Singleton
protected static $is_brute;
/** @var array Informazioni riguardanti l'utente autenticato */
protected $infos = [];
protected $user;
/** @var string Stato del tentativo di accesso */
protected $current_status;
/** @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';
$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,
]);
if (!empty($users)) {
$user = $users[0];
if (!empty($user['enabled'])) {
$this->identifyUser($user['id_utente']);
$this->identifyUser($user['id']);
$module = $this->getFirstModule();
if (
$this->isAuthenticated() &&
$this->password_check($password, $user['password'], $user['id_utente']) &&
$this->password_check($password, $user['password'], $user['id']) &&
!empty($module)
) {
// Accesso completato
$log['id_utente'] = $this->infos['id_utente'];
$log['id_utente'] = $this->user->id;
$status = 'success';
// Salvataggio nella sessione
@ -186,9 +188,11 @@ class Auth extends \Util\Singleton
protected function saveToSession()
{
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['id_utente'] = $this->user->id;
$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)) {
@ -208,15 +212,12 @@ class Auth extends \Util\Singleton
$database = Database::getConnection();
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,
], false, ['session' => false]);
if (!empty($results)) {
$results[0]['id'] = $results[0]['id_utente'];
$results[0]['is_admin'] = ($results[0]['gruppo'] == 'Amministratori');
$this->infos = $results[0];
$this->user = User::with('group')->find($user_id);
}
} catch (PDOException $e) {
$this->destory();
@ -230,7 +231,7 @@ class Auth extends \Util\Singleton
*/
public function isAuthenticated()
{
return !empty($this->infos);
return !empty($this->user);
}
/**
@ -240,17 +241,17 @@ class Auth extends \Util\Singleton
*/
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.
*
* @return array
* @return User
*/
public function getUser()
{
return $this->infos;
return $this->user;
}
/**
@ -277,7 +278,7 @@ class Auth extends \Util\Singleton
$database = Database::getConnection();
$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
@ -285,7 +286,7 @@ class Auth extends \Util\Singleton
$token = secure_random_string();
$database->insert('zz_tokens', [
'id_utente' => $user['id_utente'],
'id_utente' => $user->id,
'token' => $token,
]);
} else {
@ -302,7 +303,7 @@ class Auth extends \Util\Singleton
public function destory()
{
if ($this->isAuthenticated() || !empty($_SESSION['id_utente'])) {
$this->infos = [];
$this->user = [];
$this->first_module = null;
session_unset();
@ -396,7 +397,7 @@ class Auth extends \Util\Singleton
/**
* Restituisce le informazioni riguardanti l'utente autenticato.
*
* @return array
* @return User
*/
public static function user()
{

View File

@ -130,8 +130,7 @@ class Mail extends PHPMailer\PHPMailer\PHPMailer
{
$template = self::getTemplate($template);
$database = Database::getConnection();
$dbo = $database;
$dbo = $database = Database::getConnection();
// Lettura delle variabili nei singoli moduli
$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
use Models\Module;
/**
* Classe per la gestione delle informazioni relative ai moduli installati.
*
@ -10,19 +12,14 @@ class Modules
/** @var array Elenco dei moduli disponibili */
protected static $modules = [];
protected static $references = [];
/** @var array Elenco delle condizioni aggiuntive disponibili */
protected static $additionals = [];
/** @var array Elenco dei segmenti disponibili */
protected static $segments = [];
/** @var array Elenco delle query generiche dei moduli */
protected static $queries = [];
/** @var array Elenco gerarchico dei moduli */
protected static $hierarchy = [];
/** @var array Profondità dell'elenco gerarchico */
protected static $depth;
/** @var array Struttura HTML dedicata al menu principale */
protected static $menu;
protected static $hierarchy;
/**
* Restituisce tutte le informazioni di tutti i moduli installati.
@ -32,31 +29,11 @@ class Modules
public static function getModules()
{
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 = [];
$references = [];
$results = Auth::user()->modules();
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;
$references[$result['name']] = $result['id'];
}
@ -79,7 +56,7 @@ class Modules
$modules = self::getModules();
foreach ($modules as $key => $module) {
if ($module['permessi'] == '-') {
if ($module->permission == '-') {
unset($modules[$key]);
}
}
@ -92,7 +69,7 @@ class Modules
*
* @param string|int $module
*
* @return array
* @return Module
*/
public static function get($module)
{
@ -114,7 +91,7 @@ class Modules
*/
public static function getPermission($module)
{
return self::get($module)['permessi'];
return self::get($module)->permission ?? '-';
}
/**
@ -228,77 +205,15 @@ class Modules
*
* @return array
*/
public static function getHierarchy($depth = 3)
public static function getHierarchy()
{
if (empty(self::$hierarchy) || self::$depth != $depth) {
$database = Database::getConnection();
$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;
if (!isset(self::$hierarchy)) {
self::$hierarchy = Module::getCompleteHierarchy()->toArray();
}
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.
*
@ -308,20 +223,17 @@ class Modules
*/
public static function getMainMenu($depth = 3)
{
if (empty(self::$menu) || self::$depth != $depth) {
$menus = self::getHierarchy($depth);
$menus = self::getHierarchy();
$module_name = App::getCurrentModule()['name'];
$module = App::getCurrentModule();
$module_name = isset($module) ? $module->name : '';
$result = '';
foreach ($menus as $menu) {
$result .= self::sidebarMenu($menu, isset($module_name) ? $module_name : '')[0];
}
self::$menu = $result;
$result = '';
foreach ($menus as $menu) {
$result .= self::sidebarMenu($menu, $module_name, $depth)[0];
}
return self::$menu;
return $result;
}
/**
@ -329,23 +241,28 @@ class Modules
*
* @param array $element
* @param int $actual
* @param int $max_depth
* @param int $actual_depth
*
* @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'];
$link = ($options != '' && $options != 'menu') ? ROOTDIR.'/controller.php?id_module='.$element['id'] : 'javascript:;';
if ($actual_depth >= $max_depth) {
return '';
}
$link = (!empty($element['option']) && $element['option'] != 'menu') ? ROOTDIR.'/controller.php?id_module='.$element['id'] : 'javascript:;';
$title = $element['title'];
$target = '_self'; // $target = ($element['new'] == 1) ? '_blank' : '_self';
$active = ($actual == $element['name']);
$show = (self::getPermission($element['id']) != '-' && !empty($element['enabled'])) ? true : false;
$submenus = $element['children'];
$submenus = $element['all_children'];
if (!empty($submenus)) {
$temp = '';
foreach ($submenus as $submenu) {
$r = self::sidebarMenu($submenu, $actual);
$r = self::sidebarMenu($submenu, $actual, $actual_depth + 1);
$active = $active || $r[1];
if (!$show && $r[2]) {
$link = 'javascript:;';
@ -410,7 +327,7 @@ class Modules
$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'];
return '<a href="'.ROOTDIR.'/'.$link.'" '.$extra.'>'.$testo.'</a>';

View File

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

View File

@ -463,8 +463,7 @@ class Update
*/
protected static function executeScript($script)
{
$database = Database::getConnection();
$dbo = $database;
$dbo = $database = Database::getConnection();
// Informazioni relative a MySQL
$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
ALTER TABLE `zz_views` CHANGE `enabled` `visible` BOOLEAN NOT NULL DEFAULT 1;
-- Rimozione permessi negati (comportamento di default)
DELETE FROM `zz_permissions` WHERE `permessi` = '-';