Rimozione

This commit is contained in:
Thomas Zilio 2019-02-01 17:44:31 +01:00
parent 18b54175e0
commit dd6fa69fbb
28 changed files with 449 additions and 352 deletions

View File

@ -3,102 +3,50 @@
include_once __DIR__.'/core.php';
// Informazioni fondamentali
$start = filter('start');
$length = filter('length');
$columns = filter('columns');
$order = filter('order')[0];
$order['column'] = $order['column'] - 1;
array_shift($columns);
$total = App::readQuery($structure);
// Lettura parametri modulo
$result_query = $total['query'];
// Predisposizione dela risposta
$results = [];
$results['data'] = [];
$results['recordsTotal'] = 0;
$results['recordsFiltered'] = 0;
$results['summable'] = [];
if (!empty($result_query) && $result_query != 'menu' && $result_query != 'custom') {
// Conteggio totale
$results['recordsTotal'] = $dbo->fetchNum($result_query);
// Filtri di ricerica
$search_filters = [];
for ($i = 0; $i < count($columns); ++$i) {
if (!empty($columns[$i]['search']['value'])) {
if (str_contains($total['search_inside'][$i], '|search|')) {
$pieces = explode(',', $columns[$i]['search']['value']);
foreach ($pieces as $piece) {
$piece = trim($piece);
$search_filters[] = str_replace('|search|', prepare('%'.$piece.'%'), $total['search_inside'][$i]);
}
} else {
// Per le icone cerco nel campo icon_title
if (preg_match('/^icon_(.+?)$/', $total['fields'][$i], $m)) {
$total['search_inside'][$i] = '`icon_title_'.$m[1].'`';
}
// Per i colori cerco nel campo color_title
elseif (preg_match('/^color_(.+?)$/', $total['fields'][$i], $m)) {
$total['search_inside'][$i] = '`color_title_'.$m[1].'`';
}
$search_filters[] = $total['search_inside'][$i].' LIKE '.prepare('%'.trim($columns[$i]['search']['value'].'%'));
}
}
}
$total = Util\Query::readQuery($structure);
// Ricerca
if (!empty($search_filters)) {
$result_query = str_replace('2=2', '2=2 AND ('.implode(' AND ', $search_filters).') ', $result_query);
$search = [];
for ($i = 0; $i < count($columns); ++$i) {
if (!empty($columns[$i]['search']['value'])) {
$search[$total['fields'][$i]] = $columns[$i]['search']['value'];
}
}
$limit = [
'start' => filter('start'),
'length' => filter('length'),
];
// Predisposizione della risposta
$results = [
'data' => [],
'recordsTotal' => 0,
'recordsFiltered' => 0,
'summable' => [],
];
$query = Util\Query::getQuery($structure);
if (!empty($query)) {
// CONTEGGIO TOTALE
$results['recordsTotal'] = $dbo->fetchNum($query);
// RISULTATI VISIBILI
$query = Util\Query::getQuery($structure, $search, $order, $limit);
// Filtri derivanti dai permessi (eventuali)
if (empty($id_plugin)) {
$result_query = Modules::replaceAdditionals($id_module, $result_query);
$query = Modules::replaceAdditionals($id_module, $query);
}
// Ordinamento dei risultati
if (isset($order['dir']) && isset($order['column'])) {
$pieces = explode('ORDER', $result_query);
$count = count($pieces);
if ($count > 1) {
unset($pieces[$count - 1]);
}
$result_query = implode('ORDER', $pieces).' ORDER BY '.$total['order_by'][$order['column']].' '.$order['dir'];
}
// Calcolo di eventuali somme
if (!empty($total['summable'])) {
$sum_query = str_replace_once('SELECT', 'SELECT '.implode(', ', $total['summable']).' FROM(SELECT ', $result_query).') AS `z`';
$sums = $dbo->fetchArray($sum_query)[0];
if (!empty($sums)) {
$r = [];
foreach ($sums as $key => $sum) {
if (str_contains($key, 'sum_')) {
$r[str_replace('sum_', '', $key)] = Translator::numberToLocale($sum);
}
}
$results['summable'] = $r;
}
}
// Paginazione
if ($length > 0) {
$result_query .= ' LIMIT '.$start.', '.$length;
}
// Query effettiva
$query = str_replace_once('SELECT', 'SELECT SQL_CALC_FOUND_ROWS', $result_query);
$rs = $dbo->fetchArray($query);
$query = str_replace_once('SELECT', 'SELECT SQL_CALC_FOUND_ROWS', $query);
$rows = $dbo->fetchArray($query);
// Conteggio dei record filtrati
$count = $dbo->fetchArray('SELECT FOUND_ROWS()');
@ -106,12 +54,14 @@ if (!empty($result_query) && $result_query != 'menu' && $result_query != 'custom
$results['recordsFiltered'] = $count[0]['FOUND_ROWS()'];
}
// Creazione della tabella
// SOMME
$results['summable'] = Util\Query::getSums($structure, $search);
// Allineamento delle righe
$align = [];
foreach ($rs as $i => $r) {
if ($i == 0) {
foreach ($total['fields'] as $field) {
$value = trim($r[$field]);
$row = $rows[0] ?: [];
foreach ($row as $field => $value) {
$value = trim($value);
// Allineamento a destra se il valore della prima riga risulta numerica
if (formatter()->isStandardNumber($value)) {
@ -123,10 +73,13 @@ if (!empty($result_query) && $result_query != 'menu' && $result_query != 'custom
$align[$field] = 'text-center';
}
}
}
$result = [];
$result[] = '<span class="hide" data-id="'.$r['id'].'"></span>';
// Creazione della tabella
foreach ($rows as $i => $r) {
$result = [
'<span class="hide" data-id="'.$r['id'].'"></span>', // Colonna ID
];
foreach ($total['fields'] as $pos => $field) {
$column = [];
@ -219,5 +172,5 @@ if (!empty($result_query) && $result_query != 'menu' && $result_query != 'custom
}
}
$rows = json_encode($results);
echo $rows;
$json = json_encode($results);
echo $json;

View File

@ -12,9 +12,31 @@ if (empty($id_record) && !empty($id_module)) {
include_once App::filepath('include|custom|', 'top.php');
$query = Util\Query::getQuery($structure, [
'id' => $id_record,
]);
$has_access = $dbo->fetchNum($query);
if ($has_access) {
// Inclusione gli elementi fondamentali
include_once $docroot.'/actions.php';
}
if (empty($record) || !$has_access) {
echo '
<div class="text-center">
<h3 class="text-muted">'.
'<i class="fa fa-question-circle"></i> '.tr('Record non trovato').'
<br><br>
<small class="help-block">'.tr('Stai cercando di accedere ad un record eliminato o non presente').'</small>
</h3>
<br>
<a class="btn btn-default" href="'.ROOTDIR.'/controller.php?id_module='.$id_module.'">
<i class="fa fa-chevron-left"></i> '.tr('Indietro').'
</a>
</div>';
} else {
// Widget in alto
echo '{( "name": "widgets", "id_module": "'.$id_module.'", "id_record": "'.$id_record.'", "position": "top", "place": "editor" )}';
@ -38,21 +60,6 @@ if (!empty($advanced_sessions)) {
</div>';
}
if (empty($record)) {
echo '
<div class="text-center">
<h3 class="text-muted">'.
'<i class="fa fa-question-circle"></i> '.tr('Record non trovato').'
<br><br>
<small class="help-block">'.tr('Stai cercando di accedere ad un record eliminato o non presente').'</small>
</h3>
<br>
<a class="btn btn-default" href="'.ROOTDIR.'/controller.php?id_module='.$id_module.'">
<i class="fa fa-chevron-left"></i> '.tr('Indietro').'
</a>
</div>';
} else {
echo '
<div class="nav-tabs-custom">
<ul class="nav nav-tabs pull-right" id="tabs" role="tablist">

View File

@ -46,7 +46,7 @@ if (!empty($controller_before)) {
* Datatables con record
*/
if (!empty($type) && $type != 'menu' && $type != 'custom') {
$total = App::readQuery($structure);
$total = Util\Query::readQuery($structure);
if (empty($id_plugin) && count(Modules::getSegments($id_module)) > 1) {
echo '

View File

@ -188,10 +188,10 @@ switch (post('op')) {
case 'delete':
// Se l'anagrafica non è l'azienda principale, la disattivo
if (!in_array($id_azienda, $tipi_anagrafica)) {
$dbo->query('UPDATE an_anagrafiche SET deleted_at = NOW() WHERE idanagrafica = '.prepare($id_record).Modules::getAdditionalsQuery($id_module));
$dbo->query('UPDATE an_anagrafiche SET deleted_at = NOW() WHERE idanagrafica = '.prepare($id_record));
// Se l'anagrafica è collegata ad un utente lo disabilito
$dbo->query('UPDATE zz_users SET enabled = 0 WHERE idanagrafica = '.prepare($id_record).Modules::getAdditionalsQuery($id_module));
$dbo->query('UPDATE zz_users SET enabled = 0 WHERE idanagrafica = '.prepare($id_record));
flash()->info(tr('Anagrafica eliminata!'));
}

View File

@ -16,7 +16,7 @@ if (isset($id_record)) {
(SELECT GROUP_CONCAT(an_tipianagrafiche.idtipoanagrafica) FROM an_tipianagrafiche INNER JOIN an_tipianagrafiche_anagrafiche ON an_tipianagrafiche.idtipoanagrafica=an_tipianagrafiche_anagrafiche.idtipoanagrafica WHERE idanagrafica=an_anagrafiche.idanagrafica) AS idtipianagrafica,
(SELECT GROUP_CONCAT(idagente) FROM an_anagrafiche_agenti WHERE idanagrafica=an_anagrafiche.idanagrafica) AS idagenti,
(SELECT GROUP_CONCAT(descrizione) FROM an_tipianagrafiche INNER JOIN an_tipianagrafiche_anagrafiche ON an_tipianagrafiche.idtipoanagrafica=an_tipianagrafiche_anagrafiche.idtipoanagrafica WHERE idanagrafica=an_anagrafiche.idanagrafica) AS tipianagrafica
FROM an_anagrafiche WHERE idanagrafica='.prepare($id_record).' '.Modules::getAdditionalsQuery($id_module));
FROM an_anagrafiche WHERE idanagrafica='.prepare($id_record));
// Cast per latitudine e longitudine
if (!empty($record)) {

View File

@ -3,5 +3,5 @@
include_once __DIR__.'/../../core.php';
if (isset($id_record)) {
$record = $dbo->fetchOne('SELECT *, (SELECT tipo FROM an_anagrafiche WHERE idanagrafica = co_contratti.idanagrafica) AS tipo_anagrafica, (SELECT fatturabile FROM co_staticontratti WHERE id=idstato) AS fatturabile, (SELECT pianificabile FROM co_staticontratti WHERE id=idstato) AS pianificabile, (SELECT descrizione FROM co_staticontratti WHERE id=idstato) AS stato, (SELECT GROUP_CONCAT(my_impianti_contratti.idimpianto) FROM my_impianti_contratti WHERE idcontratto = co_contratti.id) AS idimpianti FROM co_contratti WHERE id='.prepare($id_record).Modules::getAdditionalsQuery($id_module));
$record = $dbo->fetchOne('SELECT *, (SELECT tipo FROM an_anagrafiche WHERE idanagrafica = co_contratti.idanagrafica) AS tipo_anagrafica, (SELECT fatturabile FROM co_staticontratti WHERE id=idstato) AS fatturabile, (SELECT pianificabile FROM co_staticontratti WHERE id=idstato) AS pianificabile, (SELECT descrizione FROM co_staticontratti WHERE id=idstato) AS stato, (SELECT GROUP_CONCAT(my_impianti_contratti.idimpianto) FROM my_impianti_contratti WHERE idcontratto = co_contratti.id) AS idimpianti FROM co_contratti WHERE id='.prepare($id_record));
}

View File

@ -264,7 +264,7 @@ switch (post('op')) {
$dbo->query($query);
// Eliminazione dell'intervento
$query = 'DELETE FROM in_interventi WHERE id='.prepare($id_record).' '.Modules::getAdditionalsQuery($id_module);
$query = 'DELETE FROM in_interventi WHERE id='.prepare($id_record);
$dbo->query($query);
// Elimino i collegamenti degli articoli a questo intervento
@ -370,7 +370,7 @@ switch (post('op')) {
case 'delriga':
$idriga = post('idriga');
$dbo->query('DELETE FROM in_righe_interventi WHERE id='.prepare($idriga).' '.Modules::getAdditionalsQuery($id_module));
$dbo->query('DELETE FROM in_righe_interventi WHERE id='.prepare($idriga));
break;
@ -425,7 +425,7 @@ switch (post('op')) {
$articolo->save();
// Aggiorno l'automezzo dell'intervento
$dbo->query('UPDATE in_interventi SET idautomezzo='.prepare(post('idautomezzo')).' WHERE id='.prepare($id_record).' '.Modules::getAdditionalsQuery($id_module));
$dbo->query('UPDATE in_interventi SET idautomezzo='.prepare(post('idautomezzo')).' WHERE id='.prepare($id_record));
if (!empty($serials)) {
if ($old_qta > $qta) {

View File

@ -4,7 +4,7 @@ include_once __DIR__.'/../../core.php';
$show_prezzi = Auth::user()['gruppo'] != 'Tecnici' || (Auth::user()['gruppo'] == 'Tecnici' && setting('Mostra i prezzi al tecnico'));
$query = 'SELECT *, (SELECT codice FROM mg_articoli WHERE id=mg_articoli_interventi.idarticolo) AS codice, mg_articoli_interventi.id AS idriga, (SELECT prc_guadagno FROM mg_listini WHERE id=(SELECT idlistino_vendite FROM an_anagrafiche WHERE idanagrafica=(SELECT idanagrafica FROM in_interventi WHERE id=mg_articoli_interventi.idintervento) ) ) AS prc_guadagno FROM mg_articoli_interventi WHERE idintervento='.prepare($id_record).' '.Modules::getAdditionalsQuery('Magazzino');
$query = 'SELECT *, (SELECT codice FROM mg_articoli WHERE id=mg_articoli_interventi.idarticolo) AS codice, mg_articoli_interventi.id AS idriga, (SELECT prc_guadagno FROM mg_listini WHERE id=(SELECT idlistino_vendite FROM an_anagrafiche WHERE idanagrafica=(SELECT idanagrafica FROM in_interventi WHERE id=mg_articoli_interventi.idintervento) ) ) AS prc_guadagno FROM mg_articoli_interventi WHERE idintervento='.prepare($id_record);
$rs = $dbo->fetchArray($query);
if (!empty($rs)) {

View File

@ -8,7 +8,7 @@ if (file_exists(__DIR__.'/../../../core.php')) {
$show_prezzi = Auth::user()['gruppo'] != 'Tecnici' || (Auth::user()['gruppo'] == 'Tecnici' && setting('Mostra i prezzi al tecnico'));
$query = 'SELECT * FROM in_righe_interventi WHERE idintervento='.prepare($id_record).' '.Modules::getAdditionalsQuery('Magazzino').' ORDER BY id ASC';
$query = 'SELECT * FROM in_righe_interventi WHERE idintervento='.prepare($id_record).' ORDER BY id ASC';
$rs2 = $dbo->fetchArray($query);
if (count($rs2) > 0) {

View File

@ -3,5 +3,5 @@
include_once __DIR__.'/../../core.php';
if (isset($id_record)) {
$record = $dbo->fetchOne('SELECT *, (SELECT tipo FROM an_anagrafiche WHERE idanagrafica = in_interventi.idanagrafica) AS tipo_anagrafica, (SELECT completato FROM in_statiintervento WHERE idstatointervento=in_interventi.idstatointervento) AS flag_completato, IF((in_interventi.idsede = 0), (SELECT idzona FROM an_anagrafiche WHERE idanagrafica = in_interventi.idanagrafica), (SELECT idzona FROM an_sedi WHERE id = in_interventi.idsede)) AS idzona, (SELECT colore FROM in_statiintervento WHERE idstatointervento=in_interventi.idstatointervento) AS colore, (SELECT idcontratto FROM co_promemoria WHERE idintervento=in_interventi.id LIMIT 0,1) AS idcontratto, in_interventi.id_preventivo as idpreventivo FROM in_interventi WHERE id='.prepare($id_record).Modules::getAdditionalsQuery($id_module));
$record = $dbo->fetchOne('SELECT *, (SELECT tipo FROM an_anagrafiche WHERE idanagrafica = in_interventi.idanagrafica) AS tipo_anagrafica, (SELECT completato FROM in_statiintervento WHERE idstatointervento=in_interventi.idstatointervento) AS flag_completato, IF((in_interventi.idsede = 0), (SELECT idzona FROM an_anagrafiche WHERE idanagrafica = in_interventi.idanagrafica), (SELECT idzona FROM an_sedi WHERE id = in_interventi.idsede)) AS idzona, (SELECT colore FROM in_statiintervento WHERE idstatointervento=in_interventi.idstatointervento) AS colore, (SELECT idcontratto FROM co_promemoria WHERE idintervento=in_interventi.id LIMIT 0,1) AS idcontratto, in_interventi.id_preventivo as idpreventivo FROM in_interventi WHERE id='.prepare($id_record));
}

View File

@ -3,5 +3,5 @@
include_once __DIR__.'/../../core.php';
if (isset($id_record)) {
$record = $dbo->fetchOne('SELECT *, (SELECT ragione_sociale FROM an_anagrafiche WHERE idanagrafica=my_impianti.idanagrafica) AS cliente FROM my_impianti WHERE id='.prepare($id_record).Modules::getAdditionalsQuery($id_module));
$record = $dbo->fetchOne('SELECT *, (SELECT ragione_sociale FROM an_anagrafiche WHERE idanagrafica=my_impianti.idanagrafica) AS cliente FROM my_impianti WHERE id='.prepare($id_record));
}

View File

@ -5,5 +5,5 @@ include_once __DIR__.'/../../core.php';
if (isset($id_record)) {
$preventivo = Modules\Preventivi\Preventivo::with('stato')->find($id_record);
$record = $dbo->fetchOne('SELECT *, (SELECT tipo FROM an_anagrafiche WHERE idanagrafica = co_preventivi.idanagrafica) AS tipo_anagrafica, (SELECT descrizione FROM co_statipreventivi WHERE id=idstato) AS stato FROM co_preventivi WHERE id='.prepare($id_record).Modules::getAdditionalsQuery($id_module));
$record = $dbo->fetchOne('SELECT *, (SELECT tipo FROM an_anagrafiche WHERE idanagrafica = co_preventivi.idanagrafica) AS tipo_anagrafica, (SELECT descrizione FROM co_statipreventivi WHERE id=idstato) AS stato FROM co_preventivi WHERE id='.prepare($id_record));
}

View File

@ -49,7 +49,7 @@ $_SESSION['module_'.$id_module]['id_segment'] = $id_record;
$_SESSION['module_'.$record['id_module']]['id_segment'] = $id_record;
$current_module = Modules::get($record['id_module']);
$total = App::readQuery($current_module);
$total = Util\Query::readQuery($current_module);
$module_query = Modules::replaceAdditionals($record['id_module'], $total['query']);
echo '

View File

@ -2,6 +2,8 @@
include_once __DIR__.'/../../core.php';
use Models\Module;
function check_query($query)
{
$query = mb_strtoupper($query);
@ -136,8 +138,7 @@ switch (filter('op')) {
break;
case 'test':
$total = App::readQuery(Modules::get($id_record));
$module_query = $total['query'];
$module_query = Util\Query::getQuery(Module::find($id_record));
$dbo->fetchArray($module_query.' LIMIT 1');

View File

@ -2,6 +2,8 @@
include_once __DIR__.'/../../core.php';
use Models\Module;
$enable_readonly = !setting('Modifica Viste di default');
echo '
@ -47,8 +49,7 @@ echo '
</div>';
if ($options != '' && $options != 'menu' && $options != 'custom') {
$total = App::readQuery(Modules::get($id_record));
$module_query = $total['query'];
$module_query = Util\Query::getQuery(Module::find($id_record));
echo '
<div class="row">

View File

@ -39,8 +39,8 @@ echo '
}
buttonRestore(btn, restore);
},
error: function(data) {
alert("'.tr('Errore').': " + data);
error: function(xhr) {
alert("'.tr('Errore').': " + xhr.responseJSON.error.message);
buttonRestore(btn, restore);
}

View File

@ -62,11 +62,10 @@ function download(button, file) {
title: "'.tr('Fattura già importata.').'",
type: "info",
});
buttonRestore(button, restore);
$(button).prop("disabled", true);
}
}
});
}

View File

@ -272,7 +272,7 @@ switch (filter('op')) {
case 'unlink_articolo':
$idriga = post('idriga');
$dbo->query('DELETE FROM co_promemoria_articoli WHERE id='.prepare($idriga).' '.Modules::getAdditionalsQuery($id_module));
$dbo->query('DELETE FROM co_promemoria_articoli WHERE id='.prepare($idriga));
break;
@ -350,7 +350,7 @@ switch (filter('op')) {
case 'delriga':
$idriga = post('idriga');
$dbo->query('DELETE FROM co_promemoria_righe WHERE id='.prepare($idriga).' '.Modules::getAdditionalsQuery($id_module));
$dbo->query('DELETE FROM co_promemoria_righe WHERE id='.prepare($idriga));
break;
}

View File

@ -7,7 +7,7 @@ $is_add = filter('add') ? true : false;
$pricing = Auth::admin() || Auth::user()['gruppo'] != 'Tecnici';
$rs = $dbo->fetchArray('SELECT * FROM co_promemoria_articoli WHERE id_promemoria = '.prepare($id_record).' '.Modules::getAdditionalsQuery('Magazzino').' ORDER BY id ASC');
$rs = $dbo->fetchArray('SELECT * FROM co_promemoria_articoli WHERE id_promemoria = '.prepare($id_record).' ORDER BY id ASC');
if (!empty($rs)) {
echo '

View File

@ -7,7 +7,7 @@ $is_add = filter('add') ? true : false;
$pricing = Auth::admin() || Auth::user()['gruppo'] != 'Tecnici';
$rs2 = $dbo->fetchArray('SELECT * FROM co_promemoria_righe WHERE id_promemoria='.prepare($id_record).' '.Modules::getAdditionalsQuery('Magazzino').' ORDER BY id ASC');
$rs2 = $dbo->fetchArray('SELECT * FROM co_promemoria_righe WHERE id_promemoria='.prepare($id_record).' ORDER BY id ASC');
if (!empty($rs2)) {
echo '

View File

@ -198,69 +198,6 @@ class App
return $assets;
}
/**
* Restituisce un'insieme di array comprendenti le informazioni per la costruzione della query del modulo indicato.
*
* @param array $element
*
* @return array
*/
public static function readQuery($element)
{
if (str_contains($element['option'], '|select|')) {
$result = self::readNewQuery($element);
} else {
$result = self::readOldQuery($element);
}
return $result;
}
/**
* Sostituisce i valori previsti all'interno delle query di moduli/plugin.
*
* @param string $query
* @param int $custom
*
* @return string
*/
public static function replacePlaceholder($query)
{
$id_parent = filter('id_parent');
$id_module = Modules::getCurrent()['id'];
$segment = $_SESSION['module_'.$id_module]['id_segment'];
$user = Auth::user();
// Elenco delle sostituzioni
$replace = [
// Identificatori
'|id_anagrafica|' => prepare($user['idanagrafica']),
'|id_utente|' => prepare($user['id']),
'|id_parent|' => prepare($id_parent),
// Date
'|period_start|' => $_SESSION['period_start'],
'|period_end|' => $_SESSION['period_end'],
// Segmenti
'|segment|' => !empty($segment) ? ' AND id_segment = '.prepare($segment) : '',
];
// Sostituzione dei formati
$patterns = formatter()->getSQLPatterns();
foreach ($patterns as $key => $value) {
$replace['|'.$key.'_format|'] = "'".$value."'";
}
// Sostituzione effettiva
$query = replace($query, $replace);
return $query;
}
/**
* Restituisce il codice HTML per il form contenente il file indicato.
*
@ -352,132 +289,4 @@ class App
return get_defined_vars();
}
/**
* Interpreta lo standard modulare per l'individuazione delle query di un modulo/plugin del progetto.
*
* @param array $element
*
* @return array
*/
protected static function readNewQuery($element)
{
$fields = [];
$summable = [];
$search_inside = [];
$search = [];
$format = [];
$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 (!empty($view['visible'])) {
$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' => self::replacePlaceholder($query),
'fields' => $fields,
'search_inside' => $search_inside,
'order_by' => $order_by,
'search' => $search,
'slow' => $slow,
'format' => $format,
'summable' => $summable,
];
}
/**
* Interpreta lo standard JSON per l'individuazione delle query di un modulo/plugin del progetto.
*
* @param array $element
*
* @return array
*/
protected static function readOldQuery($element)
{
$options = str_replace(["\r", "\n", "\t"], ' ', $element['option']);
$options = json_decode($options, true);
$options = $options['main_query'][0];
$fields = [];
$order_by = [];
$search = [];
$slow = [];
$format = [];
$query = $options['query'];
$views = explode(',', $options['fields']);
foreach ($views as $view) {
$fields[] = trim($view);
$order_by[] = '`'.trim($view).'`';
$search[] = 1;
$slow[] = 0;
$format[] = 0;
}
$search_inside = $order_by;
return [
'query' => self::replacePlaceholder($query),
'fields' => $fields,
'search_inside' => $search_inside,
'order_by' => $order_by,
'search' => $search,
'slow' => $slow,
'format' => $format,
'summable' => [],
];
}
/**
* Restituisce le singole componenti delle query per un determinato modulo/plugin.
*
* @param array $element
*
* @return array
*/
protected static function getViews($element)
{
$database = database();
$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;
}
}

View File

@ -74,7 +74,7 @@ class WidgetManager implements ManagerInterface
$query = str_replace('1=1', '1=1 '.$additionals, $query);
}
$query = \App::replacePlaceholder($query);
$query = \Util\Query::replacePlaceholder($query);
// Individuazione del risultato della query
$database = database();
@ -110,7 +110,7 @@ class WidgetManager implements ManagerInterface
elseif ($widget['more_link_type'] == 'javascript') {
$link = $widget['more_link'];
$link = \App::replacePlaceholder($link);
$link = \Util\Query::replacePlaceholder($link);
$result .= 'onclick="'.$link.'"';
}

View File

@ -2,7 +2,6 @@
namespace Models;
use App;
use Common\Model;
class Clause extends Model
@ -23,6 +22,6 @@ class Clause extends Model
public function getClauseAttribute($value)
{
return App::replacePlaceholder($value);
return Util\Query::replacePlaceholder($value);
}
}

View File

@ -2,7 +2,6 @@
namespace Models;
use App;
use Common\Model;
class View extends Model
@ -11,7 +10,7 @@ class View extends Model
public function getQueryAttribute($value)
{
return App::replacePlaceholder($value);
return Util\Query::replacePlaceholder($value);
}
/* Relazioni Eloquent */

View File

@ -120,7 +120,7 @@ class Modules
$results = $database->fetchArray('SELECT * FROM `zz_group_module` WHERE `idgruppo` = (SELECT `idgruppo` FROM `zz_users` WHERE `id` = '.prepare($user['id']).') AND `enabled` = 1 AND `idmodule` = '.prepare($module['id']));
foreach ($results as $result) {
if (!empty($result['clause'])) {
$result['clause'] = App::replacePlaceholder($result['clause']);
$result['clause'] = Util\Query::replacePlaceholder($result['clause']);
$additionals[$result['position']][] = $result['clause'];
}
@ -131,7 +131,7 @@ class Modules
$id_segment = $_SESSION['module_'.$module['id']]['id_segment'];
foreach ($segments as $result) {
if (!empty($result['clause']) && $result['id'] == $id_segment) {
$result['clause'] = App::replacePlaceholder($result['clause']);
$result['clause'] = Util\Query::replacePlaceholder($result['clause']);
$additionals[$result['position']][] = $result['clause'];
}

329
src/Util/Query.php Normal file
View File

@ -0,0 +1,329 @@
<?php
namespace Util;
use Auth;
use Modules;
use Translator;
/**
* Classe per la gestione delle interazione di base per le query dinamiche.
*
* @since 2.4.7
*/
class Query
{
/**
* Restituisce un'insieme di array comprendenti le informazioni per la costruzione della query del modulo indicato.
*
* @param $element
*
* @throws \Exception
*
* @return array
*/
public static function readQuery($element)
{
if (str_contains($element['option'], '|select|')) {
$result = self::readNewQuery($element);
} else {
$result = self::readOldQuery($element);
}
return $result;
}
/**
* Sostituisce i valori previsti all'interno delle query di moduli/plugin.
*
* @param string $query
*
* @return string
*/
public static function replacePlaceholder($query)
{
$id_parent = filter('id_parent');
$id_module = Modules::getCurrent()['id'];
$segment = $_SESSION['module_'.$id_module]['id_segment'];
$user = Auth::user();
// Elenco delle sostituzioni
$replace = [
// Identificatori
'|id_anagrafica|' => prepare($user['idanagrafica']),
'|id_utente|' => prepare($user['id']),
'|id_parent|' => prepare($id_parent),
// Date
'|period_start|' => $_SESSION['period_start'],
'|period_end|' => $_SESSION['period_end'],
// Segmenti
'|segment|' => !empty($segment) ? ' AND id_segment = '.prepare($segment) : '',
];
// Sostituzione dei formati
$patterns = formatter()->getSQLPatterns();
foreach ($patterns as $key => $value) {
$replace['|'.$key.'_format|'] = "'".$value."'";
}
// Sostituzione effettiva
$query = replace($query, $replace);
return $query;
}
/**
* Genera la query prevista dalla struttura indicata.
*
* @param $structure
* @param array $search
* @param array $order
* @param array $limit
*
* @throws \Exception
*
* @return mixed|string
*/
public static function getQuery($structure, $search = [], $order = [], $limit = [])
{
$total = self::readQuery($structure);
// Lettura parametri modulo
$query = $total['query'];
if (empty($query) || $query == 'menu' || $query == 'custom') {
return '';
}
// Filtri di ricerica
$search_filters = [];
foreach ($search as $field => $value) {
$pos = array_search($field, $total['fields']);
if (isset($value) && $pos !== false) {
$search_query = $total['search_inside'][$pos];
if (str_contains($search_query, '|search|')) {
$pieces = explode(',', $value);
foreach ($pieces as $piece) {
$piece = trim($piece);
$search_filters[] = str_replace('|search|', prepare('%'.$piece.'%'), $search_query);
}
} else {
// Per le icone cerco nel campo icon_title
if (preg_match('/^icon_(.+?)$/', $field, $m)) {
$search_query = '`icon_title_'.$m[1].'`';
}
// Per i colori cerco nel campo color_title
elseif (preg_match('/^color_(.+?)$/', $field, $m)) {
$search_query = '`color_title_'.$m[1].'`';
}
$search_filters[] = $search_query.' LIKE '.prepare('%'.trim($value.'%'));
}
}
// Ricerca
if (!empty($search_filters)) {
$query = str_replace('2=2', '2=2 AND ('.implode(' AND ', $search_filters).') ', $query);
}
}
// Ordinamento dei risultati
if (isset($order['dir']) && isset($order['column'])) {
$pos = array_search($order['column'], total['fields']);
if ($pos !== false) {
$pieces = explode('ORDER', $query);
$count = count($pieces);
if ($count > 1) {
unset($pieces[$count - 1]);
}
$query = implode('ORDER', $pieces).' ORDER BY '.$total['order_by'][$order['column']].' '.$order['dir'];
}
}
// Paginazione
if (!empty($limit)) {
$query .= ' LIMIT '.$limit['start'].', '.$limit['length'];
}
return $query;
}
/**
* Restituisce le somme richieste dalla query prevista dalla struttura.
*
* @param $structure
* @param array $search
*
* @throws \Exception
*
* @return array
*/
public static function getSums($structure, $search = [])
{
$total = self::readQuery($structure, $search);
// Calcolo di eventuali somme
if (empty($total['summable'])) {
return [];
}
$result_query = self::getQuery($structure, $search);
$query = str_replace_once('SELECT', 'SELECT '.implode(', ', $total['summable']).' FROM(SELECT ', $result_query).') AS `z`';
$sums = database()->fetchOne($query);
$results = [];
if (!empty($sums)) {
foreach ($sums as $key => $sum) {
if (str_contains($key, 'sum_')) {
$results[str_replace('sum_', '', $key)] = Translator::numberToLocale($sum);
}
}
}
return $results;
}
/**
* Interpreta lo standard modulare per l'individuazione delle query di un modulo/plugin del progetto.
*
* @param $element
*
* @throws \Exception
*
* @return array
*/
protected static function readNewQuery($element)
{
$fields = [];
$summable = [];
$search_inside = [];
$search = [];
$format = [];
$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 (!empty($view['visible'])) {
$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' => self::replacePlaceholder($query),
'fields' => $fields,
'search_inside' => $search_inside,
'order_by' => $order_by,
'search' => $search,
'slow' => $slow,
'format' => $format,
'summable' => $summable,
];
}
/**
* Interpreta lo standard JSON per l'individuazione delle query di un modulo/plugin del progetto.
*
* @param array $element
*
* @return array
*/
protected static function readOldQuery($element)
{
$options = str_replace(["\r", "\n", "\t"], ' ', $element['option']);
$options = json_decode($options, true);
$options = $options['main_query'][0];
$fields = [];
$order_by = [];
$search = [];
$slow = [];
$format = [];
$query = $options['query'];
$views = explode(',', $options['fields']);
foreach ($views as $view) {
$fields[] = trim($view);
$order_by[] = '`'.trim($view).'`';
$search[] = 1;
$slow[] = 0;
$format[] = 0;
}
$search_inside = $order_by;
return [
'query' => self::replacePlaceholder($query),
'fields' => $fields,
'search_inside' => $search_inside,
'order_by' => $order_by,
'search' => $search,
'slow' => $slow,
'format' => $format,
'summable' => [],
];
}
/**
* Restituisce le singole componenti delle query per un determinato modulo/plugin.
*
* @param $element
*
* @throws \Exception
*
* @return array
*/
protected static function getViews($element)
{
$database = database();
$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;
}
}

View File

@ -5,7 +5,7 @@ include_once __DIR__.'/../../core.php';
$module_name = 'Interventi';
// carica intervento
$query = 'SELECT in_interventi.*, (SELECT numero FROM co_contratti WHERE id=(SELECT idcontratto FROM co_promemoria WHERE idintervento=in_interventi.id)) AS numero_contratto, (SELECT numero FROM co_preventivi WHERE id=in_interventi.id_preventivo) AS numero_preventivo, (SELECT SUM(prezzo_dirittochiamata) FROM in_interventi_tecnici GROUP BY idintervento HAVING idintervento=in_interventi.id) AS `tot_dirittochiamata`, (SELECT SUM(km) FROM in_interventi_tecnici GROUP BY idintervento HAVING idintervento=in_interventi.id) AS `tot_km`, (SELECT SUM(ore*prezzo_ore_unitario) FROM in_interventi_tecnici GROUP BY idintervento HAVING idintervento=in_interventi.id) AS `tot_ore_consuntivo`, (SELECT SUM(prezzo_km_consuntivo) FROM in_interventi_tecnici GROUP BY idintervento HAVING idintervento=in_interventi.id) AS `tot_km_consuntivo`, in_interventi.descrizione AS `descrizione_intervento`, richiesta, (SELECT descrizione FROM in_tipiintervento WHERE idtipointervento=in_interventi.idtipointervento) AS tipointervento FROM in_interventi INNER JOIN in_tipiintervento ON in_interventi.idtipointervento=in_tipiintervento.idtipointervento WHERE id='.prepare($id_record).' '.Modules::getAdditionalsQuery('Interventi');
$query = 'SELECT in_interventi.*, (SELECT numero FROM co_contratti WHERE id=(SELECT idcontratto FROM co_promemoria WHERE idintervento=in_interventi.id)) AS numero_contratto, (SELECT numero FROM co_preventivi WHERE id=in_interventi.id_preventivo) AS numero_preventivo, (SELECT SUM(prezzo_dirittochiamata) FROM in_interventi_tecnici GROUP BY idintervento HAVING idintervento=in_interventi.id) AS `tot_dirittochiamata`, (SELECT SUM(km) FROM in_interventi_tecnici GROUP BY idintervento HAVING idintervento=in_interventi.id) AS `tot_km`, (SELECT SUM(ore*prezzo_ore_unitario) FROM in_interventi_tecnici GROUP BY idintervento HAVING idintervento=in_interventi.id) AS `tot_ore_consuntivo`, (SELECT SUM(prezzo_km_consuntivo) FROM in_interventi_tecnici GROUP BY idintervento HAVING idintervento=in_interventi.id) AS `tot_km_consuntivo`, in_interventi.descrizione AS `descrizione_intervento`, richiesta, (SELECT descrizione FROM in_tipiintervento WHERE idtipointervento=in_interventi.idtipointervento) AS tipointervento FROM in_interventi INNER JOIN in_tipiintervento ON in_interventi.idtipointervento=in_tipiintervento.idtipointervento WHERE id='.prepare($id_record);
$records = $dbo->fetchArray($query);
$costi_intervento = get_costi_intervento($id_record);

View File

@ -5,7 +5,7 @@ include_once __DIR__.'/../../core.php';
$module = Modules::get('Interventi');
$id_module = $module['id'];
$total = App::readQuery($module);
$total = Util\Query::readQuery($module);
// Lettura parametri modulo
$module_query = $total['query'];