Generalizzazione di varie sezioni

Generalizzazione della gestione delle query di Moduli e Plugin.
Miglioramento della gestione degli assets (ora gestiti dalla classe App e personalizzabili nella configurazione).
Miglioramento del nome della gestione di alcune variabili, con relativa individuazione (classe App).
Rimozione codice deprecato nel core.
This commit is contained in:
Thomas Zilio 2018-02-14 11:10:03 +01:00
parent a6844f502b
commit fdad40cb2b
14 changed files with 375 additions and 384 deletions

View File

@ -13,18 +13,14 @@ array_shift($columns);
// Lettura parametri iniziali // Lettura parametri iniziali
if (!empty($id_plugin)) { if (!empty($id_plugin)) {
$total = Plugins::getQuery($id_plugin); $element = Plugins::get($id_plugin);
$total['query'] = Modules::replacePlaceholder($total['query'], $id_parent);
} else { } else {
$total = Modules::getQuery($id_module); $element = Modules::get($id_module);
} }
$total = App::readQuery($element);
// Lettura parametri modulo // Lettura parametri modulo
$module_query = $total['query']; $result_query = $total['query'];
$module_query = str_replace('|period_start|', $_SESSION['period_start'], $module_query);
$module_query = str_replace('|period_end|', $_SESSION['period_end'], $module_query);
$module_query = str_replace('|select|', $total['select'], $module_query);
// Predisposizione dela risposta // Predisposizione dela risposta
$results = []; $results = [];
@ -33,12 +29,12 @@ $results['recordsTotal'] = 0;
$results['recordsFiltered'] = 0; $results['recordsFiltered'] = 0;
$results['summable'] = []; $results['summable'] = [];
if (!empty($module_query) && $module_query != 'menu' && $module_query != 'custom') { if (!empty($result_query) && $result_query != 'menu' && $result_query != 'custom') {
// Conteggio totale // Conteggio totale
$query = 'SELECT COUNT(*) as `tot` FROM ('.$module_query.') AS `count`'; $count_query = 'SELECT COUNT(*) as `tot` FROM ('.$result_query.') AS `count`';
$cont = $dbo->fetchArray($query); $count = $dbo->fetchArray($count_query);
if (!empty($cont)) { if (!empty($count)) {
$results['recordsTotal'] = $cont[0]['tot']; $results['recordsTotal'] = $count[0]['tot'];
} }
// Filtri di ricerica // Filtri di ricerica
@ -61,48 +57,42 @@ if (!empty($module_query) && $module_query != 'menu' && $module_query != 'custom
} }
} }
} }
/*filtro sezionali*/
if (isset($_SESSION['entrata']['idsezionale']) and (($modules_info[$id_module]['name'] == 'Fatture di vendita') or ($modules_info[$id_module]['name'] == 'Laboratorio') or ($modules_info[$id_module]['name'] == 'Ticket'))) {
/*filtro sezionali*/ $result_query = str_replace('1=1', " 1=1 AND idsezionale = '".$_SESSION['entrata']['idsezionale']."' ", $result_query);
if (isset($_SESSION['entrata']['idsezionale']) AND (($modules_info[$id_module]['name'] == 'Fatture di vendita') or ($modules_info[$id_module]['name'] == 'Laboratorio') or ($modules_info[$id_module]['name'] == 'Ticket')) ){ }
$module_query = str_replace('1=1', " 1=1 AND idsezionale = '".$_SESSION['entrata']["idsezionale"]."' ", $module_query); if (isset($_SESSION['uscita']['idsezionale']) and ($modules_info[$id_module]['name'] == 'Fatture di acquisto')) {
$result_query = str_replace('1=1', " 1=1 AND idsezionale = '".$_SESSION['uscita']['idsezionale']."' ", $result_query);
} }
/*fine filtro sezionali*/
if (isset($_SESSION['uscita']['idsezionale']) AND ($modules_info[$id_module]['name'] == 'Fatture di acquisto') ){
$module_query = str_replace('1=1', " 1=1 AND idsezionale = '".$_SESSION['uscita']["idsezionale"]."' ", $module_query);
}
/*fine filtro sezionali*/
if (!empty($search_filters)) { if (!empty($search_filters)) {
$module_query = str_replace('2=2', '2=2 AND ('.implode(' AND ', $search_filters).') ', $module_query); $result_query = str_replace('2=2', '2=2 AND ('.implode(' AND ', $search_filters).') ', $result_query);
} }
// Filtri derivanti dai permessi (eventuali) // Filtri derivanti dai permessi (eventuali)
if (empty($id_plugin)) { if (empty($id_plugin)) {
$module_query = Modules::replaceAdditionals($id_module, $module_query); $result_query = Modules::replaceAdditionals($id_module, $result_query);
} }
// Ordinamento dei risultati // Ordinamento dei risultati
if (isset($order['dir']) && isset($order['column'])) { if (isset($order['dir']) && isset($order['column'])) {
$pieces = explode('ORDER', $module_query); $pieces = explode('ORDER', $result_query);
$cont = count($pieces); $count = count($pieces);
if ($cont > 1) { if ($count > 1) {
unset($pieces[$cont - 1]); unset($pieces[$count - 1]);
} }
$module_query = implode('ORDER', $pieces).' ORDER BY '.$total['order_by'][$order['column']].' '.$order['dir']; $result_query = implode('ORDER', $pieces).' ORDER BY '.$total['order_by'][$order['column']].' '.$order['dir'];
} }
// Calcolo di eventuali somme // Calcolo di eventuali somme
if (!empty($total['summable'])) { if (!empty($total['summable'])) {
$query = str_replace_once('SELECT', 'SELECT '.implode(', ', $total['summable']).' FROM(SELECT ', $module_query).') AS `z`'; $sum_query = str_replace_once('SELECT', 'SELECT '.implode(', ', $total['summable']).' FROM(SELECT ', $result_query).') AS `z`';
$sums = $dbo->fetchArray($query)[0]; $sums = $dbo->fetchArray($sum_query)[0];
if (!empty($sums)) { if (!empty($sums)) {
$r = []; $r = [];
foreach ($sums as $key => $sum) { foreach ($sums as $key => $sum) {
@ -116,17 +106,17 @@ if (!empty($module_query) && $module_query != 'menu' && $module_query != 'custom
// Paginazione // Paginazione
if ($length > 0) { if ($length > 0) {
$module_query .= ' LIMIT '.$start.', '.$length; $result_query .= ' LIMIT '.$start.', '.$length;
} }
// Query effettiva // Query effettiva
$query = str_replace_once('SELECT', 'SELECT SQL_CALC_FOUND_ROWS', $module_query); $query = str_replace_once('SELECT', 'SELECT SQL_CALC_FOUND_ROWS', $result_query);
$rs = $dbo->fetchArray($query); $rs = $dbo->fetchArray($query);
// Conteggio dei record filtrati // Conteggio dei record filtrati
$cont = $dbo->fetchArray('SELECT FOUND_ROWS()'); $count = $dbo->fetchArray('SELECT FOUND_ROWS()');
if (!empty($cont)) { if (!empty($count)) {
$results['recordsFiltered'] = $cont[0]['FOUND_ROWS()']; $results['recordsFiltered'] = $count[0]['FOUND_ROWS()'];
} }
// Creazione della tabella // Creazione della tabella

View File

@ -36,3 +36,9 @@ $formatter = [
'thousands' => '.', 'thousands' => '.',
], ],
]; ];
// Ulteriori file CSS e JS da includere
$assets = [
'css' => [],
'js' => [],
];

115
core.php
View File

@ -12,24 +12,16 @@ if (file_exists(__DIR__.'/config.inc.php')) {
include_once __DIR__.'/config.inc.php'; include_once __DIR__.'/config.inc.php';
} }
// Individuazione dei percorsi di base
$docroot = __DIR__;
$rootdir = substr($_SERVER['SCRIPT_NAME'], 0, strrpos($_SERVER['SCRIPT_NAME'], '/')).'/';
if (strrpos($rootdir, '/'.basename($docroot).'/') !== false) {
$rootdir = substr($rootdir, 0, strrpos($rootdir, '/'.basename($docroot).'/')).'/'.basename($docroot);
} else {
$rootdir = '/';
}
$rootdir = rtrim($rootdir, '/');
$rootdir = str_replace('%2F', '/', rawurlencode($rootdir));
// Aggiunta delle variabili globali
define('DOCROOT', $docroot);
define('ROOTDIR', $rootdir);
// Caricamento delle dipendenze e delle librerie del progetto // Caricamento delle dipendenze e delle librerie del progetto
require_once __DIR__.'/vendor/autoload.php'; require_once __DIR__.'/vendor/autoload.php';
// Individuazione dei percorsi di base
App::definePaths(__DIR__);
$docroot = DOCROOT;
$rootdir = ROOTDIR;
$baseurl = BASEURL;
// Redirect al percorso HTTPS se impostato nella configurazione // Redirect al percorso HTTPS se impostato nella configurazione
if (!empty($redirectHTTPS) && !isHTTPS(true)) { if (!empty($redirectHTTPS) && !isHTTPS(true)) {
header('HTTP/1.1 301 Moved Permanently'); header('HTTP/1.1 301 Moved Permanently');
@ -37,10 +29,6 @@ if (!empty($redirectHTTPS) && !isHTTPS(true)) {
exit(); exit();
} }
// Individuazione del percorso BASEURL
$baseurl = (isHTTPS(true) ? 'https' : 'http').'://'.$_SERVER['SERVER_NAME'].$rootdir;
define('BASEURL', $baseurl);
// Forzamento del debug // Forzamento del debug
// $debug = true; // $debug = true;
@ -59,11 +47,11 @@ use Monolog\Handler\RotatingFileHandler;
$handlers = []; $handlers = [];
if (!API::isAPIRequest()) { if (!API::isAPIRequest()) {
// File di log di base (logs/error.log) // File di log di base (logs/error.log)
$handlers[] = new StreamHandler(__DIR__.'/logs/error.log', Monolog\Logger::ERROR); $handlers[] = new StreamHandler($docroot.'/logs/error.log', Monolog\Logger::ERROR);
$handlers[] = new StreamHandler(__DIR__.'/logs/setup.log', Monolog\Logger::EMERGENCY); $handlers[] = new StreamHandler($docroot.'/logs/setup.log', Monolog\Logger::EMERGENCY);
// Impostazione dei log estesi (per monitorare in modo completo le azioni degli utenti) // Impostazione dei log estesi (per monitorare in modo completo le azioni degli utenti)
$handlers[] = new StreamHandler(__DIR__.'/logs/info.log', Monolog\Logger::INFO); $handlers[] = new StreamHandler($docroot.'/logs/info.log', Monolog\Logger::INFO);
// Impostazioni di debug // Impostazioni di debug
if (!empty($debug)) { if (!empty($debug)) {
@ -71,26 +59,24 @@ if (!API::isAPIRequest()) {
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE & ~E_USER_DEPRECATED); error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE & ~E_USER_DEPRECATED);
// File di log ordinato in base alla data // File di log ordinato in base alla data
$handlers[] = new RotatingFileHandler(__DIR__.'/logs/error.log', 0, Monolog\Logger::ERROR); $handlers[] = new RotatingFileHandler($docroot.'/logs/error.log', 0, Monolog\Logger::ERROR);
$handlers[] = new RotatingFileHandler(__DIR__.'/logs/setup.log', 0, Monolog\Logger::EMERGENCY); $handlers[] = new RotatingFileHandler($docroot.'/logs/setup.log', 0, Monolog\Logger::EMERGENCY);
if (version_compare(PHP_VERSION, '5.5.9') >= 0) { $prettyPageHandler = new Whoops\Handler\PrettyPageHandler();
$prettyPageHandler = new Whoops\Handler\PrettyPageHandler();
// Imposta Whoops come gestore delle eccezioni di default // Imposta Whoops come gestore delle eccezioni di default
$whoops = new Whoops\Run(); $whoops = new Whoops\Run();
$whoops->pushHandler($prettyPageHandler); $whoops->pushHandler($prettyPageHandler);
// Abilita la gestione degli errori nel caso la richiesta sia di tipo AJAX // Abilita la gestione degli errori nel caso la richiesta sia di tipo AJAX
if (Whoops\Util\Misc::isAjaxRequest()) { if (Whoops\Util\Misc::isAjaxRequest()) {
$whoops->pushHandler(new Whoops\Handler\JsonResponseHandler()); $whoops->pushHandler(new Whoops\Handler\JsonResponseHandler());
}
$whoops->register();
} }
$whoops->register();
} }
} else { } else {
$handlers[] = new StreamHandler(__DIR__.'/logs/api.log', Monolog\Logger::ERROR); $handlers[] = new StreamHandler($docroot.'/logs/api.log', Monolog\Logger::ERROR);
} }
// Disabilita la segnalazione degli errori (se il debug è disabilitato) // Disabilita la segnalazione degli errori (se il debug è disabilitato)
@ -183,36 +169,13 @@ if (!API::isAPIRequest()) {
// Impostazione del tema grafico di default // Impostazione del tema grafico di default
$theme = !empty($theme) ? $theme : 'default'; $theme = !empty($theme) ? $theme : 'default';
$assets = $rootdir.'/assets/dist'; $assets = App::getAssets();
$css = $assets.'/css';
$js = $assets.'/js';
$img = $assets.'/img';
// CSS di base del progetto // CSS di base del progetto
$css_modules = []; $css_modules = $assets['css'];
$css_modules[] = $css.'/app.min.css';
$css_modules[] = $css.'/style.min.css';
$css_modules[] = $css.'/themes.min.css';
$css_modules[] = [
'href' => $css.'/print.min.css',
'media' => 'print',
];
// JS di base del progetto // JS di base del progetto
$jscript_modules = []; $jscript_modules = $assets['js'];
$jscript_modules[] = $js.'/app.min.js';
$jscript_modules[] = $js.'/custom.min.js';
$jscript_modules[] = $js.'/i18n/parsleyjs/'.$lang.'.min.js';
$jscript_modules[] = $js.'/i18n/select2/'.$lang.'.min.js';
$jscript_modules[] = $js.'/i18n/moment/'.$lang.'.min.js';
$jscript_modules[] = $js.'/i18n/fullcalendar/'.$lang.'.min.js';
if (Auth::check()) {
$jscript_modules[] = $rootdir.'/lib/functions.js';
$jscript_modules[] = $rootdir.'/lib/init.js';
}
if ($continue) { if ($continue) {
// Istanziamento della barra di debug // Istanziamento della barra di debug
@ -249,36 +212,8 @@ if (!API::isAPIRequest()) {
} }
Permissions::check(); Permissions::check();
// Retrocompatibilità
$user_idanagrafica = $user['idanagrafica'];
$rs = $dbo->fetchArray('SELECT * FROM `zz_modules` LEFT JOIN (SELECT `idmodule`, `permessi` FROM `zz_permissions` WHERE `idgruppo`=(SELECT `idgruppo` FROM `zz_users` WHERE `id`='.prepare($_SESSION['id_utente']).')) AS `zz_permissions` ON `zz_modules`.`id`=`zz_permissions`.`idmodule` LEFT JOIN (SELECT `idmodule`, `clause` FROM `zz_group_module` WHERE `idgruppo`=(SELECT `idgruppo` FROM `zz_users` WHERE `id`='.prepare($_SESSION['id_utente']).')) AS `zz_group_module` ON `zz_modules`.`id`=`zz_group_module`.`idmodule`');
$modules_info = [];
for ($i = 0; $i < count($rs); ++$i) {
foreach ($rs[$i] as $name => $value) {
if ($name == 'permessi' && (Auth::admin() || $value == null)) {
if (Auth::admin()) {
$value = 'rw';
} else {
$value = '-';
}
}
if ($name != 'idmodule' && $name != 'updated_at' && $name != 'created_at' && $name != 'clause') {
$modules_info[$rs[$i]['name']][$name] = $value;
} elseif ($name == 'clause') {
$additional_where[$rs[$i]['name']] = !empty($value) ? ' AND '.$value : $value;
}
}
$modules_info[$rs[$i]['id']]['name'] = $rs[$i]['name'];
}
} }
// Istanziamento di HTMLHelper (retrocompatibilità)
$html = new HTMLHelper();
// Variabili GET e POST // Variabili GET e POST
$post = Filter::getPOST(); $post = Filter::getPOST();
$get = Filter::getGET(); $get = Filter::getGET();

View File

@ -4,14 +4,14 @@ include_once __DIR__.'/../core.php';
// Lettura parametri iniziali del modulo // Lettura parametri iniziali del modulo
if (!empty($id_plugin)) { if (!empty($id_plugin)) {
$info = Plugins::get($id_plugin); $element = Plugins::get($id_plugin);
if (!empty($info['script'])) { if (!empty($element['script'])) {
// Inclusione di eventuale plugin personalizzato // Inclusione di eventuale plugin personalizzato
if (file_exists($docroot.'/modules/'.$info['module_dir'].'/plugins/custom/'.$info['script'])) { if (file_exists($docroot.'/modules/'.$element['module_dir'].'/plugins/custom/'.$element['script'])) {
include $docroot.'/modules/'.$info['module_dir'].'/plugins/custom/'.$info['script']; include $docroot.'/modules/'.$element['module_dir'].'/plugins/custom/'.$element['script'];
} elseif (file_exists($docroot.'/modules/'.$info['module_dir'].'/plugins/'.$info['script'])) { } elseif (file_exists($docroot.'/modules/'.$element['module_dir'].'/plugins/'.$element['script'])) {
include $docroot.'/modules/'.$info['module_dir'].'/plugins/'.$info['script']; include $docroot.'/modules/'.$element['module_dir'].'/plugins/'.$element['script'];
} }
return; return;
@ -19,9 +19,9 @@ if (!empty($id_plugin)) {
echo ' echo '
<h4> <h4>
'.$info['name']; '.$element['name'];
if (file_exists($docroot.'/plugins/'.$info['directory'].'/add.php')) { if (file_exists($docroot.'/plugins/'.$element['directory'].'/add.php')) {
echo ' echo '
<button type="button" class="btn btn-primary" data-toggle="modal" data-title="'.tr('Aggiungi').'..." data-target="#bs-popup" data-href="add.php?id_module='.$id_module.'&id_plugin='.$id_plugin.'&id_parent='.$id_record.'"><i class="fa fa-plus"></i></button>'; <button type="button" class="btn btn-primary" data-toggle="modal" data-title="'.tr('Aggiungi').'..." data-target="#bs-popup" data-href="add.php?id_module='.$id_module.'&id_plugin='.$id_plugin.'&id_parent='.$id_record.'"><i class="fa fa-plus"></i></button>';
} }
@ -29,18 +29,15 @@ if (!empty($id_plugin)) {
echo ' echo '
</h4>'; </h4>';
$total = Plugins::getQuery($id_plugin); $directory = '/plugins/'.$element['directory'];
$directory = '/plugins/'.$info['directory'];
} else { } else {
$info = Modules::get($id_module); $element = Modules::get($id_module);
$total = Modules::getQuery($id_module); $directory = '/modules/'.$element['directory'];
$directory = '/modules/'.$info['directory'];
} }
$total = App::readQuery($element);
$module_options = (!empty($info['options2'])) ? $info['options2'] : $info['options']; $module_options = (!empty($element['options2'])) ? $element['options2'] : $element['options'];
// Caricamento file aggiuntivo su elenco record // Caricamento file aggiuntivo su elenco record
if (file_exists($docroot.$directory.'/custom/controller_before.php')) { if (file_exists($docroot.$directory.'/custom/controller_before.php')) {
@ -174,9 +171,6 @@ if (!empty($module_options) && $module_options != 'menu' && $module_options != '
* Inclusione modulo personalizzato * Inclusione modulo personalizzato
*/ */
elseif ($module_options == 'custom') { elseif ($module_options == 'custom') {
// Inclusione elementi fondamentali del modulo
include $docroot.'/actions.php';
// Lettura template modulo (verifico se ci sono template personalizzati, altrimenti uso quello base) // Lettura template modulo (verifico se ci sono template personalizzati, altrimenti uso quello base)
if (file_exists($docroot.$directory.'/custom/edit.php')) { if (file_exists($docroot.$directory.'/custom/edit.php')) {
include $docroot.$directory.'/custom/edit.php'; include $docroot.$directory.'/custom/edit.php';

View File

@ -2,10 +2,12 @@
include_once __DIR__.'/../core.php'; include_once __DIR__.'/../core.php';
$paths = App::getPaths();
if (!empty($debugbar)) { if (!empty($debugbar)) {
$debugbarRenderer = $debugbar->getJavascriptRenderer(); $debugbarRenderer = $debugbar->getJavascriptRenderer();
$debugbarRenderer->setIncludeVendors(false); $debugbarRenderer->setIncludeVendors(false);
$debugbarRenderer->setBaseUrl($assets.'/php-debugbar'); $debugbarRenderer->setBaseUrl($paths['assets'].'/php-debugbar');
} }
echo '<!DOCTYPE html> echo '<!DOCTYPE html>
@ -83,7 +85,7 @@ if (Auth::check()) {
echo ' echo '
}; };
globals = { globals = {
rootdir: \''.$rootdir.'\', js: \''.$js.'\', css: \''.$css.'\', img: \''.$img.'\', rootdir: \''.$rootdir.'\', js: \''.$paths['js'].'\', css: \''.$paths['css'].'\', img: \''.$paths['img'].'\',
id_module: \''.$id_module.'\', id_module: \''.$id_module.'\',
id_record: \''.$id_record.'\', id_record: \''.$id_record.'\',
aggiornamenti_id: \''.($dbo->isInstalled() ? Modules::get('Aggiornamenti')['id'] : '').'\', aggiornamenti_id: \''.($dbo->isInstalled() ? Modules::get('Aggiornamenti')['id'] : '').'\',
@ -201,7 +203,7 @@ if (Auth::check()) {
</div> </div>
<div class="image"> <div class="image">
<img src="'.$img.'/logo.png" class="img-circle img-responsive" alt="'.tr('OpenSTAManager').'" /> <img src="'.$paths['img'].'/logo.png" class="img-circle img-responsive" alt="'.tr('OpenSTAManager').'" />
</div> </div>
</div> </div>

View File

@ -129,7 +129,7 @@ if (!empty($_SESSION['errors'])) {
echo ' echo '
<form action="?op=login" method="post" class="login-box box"> <form action="?op=login" method="post" class="login-box box">
<div class="box-header with-border text-center"> <div class="box-header with-border text-center">
<img src="'.$img.'/logo.png" alt="'.tr('OSM Logo').'"> <img src="'.App::getPaths()['img'].'/logo.png" alt="'.tr('OSM Logo').'">
<h3 class="box-title">'.tr('OpenSTAManager').'</h3> <h3 class="box-title">'.tr('OpenSTAManager').'</h3>
</div> </div>
<!-- /.box-header --> <!-- /.box-header -->

View File

@ -135,13 +135,9 @@ switch (filter('op')) {
break; break;
case 'test': case 'test':
$total = Modules::getQuery($id_record); $total = App::readQuery(Modules::get($id_record));
$module_query = $total['query']; $module_query = $total['query'];
$module_query = str_replace('|period_start|', $_SESSION['period_start'], $module_query);
$module_query = str_replace('|period_end|', $_SESSION['period_end'], $module_query);
$module_query = str_replace('|select|', $total['select'], $module_query);
$dbo->fetchArray($module_query.' LIMIT 1'); $dbo->fetchArray($module_query.' LIMIT 1');
break; break;

View File

@ -53,13 +53,9 @@ echo '
</div>'; </div>';
if ($options != '' && $options != 'menu' && $options != 'custom') { if ($options != '' && $options != 'menu' && $options != 'custom') {
$total = Modules::getQuery($id_record); $total = App::readQuery(Modules::get($id_record));
$module_query = $total['query']; $module_query = $total['query'];
$module_query = str_replace('|period_start|', $_SESSION['period_start'], $module_query);
$module_query = str_replace('|period_end|', $_SESSION['period_end'], $module_query);
$module_query = str_replace('|select|', $total['select'], $module_query);
echo ' echo '
<div class="row"> <div class="row">
<div class="col-xs-12 col-md-12"> <div class="col-xs-12 col-md-12">

View File

@ -12,6 +12,29 @@ class App
/** @var int Identificativo dell'elemento corrente */ /** @var int Identificativo dell'elemento corrente */
protected static $current_element; protected static $current_element;
protected static $assets = [
// CSS
'css' => [
'app.min.css',
'style.min.css',
'themes.min.css',
[
'href' => 'print.min.css',
'media' => 'print',
],
],
// JS
'js' => [
'app.min.js',
'custom.min.js',
'i18n/parsleyjs/|lang|.min.js',
'i18n/select2/|lang|.min.js',
'i18n/moment/|lang|.min.js',
'i18n/fullcalendar/|lang|.min.js',
],
];
/** /**
* Restituisce l'identificativo del modulo attualmente in utilizzo. * Restituisce l'identificativo del modulo attualmente in utilizzo.
* *
@ -20,7 +43,7 @@ class App
public static function getCurrentModule() public static function getCurrentModule()
{ {
if (empty(self::$current_module)) { if (empty(self::$current_module)) {
self::$current_module = filter('id_module'); self::$current_module = Modules::get(filter('id_module'));
} }
return self::$current_module; return self::$current_module;
@ -41,16 +64,263 @@ class App
} }
/** /**
* Restituisce la configurazione dell'installazione. * Restituisce la configurazione di default del gestionale.
* *
* @return array * @return array
*/ */
public function getConfig() protected static function getDefaultConfig()
{ {
if (file_exists(DOCROOT.'/config.inc.php')) { if (file_exists(DOCROOT.'/config.example.php')) {
include DOCROOT.'/config.inc.php'; include DOCROOT.'/config.example.php';
} }
return get_defined_vars(); return get_defined_vars();
} }
/**
* Restituisce la configurazione dell'installazione.
*
* @return array
*/
public static function getConfig()
{
if (file_exists(DOCROOT.'/config.inc.php')) {
include DOCROOT.'/config.inc.php';
$config = get_defined_vars();
} else {
$config = [];
}
$defaultConfig = self::getDefaultConfig();
return array_merge($defaultConfig, $config);
}
/**
* Individuazione dei percorsi di base.
*
* @return array
*/
public static function definePaths($docroot)
{
// Individuazione di $rootdir
$rootdir = substr($_SERVER['SCRIPT_NAME'], 0, strrpos($_SERVER['SCRIPT_NAME'], '/')).'/';
if (strrpos($rootdir, '/'.basename($docroot).'/') !== false) {
$rootdir = substr($rootdir, 0, strrpos($rootdir, '/'.basename($docroot).'/')).'/'.basename($docroot);
} else {
$rootdir = '/';
}
$rootdir = rtrim($rootdir, '/');
$rootdir = str_replace('%2F', '/', rawurlencode($rootdir));
// Individuazione di $baseurl
$baseurl = (isHTTPS(true) ? 'https' : 'http').'://'.$_SERVER['HTTP_HOST'].$rootdir;
// Impostazione delle variabili globali
define('DOCROOT', $docroot);
define('ROOTDIR', $rootdir);
define('BASEURL', $baseurl);
}
/**
* Restituisce la configurazione dell'installazione.
*
* @return array
*/
public static function getPaths()
{
$assets = ROOTDIR.'/assets/dist';
return [
'assets' => $assets,
'css' => $assets.'/css',
'js' => $assets.'/js',
'img' => $assets.'/img',
];
}
/**
* Restituisce la configurazione dell'installazione.
*
* @return array
*/
public static function getAssets()
{
// Assets aggiuntivi
$config = self::getConfig();
$css = array_unique(array_merge(self::$assets['css'], $config['assets']['css']));
$js = array_unique(array_merge(self::$assets['js'], $config['assets']['js']));
// Impostazione dei percorsi
$paths = self::getPaths();
$lang = Translator::getInstance()->getCurrentLocale();
foreach ($css as $key => $value) {
if (is_array($value)) {
$path = $value['href'];
} else {
$path = $value;
}
$path = $paths['css'].'/'.$path;
$path = str_replace('|lang|', $lang, $path);
if (is_array($value)) {
$value['href'] = $path;
} else {
$value = $path;
}
$css[$key] = $value;
}
foreach ($js as $key => $value) {
$value = $paths['js'].'/'.$value;
$value = str_replace('|lang|', $lang, $value);
$js[$key] = $value;
}
// JS aggiuntivi per gli utenti connessi
if (Auth::check()) {
$js[] = ROOTDIR.'/lib/functions.js';
$js[] = ROOTDIR.'/lib/init.js';
}
return [
'css' => $css,
'js' => $js,
];
}
/**
* Restituisce un'insieme di array comprendenti le informazioni per la costruzione della query del modulo indicato.
*
* @param int $id
*
* @return array
*/
public static function readQuery($element)
{
if (str_contains($element['option'], '|select|')) {
$result = self::readNewQuery($element);
} else {
$result = self::readOldQuery($element);
}
return $result;
}
protected static function readNewQuery($element)
{
$fields = [];
$summable = [];
$search_inside = [];
$search = [];
$slow = [];
$order_by = [];
$query = $element['option'];
$views = self::getViews($element);
$select = [];
foreach ($views as $view) {
$select[] = $view['query'].(!empty($view['name']) ? " AS '".$view['name']."'" : '');
if ($view['enabled']) {
$view['name'] = trim($view['name']);
$view['search_inside'] = trim($view['search_inside']);
$view['order_by'] = trim($view['order_by']);
$fields[] = trim($view['name']);
$search_inside[] = !empty($view['search_inside']) ? $view['search_inside'] : $view['name'];
$order_by[] = !empty($view['order_by']) ? $view['order_by'] : $view['name'];
$search[] = $view['search'];
$slow[] = $view['slow'];
$format[] = $view['format'];
if ($view['summable']) {
$summable[] = 'SUM(`'.trim($view['name']."`) AS 'sum_".(count($fields) - 1)."'");
}
}
}
$select = empty($select) ? '*' : implode(', ', $select);
$query = str_replace('|select|', $select, $query);
return [
'query' => $query,
'fields' => $fields,
'search_inside' => $search_inside,
'order_by' => $order_by,
'search' => $search,
'slow' => $slow,
'format' => $format,
'summable' => [],
];
}
protected static function readOldQuery($element)
{
$options = str_replace(["\r", "\n", "\t"], ' ', $element['option']);
$options = json_decode($options, true);
$options = $options['main_query'][0];
$query = $options['query'];
$fields = explode(',', $options['fields']);
foreach ($fields as $key => $value) {
$fields[$key] = trim($value);
$search[] = 1;
$slow[] = 0;
$format[] = 0;
}
$search_inside = $fields;
$order_by = $fields;
return [
'query' => $query,
'fields' => $fields,
'search_inside' => $search_inside,
'order_by' => $order_by,
'search' => $search,
'slow' => $slow,
'format' => $format,
'summable' => [],
];
}
protected static function getViews($element)
{
$database = Database::getConnection();
$user = Auth::user();
$views = $database->fetchArray('SELECT * FROM `zz_views` WHERE `id_module`='.prepare($element['id']).' AND
`id` IN (
SELECT `id_vista` FROM `zz_group_view` WHERE `id_gruppo`=(
SELECT `idgruppo` FROM `zz_users` WHERE `id`='.prepare($user['id']).'
))
ORDER BY `order` ASC');
return $views;
}
public static function replacePlaceholder($query, $custom = null)
{
$user = Auth::user();
$id = empty($custom) ? $user['idanagrafica'] : $custom;
$query = str_replace(['|idagente|', '|idtecnico|', '|idanagrafica|'], prepare($id), $query);
$query = str_replace(['|period_start|', '|period_end|'], [$_SESSION['period_start'], $_SESSION['period_end']], $query);
return $query;
}
} }

View File

@ -207,6 +207,7 @@ class Auth extends \Util\Singleton
$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 = '.prepare($user_id).' AND enabled = 1 LIMIT 1', false, ['session' => false]); $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 = '.prepare($user_id).' AND enabled = 1 LIMIT 1', false, ['session' => false]);
if (!empty($results)) { if (!empty($results)) {
$results[0]['id'] = $results[0]['id_utente'];
$results[0]['is_admin'] = ($results[0]['gruppo'] == 'Amministratori'); $results[0]['is_admin'] = ($results[0]['gruppo'] == 'Amministratori');
$this->infos = $results[0]; $this->infos = $results[0];

View File

@ -49,8 +49,13 @@ class Modules
$additionals[$result['id']]['HVN'] = []; $additionals[$result['id']]['HVN'] = [];
} }
$result['options'] = App::replacePlaceholder($result['options']);
$result['options2'] = App::replacePlaceholder($result['options2']);
$result['option'] = empty($result['options2']) ? $result['options'] : $result['options2'];
if (!empty($result['clause'])) { if (!empty($result['clause'])) {
$result['clause'] = self::replacePlaceholder($result['clause']); $result['clause'] = App::replacePlaceholder($result['clause']);
$additionals[$result['id']][$result['position']][] = $result['clause']; $additionals[$result['id']][$result['position']][] = $result['clause'];
} }
@ -173,141 +178,6 @@ class Modules
return $result; return $result;
} }
/**
* Restituisce l'identificativo del modulo attualmente in utilizzo.
*
* @return int
*/
public static function getCurrentModule()
{
if (empty(self::$current_module)) {
self::$current_module = filter('id_module');
}
return self::get(self::$current_module);
}
/**
* Restituisce l'identificativo dell'elemento attualmente in utilizzo.
*
* @return int
*/
public static function getCurrentElement()
{
if (empty(self::$current_element)) {
self::$current_element = filter('id_record');
}
return self::$current_element;
}
/**
* Restituisce un'insieme di array comprendenti le informazioni per la costruzione della query del modulo indicato.
*
* @param int $id
*
* @return array
*/
public static function getQuery($id)
{
if (empty(self::$queries[$id])) {
$database = Database::getConnection();
$module = self::get($id);
$fields = [];
$summable = [];
$search_inside = [];
$search = [];
$slow = [];
$order_by = [];
$select = '*';
$options = !empty($module['options2']) ? $module['options2'] : $module['options'];
if (str_contains($options, '|select|')) {
$query = $options;
$user = Auth::user();
$datas = $database->fetchArray('SELECT * FROM `zz_views` WHERE `id_module`='.prepare($id).' AND `id` IN (SELECT `id_vista` FROM `zz_group_view` WHERE `id_gruppo`=(SELECT `idgruppo` FROM `zz_users` WHERE `id`='.prepare($user['id_utente']).')) ORDER BY `order` ASC');
if (!empty($datas)) {
$select = '';
foreach ($datas as $data) {
$select .= $data['query'].(!empty($data['name']) ? " AS '".$data['name']."', " : '');
if ($data['enabled']) {
$data['name'] = trim($data['name']);
$data['search_inside'] = trim($data['search_inside']);
$data['order_by'] = trim($data['order_by']);
$fields[] = trim($data['name']);
$search_inside[] = !empty($data['search_inside']) ? $data['search_inside'] : $data['name'];
$order_by[] = !empty($data['order_by']) ? $data['order_by'] : $data['name'];
$search[] = $data['search'];
$slow[] = $data['slow'];
$format[] = $data['format'];
if ($data['summable']) {
$summable[] = 'SUM(`'.trim($data['name']."`) AS 'sum_".(count($fields) - 1)."'");
}
}
}
$select = substr($select, 0, strlen($select) - 2);
}
} else {
$options = self::readOldQuery($options);
$query = $options['query'];
$fields = explode(',', $options['fields']);
foreach ($fields as $key => $value) {
$fields[$key] = trim($value);
$search[] = 1;
$slow[] = 0;
$format[] = 0;
}
$search_inside = $fields;
$order_by = $fields;
}
$result = [];
$result['query'] = $query;
$result['select'] = $select;
$result['fields'] = $fields;
$result['search_inside'] = $search_inside;
$result['order_by'] = $order_by;
$result['search'] = $search;
$result['slow'] = $slow;
$result['format'] = $format;
$result['summable'] = $summable;
self::$queries[$id] = $result;
}
return self::$queries[$id];
}
public static function readOldQuery($options)
{
$options = str_replace(["\r", "\n", "\t"], ' ', $options);
$options = json_decode($options, true);
return $options['main_query'][0];
}
public static function replacePlaceholder($query, $custom = null)
{
$user = Auth::user();
$custom = empty($custom) ? $user['idanagrafica'] : $custom;
$result = str_replace(['|idagente|', '|idtecnico|', '|idanagrafica|'], prepare($custom), $query);
return $result;
}
/** /**
* Restituisce tutte le informazioni dei moduli installati in una scala gerarchica fino alla profondità indicata. * Restituisce tutte le informazioni dei moduli installati in una scala gerarchica fino alla profondità indicata.
* *
@ -399,7 +269,7 @@ class Modules
if (empty(self::$menu) || self::$depth != $depth) { if (empty(self::$menu) || self::$depth != $depth) {
$menus = self::getHierarchy($depth); $menus = self::getHierarchy($depth);
$module_name = self::getCurrentModule()['name']; $module_name = App::getCurrentModule()['name'];
$result = ''; $result = '';
foreach ($menus as $menu) { foreach ($menus as $menu) {

View File

@ -27,6 +27,11 @@ class Plugins
$plugins = []; $plugins = [];
foreach ($results as $result) { foreach ($results as $result) {
$result['options'] = App::replacePlaceholder($result['options'], filter('id_parent'));
$result['options2'] = App::replacePlaceholder($result['options2'], filter('id_parent'));
$result['option'] = empty($result['options2']) ? $result['options'] : $result['options2'];
$plugins[$result['id']] = $result; $plugins[$result['id']] = $result;
$plugins[$result['name']] = $result['id']; $plugins[$result['name']] = $result['id'];
} }
@ -52,58 +57,4 @@ class Plugins
return self::getPlugins()[$plugin]; return self::getPlugins()[$plugin];
} }
/**
* Restituisce un'insieme di array comprendenti le informazioni per la costruzione della query del modulo indicato.
*
* @param int $id
*
* @return array
*/
public static function getQuery($id)
{
if (empty(self::$queries[$id])) {
$database = Database::getConnection();
$module = self::get($id);
$fields = [];
$summable = [];
$search_inside = [];
$search = [];
$slow = [];
$order_by = [];
$select = '*';
$options = !empty($module['options2']) ? $module['options2'] : $module['options'];
$options = Modules::readOldQuery($options);
$query = $options['query'];
$fields = explode(',', $options['fields']);
foreach ($fields as $key => $value) {
$fields[$key] = trim($value);
$search[] = 1;
$slow[] = 0;
$format[] = 0;
}
$search_inside = $fields;
$order_by = $fields;
$result = [];
$result['query'] = $query;
$result['select'] = $select;
$result['fields'] = $fields;
$result['search_inside'] = $search_inside;
$result['order_by'] = $order_by;
$result['search'] = $search;
$result['slow'] = $slow;
$result['format'] = $format;
$result['summable'] = $summable;
self::$queries[$id] = $result;
}
return self::$queries[$id];
}
} }

View File

@ -5,13 +5,10 @@ include_once __DIR__.'/../../core.php';
$module = Modules::get('Interventi'); $module = Modules::get('Interventi');
$id_module = $module['id']; $id_module = $module['id'];
$total = Modules::getQuery($id_module); $total = App::readQuery($module);
// Lettura parametri modulo // Lettura parametri modulo
$module_query = $total['query']; $module_query = $total['query'];
$module_query = str_replace('|period_start|', $_SESSION['period_start'], $module_query);
$module_query = str_replace('|period_end|', $_SESSION['period_end'], $module_query);
$module_query = str_replace('|select|', $total['select'], $module_query);
$search_filters = []; $search_filters = [];

View File

@ -1,17 +0,0 @@
<?php
require 'core.php';
$user = \App::getUser();
print_r(Models\Module::getHierarchy()->toArray());
exit();
print_r($user->modules()->get()->toArray());
print_r($user->toArray());
$modules = Models\Module::all();
foreach ($modules as $module) {
print_r($module->title.': '.$module->permission.'<br>');
//print_r($module->views.'<br><br>');
}
exit();