Introduzione gestione tramite pacchetto Laravel

This commit is contained in:
Dasc3er 2021-08-06 17:26:51 +02:00 committed by Thomas Zilio
parent 4869e50eb3
commit 3b3b8b25d3
21 changed files with 306 additions and 249 deletions

View File

@ -88,7 +88,7 @@ if (filter('op') == 'send') {
}
redirect_legacy(base_url().'/bug.php');
throw new \App\Exceptions\LegacyExitException();
throw new \LegacyExitException();
}
$pageTitle = tr('Bug');

View File

@ -1,5 +1,5 @@
{
"name": "devcode-it/openstamanager",
"name": "devcode-it/legacy",
"description": "Gestionale open-source per assistenza tecnica e fatturazione elettronica",
"license": "GPL-3.0",
"keywords": [
@ -13,14 +13,8 @@
"name": "DevCode s.r.l.",
"email": "info@openstamanager.com"
}],
"type": "project",
"require": {
"php": "^7.3|^8.0",
"fideloper/proxy": "^4.4",
"fruitcake/laravel-cors": "^2.0",
"guzzlehttp/guzzle": "^7.0.1",
"laravel/framework": "^8.12",
"laravel/tinker": "^2.5",
"php": ">=7.2",
"ext-curl": "*",
"ext-dom": "*",
"ext-fileinfo": "*",
@ -36,44 +30,25 @@
"aluguest/ical-easy-reader": "^1.5",
"voku/stringy": "~6.0",
"davidepastore/codice-fiscale": "^0.6.0",
"dragonmantank/cron-expression": "^1.0",
"ezyang/htmlpurifier": "^4.8",
"filp/whoops": "^2.1",
"ifsnop/mysqldump-php": "^2.3",
"illuminate/database": "^6.0",
"illuminate/support": "~7|~8",
"intervention/image": "^2.3",
"league/csv": "^8.2",
"league/oauth2-client": "^2.6",
"league/oauth2-google": "^3.0",
"maximebf/debugbar": "^1.15",
"monolog/monolog": "^1.22",
"mpdf/mpdf": "^v8.0.7",
"mpociot/vat-calculator": "^2.3",
"owasp/csrf-protector-php": "^1.0",
"phpmailer/phpmailer": "^6.0",
"respect/validation": "^1.1",
"servo/fluidxml": "^1.21",
"slim/flash": "^0.4.0",
"spipu/html2pdf": "^5.0",
"symfony/filesystem": "^3.3",
"symfony/finder": "^3.3",
"symfony/polyfill-ctype": "^1.8",
"symfony/polyfill-php70": "^1.8",
"symfony/translation": "^3.3",
"symfony/var-dumper": "^3.3",
"thenetworg/oauth2-azure": "^2.0",
"willdurand/geocoder": "^3.3",
"digitick/sepa-xml": "^1.6",
"wdog/sdd_ita": "dev-master"
},
"require-dev": {
"codeception/codeception": "^3.0",
"friendsofphp/php-cs-fixer": "^2.10",
"facade/ignition": "^2.5",
"fakerphp/faker": "^1.9.1",
"mockery/mockery": "^1.4.2",
"nunomaduro/collision": "^5.0",
"phpunit/phpunit": "^9.3.3"
"phpunit/phpunit": "~9.0",
"orchestra/testbench": "~5|~6"
},
"autoload": {
"psr-4": {
@ -136,23 +111,14 @@
"lib/deprecated.php"
]
},
"repositories": [
{
"type": "vcs",
"url": "https://github.com/wdog/sdd_ita"
}
],
"config": {
"sort-packages": true,
"optimize-autoloader": false,
"apcu-autoloader": true,
"prefer-stable": true,
"platform-check": false,
"platform": {
"php": "7.4"
},
"allow-plugins": {
"kylekatarnls/update-helper": true
"extra": {
"laravel": {
"providers": [
"\\ServiceProvider"
],
"aliases": {
"Legacy": "\\Facades\\Legacy"
}
}
}
}

189
core.php
View File

@ -17,115 +17,15 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
// Impostazioni di configurazione PHP
date_default_timezone_set('Europe/Rome');
// Controllo sulla versione PHP
$minimum = '7.2.0';
if (version_compare(phpversion(), $minimum) < 0) {
echo '
<p>Stai utilizzando la versione PHP '.phpversion().', non compatibile con OpenSTAManager.</p>
<p>Aggiorna PHP alla versione >= '.$minimum.'.</p>';
throw new \App\Exceptions\LegacyExitException();
if (!auth()->check()) {
throw new \LegacyExitException();
}
// Caricamento delle impostazioni personalizzabili
if (file_exists(__DIR__.'/config.inc.php')) {
include_once __DIR__.'/config.inc.php';
}
/*
// Sicurezza della sessioni
ini_set('session.cookie_samesite', 'strict');
ini_set('session.use_trans_sid', '0');
ini_set('session.use_only_cookies', '1');
session_set_cookie_params(0, base_url(), null, isHTTPS(true));
session_start();*/
/* GESTIONE DEGLI ERRORI */
// Logger per la segnalazione degli errori
$logger = new Monolog\Logger('Logs');
$logger->pushProcessor(new Monolog\Processor\UidProcessor());
$logger->pushProcessor(new Monolog\Processor\WebProcessor());
// Registrazione globale del logger
Monolog\Registry::addLogger($logger, 'logs');
use Monolog\Handler\FilterHandler;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Handler\StreamHandler;
$handlers = [];
if (!$api_request) {
// File di log di base (logs/error.log, logs/setup.log)
$handlers[] = new StreamHandler(base_dir().'/logs/error.log', Monolog\Logger::ERROR);
$handlers[] = new StreamHandler(base_dir().'/logs/setup.log', Monolog\Logger::EMERGENCY);
// Messaggi grafici per l'utente
$handlers[] = new Extensions\MessageHandler(Monolog\Logger::ERROR);
// File di log ordinati in base alla data
if (AppLegacy::debug()) {
$handlers[] = new RotatingFileHandler(base_dir().'/logs/error.log', 0, Monolog\Logger::ERROR);
$handlers[] = new RotatingFileHandler(base_dir().'/logs/setup.log', 0, Monolog\Logger::EMERGENCY);
}
// Inizializzazione Whoops
$whoops = new Whoops\Run();
if (AppLegacy::debug()) {
$whoops->pushHandler(new Whoops\Handler\PrettyPageHandler());
}
// Abilita la gestione degli errori nel caso la richiesta sia di tipo AJAX
if (Whoops\Util\Misc::isAjaxRequest()) {
$whoops->pushHandler(new Whoops\Handler\JsonResponseHandler());
}
$whoops->register();
// Aggiunta di Monolog a Whoops
$whoops->pushHandler(function ($exception, $inspector, $run) use ($logger) {
$logger->addError($exception->getMessage(), [
'code' => $exception->getCode(),
'message' => $exception->getMessage(),
'file' => $exception->getFile(),
'line' => $exception->getLine(),
'trace' => $exception->getTraceAsString(),
]);
});
} else {
$handlers[] = new StreamHandler(base_dir().'/logs/api.log', Monolog\Logger::ERROR);
}
// Disabilita i messaggi nativi di PHP
ini_set('display_errors', 0);
// Ignora gli avvertimenti e le informazioni relative alla deprecazione di componenti
error_reporting(E_ALL & ~E_WARNING & ~E_CORE_WARNING & ~E_NOTICE & ~E_USER_DEPRECATED & ~E_STRICT);
$pattern = '[%datetime%] %channel%.%level_name%: %message% %context%'.PHP_EOL.'%extra% '.PHP_EOL;
$monologFormatter = new Monolog\Formatter\LineFormatter($pattern);
$monologFormatter->includeStacktraces(AppLegacy::debug());
// 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
$handler = new Monolog\ErrorHandler($logger);
if (!API\Response::isAPIRequest()) {
$handler->registerErrorHandler([]);
$handler->registerExceptionHandler(Monolog\Logger::ERROR);
}
$handler->registerFatalHandler(Monolog\Logger::ERROR);
// Database
$dbo = $database = database();
$lang = app()->getLocale();
/* INTERNAZIONALIZZAZIONE */
// Individuazione di versione e revisione del progetto
@ -134,80 +34,51 @@ $revision = Update::getRevision();
/* ACCESSO E INSTALLAZIONE */
// Controllo sulla presenza dei permessi di accesso basilari
$continue = $dbo->isInstalled() && !Update::isUpdateAvailable() && (auth()->check() || $api_request);
if (!empty($skip_permissions)) {
Permissions::skip();
}
if (!$continue && getURLPath() != slashes(base_url().'/index.php') && !Permissions::getSkip()) {
if (auth()->check()) {
auth()->logout();
}
redirect_legacy(base_url().'/');
throw new \App\Exceptions\LegacyExitException();
if (!(auth()->check() || $api_request) && !Permissions::getSkip()) {
throw new \LegacyExitException();
}
/* INIZIALIZZAZIONE GENERALE */
// Operazione aggiuntive (richieste non API)
if (!$api_request) {
// Impostazioni di Content-Type e Charset Header
header('Content-Type: text/html; charset=UTF-8');
// Registrazione globale del template per gli input HTML
ob_start();
// Retrocompatibilità
session(['infos' => isset($_SESSION['infos']) ? array_unique($_SESSION['infos']) : []]);
session(['warnings' => isset($_SESSION['warnings']) ? array_unique($_SESSION['warnings']) : []]);
session(['errors' => isset($_SESSION['errors']) ? array_unique($_SESSION['errors']) : []]);
// Impostazione del tema grafico di default
$theme = 'default';
if ($continue) {
// Periodo di visualizzazione dei record
// Personalizzato
if (!empty($_GET['period_start'])) {
session(['period_start' => $_GET['period_start']]);
session(['period_end' => $_GET['period_end']]);
}
// Dal 01-01-yyy al 31-12-yyyy
elseif (session('period_start') == null) {
session(['period_start' => date('Y').'-01-01']);
session(['period_end' => date('Y').'-12-31']);
$id_record = filter('id_record');
$id_parent = filter('id_parent');
Modules::setCurrent(filter('id_module'));
Plugins::setCurrent(filter('id_plugin'));
// Variabili fondamentali
$module = Modules::getCurrent();
$plugin = Plugins::getCurrent();
$structure = isset($plugin) ? $plugin : $module;
$id_module = $module ? $module['id'] : null;
$id_plugin = $plugin ? $plugin['id'] : null;
$user = auth()->user();
if (!empty($id_module)) {
// Segmenti
if (session('module_'.$id_module.'.id_segment') === null) {
$segments = Modules::getSegments($id_module);
session(['module_'.$id_module.'.id_segment' => isset($segments[0]['id']) ? $segments[0]['id'] : null]);
}
$id_record = filter('id_record');
$id_parent = filter('id_parent');
Modules::setCurrent(filter('id_module'));
Plugins::setCurrent(filter('id_plugin'));
// Variabili fondamentali
$module = Modules::getCurrent();
$plugin = Plugins::getCurrent();
$structure = isset($plugin) ? $plugin : $module;
$id_module = $module ? $module['id'] : null;
$id_plugin = $plugin ? $plugin['id'] : null;
$user = auth()->user();
if (!empty($id_module)) {
// Segmenti
if (session('module_'.$id_module.'.id_segment') === null) {
$segments = Modules::getSegments($id_module);
session(['module_'.$id_module.'.id_segment' => isset($segments[0]['id']) ? $segments[0]['id'] : null]);
}
Permissions::addModule($id_module);
}
Permissions::check();
Permissions::addModule($id_module);
}
Permissions::check();
// Retrocompatibilità
$post = Filter::getPOST();
$get = Filter::getGET();

View File

@ -41,7 +41,7 @@ echo '
</div><!-- ./wrapper -->';
if (auth()->check()) {
if (!empty($_SESSION['keep_alive'])) {
if (session('keep_alive') === true) {
echo '
<script> setInterval("session_keep_alive()", 5*60*1000); </script>';
}
@ -88,10 +88,3 @@ echo '
<script>$(document).ready(init)</script>
</body>
</html>';
// Retrocompatibilità
if (!empty($id_record) || basename($_SERVER['PHP_SELF']) == 'controller.php' || basename($_SERVER['PHP_SELF']) == 'index.php') {
unset($_SESSION['infos']);
unset($_SESSION['errors']);
unset($_SESSION['warnings']);
}

View File

@ -110,7 +110,7 @@ if (post('db_host') !== null) {
}
echo $state;
throw new \App\Exceptions\LegacyExitException();
throw new \LegacyExitException();
}
// Creazione della configurazione
@ -204,7 +204,7 @@ if (post('db_host') !== null) {
file_put_contents('manifest.json', $manifest);
redirect_legacy(base_url().'/index.php');
throw new \App\Exceptions\LegacyExitException();
throw new \LegacyExitException();
}
}
}
@ -609,4 +609,4 @@ if (empty($creation) && (!file_exists('config.inc.php') || !$valid_config)) {
include_once AppLegacy::filepath('include|custom|', 'bottom.php');
throw new \App\Exceptions\LegacyExitException();
throw new \LegacyExitException();

View File

@ -115,7 +115,7 @@ if (post('action') == 'init') {
}
redirect_legacy(base_url(), 'js');
throw new \App\Exceptions\LegacyExitException();
throw new \LegacyExitException();
}
$img = AppLegacy::getPaths()['img'];
@ -262,4 +262,4 @@ echo '
include_once AppLegacy::filepath('include|custom|', 'bottom.php');
throw new \App\Exceptions\LegacyExitException();
throw new \LegacyExitException();

View File

@ -109,7 +109,7 @@ if (filter('action') == 'do_update') {
</a>';
}
throw new \App\Exceptions\LegacyExitException();
throw new \LegacyExitException();
} elseif (Update::isUpdateAvailable()) {
// Controllo se l'aggiornamento è in esecuzione
if (Update::isUpdateLocked() && filter('force') === null) {
@ -131,7 +131,7 @@ if (filter('action') == 'do_update') {
include_once AppLegacy::filepath('include|custom|', 'bottom.php');
throw new \App\Exceptions\LegacyExitException();
throw new \LegacyExitException();
}
$firstuse = !$dbo->isInstalled() ? 'true' : 'false';

View File

@ -62,7 +62,7 @@ if (auth()->check() && isset($dbo) && $dbo->isConnected() && $dbo->isInstalled()
} else {
redirect_legacy(base_url().'/index.php?op=logout');
}
throw new \App\Exceptions\LegacyExitException();
throw new \LegacyExitException();
}
// Procedura di installazione

View File

@ -23,7 +23,6 @@
* @since 2.3
*/
use App\Exceptions\LegacyRedirectException;
use HTMLBuilder\HTMLBuilder;
use Models\OperationLog;
use Symfony\Component\Filesystem\Exception\IOException;
@ -248,23 +247,6 @@ function translateTemplate($template)
OperationLog::build($op);
}
// Retrocompatibilità
if (!empty($_SESSION['infos'])) {
foreach ($_SESSION['infos'] as $message) {
flash()->info($message);
}
}
if (!empty($_SESSION['warnings'])) {
foreach ($_SESSION['warnings'] as $message) {
flash()->warning($message);
}
}
if (!empty($_SESSION['errors'])) {
foreach ($_SESSION['errors'] as $message) {
flash()->error($message);
}
}
// Annullo le notifiche (AJAX)
if (isAjaxRequest()) {
//flash()->clearMessage('info');
@ -323,7 +305,7 @@ function redirectOperation($id_module, $id_record)
redirect_legacy(base_url().'/controller.php?id_module='.$id_module.$hash);
}
throw new \App\Exceptions\LegacyExitException();
throw new \LegacyExitException();
}
}
@ -434,7 +416,7 @@ function base_url()
*/
function base_dir()
{
return base_path().DIRECTORY_SEPARATOR.'legacy'.DIRECTORY_SEPARATOR;
return realpath(__DIR__.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR);
}
/**

View File

@ -26,7 +26,7 @@ if (get('anteprima') !== null) {
if (empty($rs)) {
echo tr('Intervento inesistente!');
throw new \App\Exceptions\LegacyExitException();
throw new \LegacyExitException();
}
// Gestione della stampa

View File

@ -47,7 +47,7 @@ switch (filter('op')) {
echo json_encode([
'id' => 1,
]);
throw new \App\Exceptions\LegacyExitException();
throw new \LegacyExitException();
} else {
$content = file_get_contents($temp_name);

View File

@ -60,7 +60,7 @@ switch (post('op')) {
}
redirect_legacy(base_url().'/index.php');
throw new \App\Exceptions\LegacyExitException();
throw new \LegacyExitException();
break;
case 'update':
@ -77,7 +77,7 @@ switch (post('op')) {
flash()->info(tr('Password cambiata!'));
redirect_legacy(base_url().'/index.php');
throw new \App\Exceptions\LegacyExitException();
throw new \LegacyExitException();
break;
}

24
routes.php Normal file
View File

@ -0,0 +1,24 @@
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use DevCode\CausaliTrasporto\Controllers\CausaliTrasportoController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::middleware('web')
->group(function () {
// Route di fallback generale
Route::any('/legacy/{path}', [LegacyController::class, 'index'])
->name('legacy')
->where('path', '.*');
});

View File

@ -0,0 +1,44 @@
<?php
namespace DevCode\CausaliTrasporto\Controllers;
use App\Http\Controllers\RequirementsController;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use InvalidArgumentException;
use DevCode\Aggiornamenti\Aggiornamento;
use DevCode\Aggiornamenti\DowngradeException;
class CausaliTrasportoController extends Controller
{
public $module;
public function __construct()
{
$this->module = module('Causali');
}
/**
* Display a listing of the resource.
* @return Renderable
*/
public function index()
{
return view('causali-trasporto::index', [
'module' => $this->module,
]);
}
/**
* Display a listing of the resource.
* @return Renderable
*/
public function dettagli()
{
$args = [
'module' => $this->module,
];
return view('causali-trasporto::dettagli', $args);
}
}

18
src/Facades/Legacy.php Normal file
View File

@ -0,0 +1,18 @@
<?php
namespace DevCode\CausaliTrasporto\Facades;
use Illuminate\Support\Facades\Facade;
class Legacy extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor(): string
{
return 'legacy';
}
}

