From 0a911a877a32580a44442917c72655c836034183 Mon Sep 17 00:00:00 2001 From: Thomas Zilio Date: Sun, 6 Jan 2019 14:18:48 +0100 Subject: [PATCH] Generalizzazione gestione errori Aggiunta di un sistema standard per la gestione degli errori in caso di debug disattivato. Sostituzione di alcuni metodi della classe Database con il corrispettivo Eloquent. --- composer.json | 3 +- core.php | 4 +- include/init/update.php | 9 +- include/src/Components/Row.php | 30 +-- include/src/Document.php | 36 +-- modules/anagrafiche/actions.php | 22 +- modules/anagrafiche/add.php | 1 - modules/anagrafiche/edit.php | 16 +- modules/anagrafiche/plugins/statistiche.php | 4 +- modules/ddt/src/Components/Articolo.php | 2 +- modules/primanota/actions.php | 26 +-- modules/primanota/add.php | 6 +- plugins/exportFE/src/FatturaElettronica.php | 17 +- plugins/importFE/rows.php | 4 +- src/Auth.php | 2 +- src/Database.php | 234 ++++---------------- src/Extensions/MessageHandler.php | 31 +++ src/HTMLBuilder/Manager/FileManager.php | 4 +- src/Update.php | 6 +- update/2_4_5.sql | 3 - 20 files changed, 181 insertions(+), 279 deletions(-) create mode 100644 src/Extensions/MessageHandler.php diff --git a/composer.json b/composer.json index 9f8f2d3d8..d045ee1e7 100644 --- a/composer.json +++ b/composer.json @@ -61,7 +61,8 @@ }, "require-dev": { "codeception/codeception": "2.4.*", - "friendsofphp/php-cs-fixer": "^2.10" + "friendsofphp/php-cs-fixer": "^2.10", + "phpmd/phpmd": "2.6.0" }, "autoload": { "psr-4": { diff --git a/core.php b/core.php index 4df2501b8..ba0afd8d5 100644 --- a/core.php +++ b/core.php @@ -82,6 +82,7 @@ if (!API::isAPIRequest()) { // File di log di base (logs/error.log) $handlers[] = new StreamHandler($docroot.'/logs/error.log', Monolog\Logger::ERROR); $handlers[] = new StreamHandler($docroot.'/logs/setup.log', Monolog\Logger::EMERGENCY); + $handlers[] = new Extensions\MessageHandler(Monolog\Logger::ERROR); // Impostazioni di debug if (App::debug()) { @@ -128,13 +129,14 @@ if (App::debug()) { $monologFormatter->includeStacktraces(true); } +// Filtra gli errori per livello preciso del gestore dedicato foreach ($handlers as $handler) { $handler->setFormatter($monologFormatter); $logger->pushHandler(new FilterHandler($handler, [$handler->getLevel()])); } // Imposta Monolog come gestore degli errori -Monolog\ErrorHandler::register($logger); +Monolog\ErrorHandler::register($logger, [], Monolog\Logger::ERROR, Monolog\Logger::ERROR); // Database $dbo = $database = database(); diff --git a/include/init/update.php b/include/init/update.php index edecc88e0..78401ed2f 100644 --- a/include/init/update.php +++ b/include/init/update.php @@ -73,7 +73,10 @@ if (filter('action') == 'do_update') { Update::updateCleanup(); echo ' -

'.tr('Aggiornamento completato').'

'; +

'.tr('Aggiornamento completato').'

+ '; // Istruzioni per la prima installazione if ($_GET['firstuse'] == 'true') { @@ -214,6 +217,10 @@ if (filter('action') == 'do_update') { percent = Math.round(percent); percent = percent > 100 ? 100 : percent; + setPercent(percent); + } + + function setPercent(percent){ $("#progress .progress-bar").width(percent + "%"); $("#progress .progress-bar span").text(percent + "%"); } diff --git a/include/src/Components/Row.php b/include/src/Components/Row.php index 1a3c05ce8..4a3cb5210 100644 --- a/include/src/Components/Row.php +++ b/include/src/Components/Row.php @@ -212,6 +212,21 @@ abstract class Row extends Description return parent::save($options); } + public function aliquota() + { + return $this->belongsTo(Aliquota::class, 'idiva'); + } + + public function rivalsa() + { + return $this->belongsTo(RivalsaINPS::class, 'idrivalsainps'); + } + + public function ritenuta() + { + return $this->belongsTo(RitenutaAcconto::class, 'idritenutaacconto'); + } + protected static function boot($bypass = false) { parent::boot(true); @@ -277,19 +292,4 @@ abstract class Row extends Description { $this->attributes['sconto'] = $this->sconto; } - - public function aliquota() - { - return $this->belongsTo(Aliquota::class, 'idiva'); - } - - public function rivalsa() - { - return $this->belongsTo(RivalsaINPS::class, 'idrivalsainps'); - } - - public function ritenuta() - { - return $this->belongsTo(RitenutaAcconto::class, 'idritenutaacconto'); - } } diff --git a/include/src/Document.php b/include/src/Document.php index d1a89fc2f..8e0f679d5 100644 --- a/include/src/Document.php +++ b/include/src/Document.php @@ -26,24 +26,6 @@ abstract class Document extends Model abstract public function scontoGlobale(); - /** - * Calcola la somma degli attributi indicati come parametri. - * Il metodo **non** deve essere adattato per ulteriori funzionalità: deve esclusivamente calcolare la somma richiesta in modo esplicito dagli argomenti. - * - * @param mixed ...$args - * - * @return float - */ - protected function calcola(...$args) - { - $result = 0; - foreach ($args as $arg) { - $result += $this->getRigheContabili()->sum($arg); - } - - return $this->round($result); - } - /** * Calcola l'imponibile della fattura. * @@ -154,6 +136,24 @@ abstract class Document extends Model return $this->calcola('guadagno'); } + /** + * Calcola la somma degli attributi indicati come parametri. + * Il metodo **non** deve essere adattato per ulteriori funzionalità: deve esclusivamente calcolare la somma richiesta in modo esplicito dagli argomenti. + * + * @param mixed ...$args + * + * @return float + */ + protected function calcola(...$args) + { + $result = 0; + foreach ($args as $arg) { + $result += $this->getRigheContabili()->sum($arg); + } + + return $this->round($result); + } + /** * Restituisce la collezione di righe e articoli con valori rilevanti per i conti. * diff --git a/modules/anagrafiche/actions.php b/modules/anagrafiche/actions.php index 0d88c2507..3699c9b08 100644 --- a/modules/anagrafiche/actions.php +++ b/modules/anagrafiche/actions.php @@ -25,12 +25,12 @@ switch (post('op')) { $sede->email = post('email'); $sede->save(); - - if (!empty(post('nome')) and !empty(post('cognome')) ){ - $ragione_sociale = post('nome').' '.post('cognome'); - }else{ - $ragione_sociale = post('ragione_sociale'); - } + + if (!empty(post('nome')) and !empty(post('cognome'))) { + $ragione_sociale = post('nome').' '.post('cognome'); + } else { + $ragione_sociale = post('ragione_sociale'); + } // Informazioni sull'anagrafica $anagrafica->codice = post('codice'); $anagrafica->tipo = post('tipo'); @@ -68,7 +68,7 @@ switch (post('op')) { $anagrafica->idagente = post('idagente'); $anagrafica->idrelazione = post('idrelazione'); $anagrafica->sitoweb = post('sitoweb'); - $anagrafica->nome = post('nome'); + $anagrafica->nome = post('nome'); $anagrafica->cognome = post('cognome'); $anagrafica->iscrizione_tribunale = post('iscrizione_tribunale'); $anagrafica->cciaa = post('cciaa'); @@ -127,7 +127,7 @@ switch (post('op')) { case 'add': $idtipoanagrafica = post('idtipoanagrafica'); $ragione_sociale = post('ragione_sociale'); - + $anagrafica = Anagrafica::build($ragione_sociale, $idtipoanagrafica); $id_record = $anagrafica->id; @@ -145,9 +145,9 @@ switch (post('op')) { } $idagente = ($agente_is_logged && in_array($id_cliente, $idtipoanagrafica)) ? $user['idanagrafica'] : 0; - - $anagrafica->nome = post('nome'); - $anagrafica->cognome = post('cognome'); + + $anagrafica->nome = post('nome'); + $anagrafica->cognome = post('cognome'); $anagrafica->partita_iva = post('piva'); $anagrafica->codice_fiscale = post('codice_fiscale'); $anagrafica->indirizzo = post('indirizzo'); diff --git a/modules/anagrafiche/add.php b/modules/anagrafiche/add.php index 967eec884..a159b7a6a 100644 --- a/modules/anagrafiche/add.php +++ b/modules/anagrafiche/add.php @@ -32,7 +32,6 @@ echo ' '; - echo '
diff --git a/modules/anagrafiche/edit.php b/modules/anagrafiche/edit.php index ff30377c7..bec55752b 100644 --- a/modules/anagrafiche/edit.php +++ b/modules/anagrafiche/edit.php @@ -95,9 +95,17 @@ if (!$cliente) {
Attenzione: per impostare il codice specificare prima \'Tipologia\' e \'Nazione\' dell\'anagrafica:
  • Ente pubblico (B2G/PA) - Codice Univoco Ufficio (www.indicepa.gov.it), 6 caratteri
  • Azienda (B2B) - Codice Destinatario, 7 caratteri
  • Privato (B2C) - viene utilizzato il Codice Fiscale
'.((in_array($id_azienda, $tipi_anagrafica)) ? '

N.B. non è necessario comunicare il proprio codice destinatario ai fornitori in quanto è sufficiente che questo sia registrato nel portale del Sistema Di Interscambio dell\'Agenzia Entrate (SDI)

' : '').''; - ?> - {[ "type": "text", "label": "", "name": "codice_destinatario", "required": 0, "class": "text-center text-uppercase alphanumeric-mask", "value": "$codice_destinatario$", "maxlength": , "extra": "", "help": "", "readonly": "sedeLegale->nazione->iso2 != 'IT'); ?>" ]} + $help_codice_destinatario = tr("Per impostare il codice specificare prima 'Tipologia' e 'Nazione' dell'anagrafica").':
    +
  • '.tr('Ente pubblico (B2G/PA) - Codice Univoco Ufficio (www.indicepa.gov.it), 6 caratteri').'
  • +
  • '.tr('Azienda (B2B) - Codice Destinatario, 7 caratteri').'
  • +
  • '.tr('Privato (B2C) - viene utilizzato il Codice Fiscale').'
  • +
'; + + if (in_array($id_azienda, $tipi_anagrafica)) { + $help_codice_destinatario .= ''.tr("Non è necessario comunicare il proprio codice destinatario ai fornitori in quanto è sufficiente che questo sia registrato nel portale del Sistema Di Interscambio dell'Agenzia Entrate (SDI)").'.'; + } + ?> + {[ "type": "text", "label": "", "name": "codice_destinatario", "required": 0, "class": "text-center text-uppercase alphanumeric-mask", "value": "$codice_destinatario$", "maxlength": , "extra": "", "help": "", "readonly": "sedeLegale->nazione->iso2 != 'IT'); ?>" ]}
@@ -449,7 +457,7 @@ if (!empty($google)) {
- {[ "type": "checkbox", "label": "", "name": "split_payment", "value": "$split_payment$", "help": "è obbligatorio per:
  • Stato;
  • organi statali ancorché dotati di personalità giuridica;
  • enti pubblici territoriali e dei consorzi tra essi costituiti;
  • Camere di Commercio;
  • Istituti universitari;
  • ASL e degli enti ospedalieri;
  • enti pubblici di ricovero e cura aventi prevalente carattere scientifico;
  • enti pubblici di assistenza e beneficienza;
  • enti di previdenza;
  • consorzi tra questi costituiti.
'); ?>", "placeholder": "", "extra" : "" ]} + {[ "type": "checkbox", "label": "", "name": "split_payment", "value": "$split_payment$", "help": "è obbligatorio per:
  • Stato;
  • organi statali ancorché dotati di personalità giuridica;
  • enti pubblici territoriali e dei consorzi tra essi costituiti;
  • Camere di Commercio;
  • Istituti universitari;
  • ASL e degli enti ospedalieri;
  • enti pubblici di ricovero e cura aventi prevalente carattere scientifico;
  • enti pubblici di assistenza e beneficienza;
  • enti di previdenza;
  • consorzi tra questi costituiti.
'); ?>", "placeholder": "", "extra" : "" ]}
diff --git a/modules/anagrafiche/plugins/statistiche.php b/modules/anagrafiche/plugins/statistiche.php index bdc922f65..742b4cb69 100644 --- a/modules/anagrafiche/plugins/statistiche.php +++ b/modules/anagrafiche/plugins/statistiche.php @@ -134,10 +134,10 @@ echo '
'; // Fatture di vendita $totale_fatture_vendita = 0; -$fatture = database()->fetchArray("SELECT id FROM co_documenti WHERE idanagrafica=".prepare($id_record)); +$fatture = database()->fetchArray('SELECT id FROM co_documenti WHERE idanagrafica='.prepare($id_record)); foreach ($fatture as $fattura) { - $totale_fatture_vendita = sum( $totale_fatture_vendita, Modules\Fatture\Fattura::find( $fattura['id'] )->netto ); + $totale_fatture_vendita = sum($totale_fatture_vendita, Modules\Fatture\Fattura::find($fattura['id'])->netto); } $data_start = strtotime('now'); diff --git a/modules/ddt/src/Components/Articolo.php b/modules/ddt/src/Components/Articolo.php index 985dfec53..7eb3517f2 100644 --- a/modules/ddt/src/Components/Articolo.php +++ b/modules/ddt/src/Components/Articolo.php @@ -15,7 +15,7 @@ class Articolo extends Article /** * Crea un nuovo articolo collegato ad una ddt. * - * @param DDT $ddt + * @param DDT $ddt * @param Original $articolo * * @return self diff --git a/modules/primanota/actions.php b/modules/primanota/actions.php index 409eb5b44..6be37bcc1 100644 --- a/modules/primanota/actions.php +++ b/modules/primanota/actions.php @@ -92,20 +92,18 @@ switch (post('op')) { //Creo il modello di prima nota if (!empty(post('crea_modello'))) { - - if (empty(post('idmastrino'))){ - $idmastrino = get_new_idmastrino('co_movimenti_modelli'); - }else{ - $dbo->query('DELETE FROM co_movimenti_modelli WHERE idmastrino='.prepare(post('idmastrino'))); - $idmastrino = post('idmastrino'); - } - - for ($i = 0; $i < sizeof(post('idconto')); ++$i) { - $idconto = post('idconto')[$i]; - $query = 'INSERT INTO co_movimenti_modelli(idmastrino, descrizione, idconto) VALUES('.prepare($idmastrino).', '.prepare($descrizione).', '.prepare($idconto).')'; - $dbo->query($query); - } - + if (empty(post('idmastrino'))) { + $idmastrino = get_new_idmastrino('co_movimenti_modelli'); + } else { + $dbo->query('DELETE FROM co_movimenti_modelli WHERE idmastrino='.prepare(post('idmastrino'))); + $idmastrino = post('idmastrino'); + } + + for ($i = 0; $i < sizeof(post('idconto')); ++$i) { + $idconto = post('idconto')[$i]; + $query = 'INSERT INTO co_movimenti_modelli(idmastrino, descrizione, idconto) VALUES('.prepare($idmastrino).', '.prepare($descrizione).', '.prepare($idconto).')'; + $dbo->query($query); + } } break; diff --git a/modules/primanota/add.php b/modules/primanota/add.php index d5ec108f2..d039f32a0 100644 --- a/modules/primanota/add.php +++ b/modules/primanota/add.php @@ -351,9 +351,11 @@ include_once __DIR__.'/../../core.php'; var causale = $(this).find('option:selected').text(); //aggiornava erroneamente anche la causale ed eventuale numero di fattura e data - + $('#bs-popup #desc').val(causale); - + $.get('/ajax_complete.php?op=get_conti&idmastrino='+idmastrino, function(data){ var conti = data.split(','); diff --git a/plugins/exportFE/src/FatturaElettronica.php b/plugins/exportFE/src/FatturaElettronica.php index b0baa2080..e37c84d27 100644 --- a/plugins/exportFE/src/FatturaElettronica.php +++ b/plugins/exportFE/src/FatturaElettronica.php @@ -637,8 +637,6 @@ class FatturaElettronica return $this->intermediario; } - - /** * Restituisce le informazioni riguardanti un anagrafica sulla base dell'identificativo fornito. * @@ -1077,12 +1075,11 @@ class FatturaElettronica return $result; } - /** - * Restituisce l'array responsabile per la generazione del tag TerzoIntermediarioOSoggettoEmittente (1.5). - * - * @return array - */ + * Restituisce l'array responsabile per la generazione del tag TerzoIntermediarioOSoggettoEmittente (1.5). + * + * @return array + */ protected static function getTerzoIntermediarioOSoggettoEmittente($fattura) { $intermediario = $fattura->getIntermediario(); @@ -1094,7 +1091,6 @@ class FatturaElettronica return $result; } - /** * Restituisce l'array responsabile per la generazione del tag DatiGeneraliDocumento. * @@ -1105,6 +1101,8 @@ class FatturaElettronica $documento = $fattura->getDocumento(); $azienda = static::getAzienda(); + $fattura = Modules\Fatture\Fattura::find($documento['id']); + $result = [ 'TipoDocumento' => $documento['tipo_documento'], 'Divisa' => 'EUR', @@ -1157,8 +1155,6 @@ class FatturaElettronica $iva = database()->fetchOne('SELECT `percentuale`, `codice_natura_fe` FROM `co_iva` WHERE `id` = '.prepare($aliquota_iva_rivalsainps)); $percentuale = database()->fetchOne('SELECT percentuale FROM co_rivalsainps WHERE id = '.prepare($id_rivalsainps))['percentuale']; - $fattura = Modules\Fatture\Fattura::find($documento['id']); - $dati_cassa = [ 'TipoCassa' => setting('Tipo Cassa'), 'AlCassa' => $percentuale, @@ -1196,7 +1192,6 @@ class FatturaElettronica // Importo Totale Documento (2.1.1.9) // Importo totale del documento al netto dell'eventuale sconto e comprensivo di imposta a debito del cessionario / committente - $fattura = Modules\Fatture\Fattura::find($documento['id']); $result['ImportoTotaleDocumento'] = $fattura->netto; return $result; diff --git a/plugins/importFE/rows.php b/plugins/importFE/rows.php index 0ea8a412f..b8d2ec747 100644 --- a/plugins/importFE/rows.php +++ b/plugins/importFE/rows.php @@ -30,8 +30,8 @@ echo '

'. $ragione_sociale.'
- '.( !empty($codice_fiscale) ? (tr('Codice Fiscale').': '.$codice_fiscale.'
') : '' ).' - '.( !empty($partita_iva) ? (tr('Partita IVA').': '.$partita_iva.'
') : '' ).' + '.(!empty($codice_fiscale) ? (tr('Codice Fiscale').': '.$codice_fiscale.'
') : '').' + '.(!empty($partita_iva) ? (tr('Partita IVA').': '.$partita_iva.'
') : '').' '.$cap.' '.$citta.' ('.$provincia.')


'; diff --git a/src/Auth.php b/src/Auth.php index 51ca9e64a..7767e9c7a 100644 --- a/src/Auth.php +++ b/src/Auth.php @@ -460,7 +460,7 @@ class Auth extends \Util\Singleton try { $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)) { $this->user = User::with('group')->find($user_id); diff --git a/src/Database.php b/src/Database.php index 091d7a1f7..655d45173 100644 --- a/src/Database.php +++ b/src/Database.php @@ -89,7 +89,7 @@ class Database extends Util\Singleton $e = new PDOException(($e->getCode() == 1049) ? tr('Database non esistente!') : tr('Credenziali di accesso invalide!')); } - $this->signal($e, tr('Errore durante la connessione al database'), ['throw' => false, 'session' => false]); + throw $e; } } } @@ -203,51 +203,45 @@ class Database extends Util\Singleton * * @since 2.0 * - * @param string $query Query da eseguire + * @param string $query Query da eseguire + * @param array $parameters * * @return int */ - public function query($query, $parameters = [], $signal = null, $options = []) + public function query($query, $parameters = []) { - try { - $statement = $this->getPDO()->prepare($query); - $statement->execute($parameters); + $statement = $this->getPDO()->prepare($query); + $statement->execute($parameters); - $id = $this->lastInsertedID(); - if ($id == 0) { - return 1; - } else { - return $id; - } - } catch (PDOException $e) { - $signal = empty($signal) ? $query : $signal; - $this->signal($e, $signal, $options); + $id = $this->lastInsertedID(); + if ($id == 0) { + return 1; + } else { + return $id; } } /** * Restituisce un'array strutturato in base ai nomi degli attributi della selezione. * - * @since 2.0 + * @param string $query Query da eseguire + * @param array $parameters + * @param bool $numeric * - * @param string $query Query da eseguire + * @throws Exception * * @return array */ - public function fetchArray($query, $parameters = [], $numeric = false, $options = []) + public function fetchArray($query, $parameters = [], $numeric = false) { - try { - $mode = empty($numeric) ? PDO::FETCH_ASSOC : PDO::FETCH_NUM; + $mode = empty($numeric) ? PDO::FETCH_ASSOC : PDO::FETCH_NUM; - $statement = $this->getPDO()->prepare($query); - $statement->execute($parameters); + $statement = $this->getPDO()->prepare($query); + $statement->execute($parameters); - $result = $statement->fetchAll($mode); + $result = $statement->fetchAll($mode); - return $result; - } catch (PDOException $e) { - $this->signal($e, $query, $options); - } + return $result; } /** @@ -359,7 +353,7 @@ class Database extends Util\Singleton try { return $this->getPDO()->lastInsertId(); } catch (PDOException $e) { - $this->signal($e, tr("Impossibile ottenere l'ultimo identificativo creato")); + throw new PDOException(tr("Impossibile ottenere l'ultimo identificativo creato")); } } @@ -452,41 +446,40 @@ class Database extends Util\Singleton } $select = !empty($select) ? $select : ['*']; - // Costruzione della query - $query = 'SELECT '.implode(', ', $select).' FROM '.$this->quote($table); - - // Condizioni di selezione - $where = $this->whereStatement($conditions); - if (!empty($where)) { - $query .= ' WHERE '.$where; - } + $statement = Capsule::table($table)->where($conditions)->select($select); // Impostazioni di ordinamento if (!empty($order)) { - $list = []; - $allow = ['ASC', 'DESC']; foreach ((array) $order as $key => $value) { - if (is_numeric($key)) { - $key = $value; - $value = $allow[0]; + $order = is_numeric($key) ? 'ASC' : strtoupper($value); + $field = is_numeric($key) ? $value : key; + + if ($order == 'ASC') { + $statement = $statement->orderBy($field); + } else { + $statement = $statement->orderByDesc($field); } - - $value = in_array($value, $allow) ? $value : $allow[0]; - $list[] = $this->quote($key).' '.$value; } - - $query .= ' ORDER BY '.implode(', ', $list); } // Eventuali limiti if (!empty($limit)) { - $query .= ' LIMIT '.(is_array($limit) ? $limit[0].', '.$limit[1] : $limit); + $offset = is_array($limit) ? $limit[0] : null; + $count = is_array($limit) ? $limit[1] : $limit; + + if ($offset) { + $statement = $statement->offset($offset); + } + + $statement = $statement->limit($count); } if (!empty($return)) { - return $query; + return $statement->toSql(); } else { - return $this->fetchArray($query); + $result = $statement->get()->toArray(); + + return json_decode(json_encode($result), true); } } @@ -523,24 +516,17 @@ class Database extends Util\Singleton * * @param string $table * @param array $conditions - * @param bool $return * * @return string|array */ - public function delete($table, $conditions, $return = false) + public function delete($table, $conditions) { if (!is_string($table) || !is_array($conditions)) { throw new UnexpectedValueException(); } // Costruzione della query - $query = 'DELETE FROM '.$this->quote($table).' WHERE '.$this->whereStatement($conditions); - - if (!empty($return)) { - return $query; - } else { - return $this->query($query); - } + return Capsule::table($table)->where($conditions)->delete(); } /** @@ -647,7 +633,7 @@ class Database extends Util\Singleton } /** - * Esegue le query interne ad un file .sql. + * Esegue le query interne ad un file ".sql". * * @since 2.0 * @@ -660,15 +646,7 @@ class Database extends Util\Singleton $end = count($queries); for ($i = $start; $i < $end; ++$i) { - try { - $this->getPDO()->exec($queries[$i]); - } catch (PDOException $e) { - $this->signal($e, $queries[$i], [ - 'throw' => false, - ]); - - return $i; - } + $this->query($queries[$i]); } return true; @@ -689,124 +667,4 @@ class Database extends Util\Singleton return $char.str_replace([$char, '#'], '', $string).$char; } - - /** - * Predispone una variabile per il relativo inserimento all'interno di uno statement SQL. - * - * @since 2.3 - * - * @param string $value - * - * @return string - */ - protected function prepareValue($field, $value) - { - $value = (is_null($value)) ? 'NULL' : $value; - $value = is_bool($value) ? intval($value) : $value; - - if (!starts_with($field, '#')) { - if ($value != 'NULL') { - $value = $this->prepare($value); - } - } - - return $value; - } - - /** - * Predispone il contenuto di un array come clausola WHERE. - * - * @since 2.3 - * - * @param string|array $where - * @param bool $and - * - * @return string - */ - protected function whereStatement($where, $and = true) - { - $result = []; - - foreach ($where as $key => $value) { - // Query personalizzata - if (starts_with($key, '#')) { - $result[] = $this->prepareValue($key, $value); - } else { - // Ulteriori livelli di complessità - if (is_array($value) && in_array(strtoupper($key), ['AND', 'OR'])) { - $result[] = '('.$this->whereStatement($value, $key == 'AND').')'; - } - // Condizione IN - elseif (is_array($value)) { - if (!empty($value)) { - $in = []; - foreach ($value as $v) { - $in[] = $this->prepareValue($key, $v); - } - - $result[] = $this->quote($key).' IN ('.implode(',', $in).')'; - } - } - // Condizione LIKE - elseif (str_contains($value, '%') || str_contains($value, '_')) { - $result[] = $this->quote($key).' LIKE '.$this->prepareValue($key, $value); - } - // Condizione BETWEEN - elseif (str_contains($value, '|')) { - $pieces = explode('|', $value); - $result[] = $this->quote($key).' BETWEEN '.$this->prepareValue($key, $pieces[0]).' AND '.$this->prepareValue($key, $pieces[1]); - } - // Condizione di uguaglianza - else { - $prepared = $this->prepareValue($key, $value); - - if ($prepared == 'NULL') { - $result[] = $this->quote($key).' IS '.$prepared; - } else { - $result[] = $this->quote($key).' = '.$prepared; - } - } - } - } - - $cond = !empty($and) ? 'AND' : 'OR'; - - return implode(' '.$cond.' ', $result); - } - - /** - * Aggiunge informazioni alla struttura di base dell'erroe o dell'eccezione intercettata. - * - * @since 2.3 - */ - protected function signal($e, $message, $options = []) - { - $options = array_merge([ - 'session' => true, - 'level' => \Monolog\Logger::ERROR, - 'throw' => true, - ], $options); - - if (!empty($options['session']) && !API::isAPIRequest()) { - $msg = tr("Si è verificato un'errore").'.'; - - if (Auth::check()) { - $msg .= ' '.tr('Se il problema persiste siete pregati di chiedere assistenza tramite la sezione Bug').'. '; - } - - $msg .= '
'.$e->getMessage().''; - - flash()->error($msg); - } - - $error = $e->getMessage().' - '.$message; - - if (!empty($options['throw'])) { - throw new PDOException($error); - } else { - $logger = logger(); - - $logger->addRecord($options['level'], $error); - } - } } diff --git a/src/Extensions/MessageHandler.php b/src/Extensions/MessageHandler.php new file mode 100644 index 000000000..0d0f26e76 --- /dev/null +++ b/src/Extensions/MessageHandler.php @@ -0,0 +1,31 @@ +check()) { + $message .= ' + '.tr('Se il problema persiste siete pregati di chiedere assistenza tramite la sezione Bug').'. +
'.$record['message'].''; + } + + //flash()->error($message); + + echo ' +
+ '.$message.' +
'; + } +} diff --git a/src/HTMLBuilder/Manager/FileManager.php b/src/HTMLBuilder/Manager/FileManager.php index fb4381d75..2daed0058 100644 --- a/src/HTMLBuilder/Manager/FileManager.php +++ b/src/HTMLBuilder/Manager/FileManager.php @@ -77,7 +77,7 @@ class FileManager implements ManagerInterface '; foreach ($rs as $r) { - $extension = pathinfo($r['original'])['extension']; + $extension = pathinfo($r['original'])['extension']; $result .= ' @@ -112,7 +112,7 @@ class FileManager implements ManagerInterface '; - } elseif (strtolower($extension) == 'xml' ) { + } elseif (strtolower($extension) == 'xml') { $result .= ' diff --git a/src/Update.php b/src/Update.php index 08be97caf..b68f882ea 100644 --- a/src/Update.php +++ b/src/Update.php @@ -219,7 +219,11 @@ class Update if ($start < $end) { for ($i = $start; $i < $end; ++$i) { - $database->query($queries[$i], [], tr('Aggiornamento fallito').': '.$queries[$i]); + try { + $database->query($queries[$i]); + } catch (\Exception $e) { + throw new PDOException(tr('Aggiornamento fallito').': '.$queries[$i]); + } $database->query('UPDATE `updates` SET `done` = :done WHERE id = :id', [ ':done' => $i + 3, diff --git a/update/2_4_5.sql b/update/2_4_5.sql index 8e14cf590..b6188736c 100644 --- a/update/2_4_5.sql +++ b/update/2_4_5.sql @@ -36,11 +36,9 @@ UPDATE `zz_settings` SET `tipo` = 'query=SELECT ''IMP'' AS id, ''Imponibile'' AS UPDATE `an_anagrafiche` SET `provincia` = UPPER(provincia); UPDATE `an_sedi` SET `provincia` = UPPER(provincia); - -- Colonna Codice Modalità (Pagamenti) INSERT INTO `zz_views` (`id`, `id_module`, `name`, `query`, `order`, `search`, `slow`, `format`, `search_inside`, `order_by`, `visible`, `summable`, `default` ) VALUES (NULL, (SELECT `id` FROM `zz_modules` WHERE `name` = 'Pagamenti'), 'Codice Modalità', 'codice_modalita_pagamento_fe', 2, 1, 0, 0, NULL, NULL, 1, 0, 0); - -- Impostazione "Anagrafica del terzo intermediario" INSERT INTO `zz_settings` (`id`, `nome`, `valore`, `tipo`, `editable`, `sezione`) VALUES (NULL, 'Terzo intermediario', '', 'query=SELECT `an_anagrafiche`.`idanagrafica` AS ''id'', `ragione_sociale` AS ''descrizione'' FROM `an_anagrafiche` INNER JOIN `an_tipianagrafiche_anagrafiche` ON `an_anagrafiche`.`idanagrafica` = `an_tipianagrafiche_anagrafiche`.`idanagrafica` WHERE `idtipoanagrafica` = (SELECT `idtipoanagrafica` FROM `an_tipianagrafiche` WHERE `descrizione` = ''Fornitore'') AND `deleted_at` IS NULL', '1', 'Fatturazione Elettronica'); @@ -48,7 +46,6 @@ INSERT INTO `zz_settings` (`id`, `nome`, `valore`, `tipo`, `editable`, `sezione` ALTER TABLE `an_anagrafiche` CHANGE `nome_cognome` `nome` VARCHAR(255) NOT NULL; ALTER TABLE `an_anagrafiche` ADD `cognome` VARCHAR(255) NOT NULL AFTER `nome`; - -- Colonna Rif. fattura (Prima nota) INSERT INTO `zz_views` (`id`, `id_module`, `name`, `query`, `order`, `search`, `slow`, `format`, `search_inside`, `order_by`, `visible`, `summable`, `default` ) VALUES (NULL, (SELECT `id` FROM `zz_modules` WHERE `name` = 'Prima nota'), 'Rif. fattura', 'IF((iddocumento != ''),(SELECT numero_esterno FROM co_documenti WHERE id = iddocumento), ''-'')', 2, 1, 0, 0, NULL, NULL, 1, 0, 0);