83
src/LegacyController.php Normal file
View File

@ -0,0 +1,83 @@
<?php
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Redirect;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class LegacyController extends BaseController
{
use AuthorizesRequests;
use DispatchesJobs;
use ValidatesRequests;
public function index(Request $request, $path)
{
//$path = substr($request->getPathInfo(), 1);
// Gestione dell'output
$output = self::simulate($path);
$response = response($output);
// Fix content-type per contenuti non HTML
if (ends_with($path, '.js')) {
$response = $response->header('Content-Type', 'application/javascript');
} elseif (string_contains($path, 'pdfgen.php')) {
$response = $response->header('Content-Type', 'application/pdf');
}
// Correzione header per API
elseif (self::isApiRequest($path)) {
$output = json_decode($output, true);
$response = $response->header('Content-Type', 'application/json')
->setStatusCode($output['status']);
}
return $response;
}
public static function simulate($path)
{
$base_path = base_dir();
// Fix per redirect all'API
$api_request = self::isApiRequest($path);
if ($api_request) {
$path = 'api/index.php';
}
// Ricerca del file interessato
$file = realpath($base_path.'/'.$path);
if (strpos($file, $base_path) === false) {
throw new NotFoundHttpException();
}
// Inclusione diretta del file
ob_start();
try {
require $file;
} catch (LegacyExitException $e) {
} catch (LegacyRedirectException $e) {
return Redirect::to($e->getMessage());
}
// Gestione dell'output
$output = ob_get_clean();
return $output;
}
protected static function isApiRequest($path)
{
// Fix per redirect all'API
$api_request = false;
if (in_array($path, ['api', 'api/', 'api/index.php'])) {
$api_request = true;
}
return $api_request;
}
}

View File

@ -0,0 +1,6 @@
<?php
class LegacyExitException extends Exception
{
}

View File

@ -0,0 +1,10 @@
<?php
class LegacyRedirectException extends Exception
{
public function __construct($message = '', $code = 0, Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
}
}

View File

@ -88,7 +88,7 @@ class Permissions
if (!auth()->check() && getURLPath() == slashes(base_url().'/index.php')) {
redirect_legacy(base_url().'/');
$result = false;
throw new \App\Exceptions\LegacyExitException();
throw new \LegacyExitException();
} else {
if (!empty(self::$permissions)) {
foreach (self::$permissions as $module) {

View File

@ -180,7 +180,7 @@ class Prints
echo '
<p align="center">'.$error.'</p>';
throw new \App\Exceptions\LegacyExitException();
throw new \LegacyExitException();
}
if (self::isCompletelyCustom($print)) {

60
src/ServiceProvider.php Normal file
View File

@ -0,0 +1,60 @@
<?php
use Illuminate\Support\ServiceProvider as BaseProvider;
class ServiceProvider extends BaseProvider
{
/**
* Perform post-registration booting of services.
*
* @return void
*/
public function boot(): void
{
$this->loadRoutesFrom(__DIR__.'/../routes.php');
// Publishing is only necessary when using the CLI.
if ($this->app->runningInConsole()) {
$this->bootForConsole();
}
}
/**
* Register any package services.
*
* @return void
*/
public function register(): void
{
// Register the service the package provides.
$this->app->singleton('legacy', function ($app) {
return new \AppLegacy();
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return ['legacy'];
}
/**
* Console-specific booting.
*
* @return void
*/
protected function bootForConsole(): void
{
// Publishing assets.
$this->publishes([
__DIR__.'/../assets' => public_path('vendor/devcode-it'),
], 'causali-trasporto');
// Registering package commands.
// $this->commands([]);
}
}