-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgestionale-portal.php
More file actions
532 lines (487 loc) · 23.4 KB
/
Copy pathgestionale-portal.php
File metadata and controls
532 lines (487 loc) · 23.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
<?php
/*
Plugin Name: Gestionale Start Portal
Description: Pagina di avvio con login, registrazione con approvazione admin, e dashboard a pulsanti per la suite Gestionale.
Version: 2.0
Author: Tu
*/
if (!defined('ABSPATH')) exit;
// ============================
// ENQUEUE ASSETS
// ============================
function gsp_enqueue_assets() {
wp_enqueue_style('gsp-portal-style', plugins_url('portal-style.css', __FILE__), [], time());
wp_enqueue_script('gsp-portal-script', plugins_url('portal-script.js', __FILE__), ['jquery'], time(), true);
wp_localize_script('gsp-portal-script', 'gspAjax', [
'ajaxurl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('gsp_register_nonce')
]);
}
add_action('wp_enqueue_scripts', 'gsp_enqueue_assets');
// ============================
// PORTAL SHORTCODE
// ============================
function gsp_portal_shortcode() {
ob_start();
if (!is_user_logged_in()) {
gsp_render_access_view();
} else {
$user_id = get_current_user_id();
// Controlla se l'account è in attesa di approvazione
if (get_user_meta($user_id, 'gsp_pending_approval', true) == '1') {
gsp_render_pending_view();
} else {
gsp_render_dashboard_view();
}
}
return ob_get_clean();
}
add_shortcode('gestionale_portal', 'gsp_portal_shortcode');
// ============================
// VIEW: LOGIN + REGISTRAZIONE (con Tab)
// ============================
function gsp_render_access_view() {
$login_error = '';
$reg_success = '';
$reg_error = '';
$active_tab = isset($_GET['tab']) && $_GET['tab'] === 'register' ? 'register' : 'login';
// Gestione errore login da WordPress
if (isset($_GET['login']) && $_GET['login'] === 'failed') {
$login_error = 'Nome utente o password non corretti.';
if (isset($_GET['reason'])) {
$login_error .= ' (Dettaglio: ' . esc_html(urldecode($_GET['reason'])) . ')';
}
}
// Messaggio di successo registrazione
if (isset($_GET['registered']) && $_GET['registered'] === '1') {
$reg_success = 'Registrazione completata con successo! Ora puoi effettuare il login e accedere.';
$active_tab = 'login';
}
if (isset($_GET['reg_error'])) {
$reg_error = esc_html(urldecode($_GET['reg_error']));
$active_tab = 'register';
}
?>
<div class="portal-body">
<div class="portal-wrapper portal-wrapper--narrow">
<div class="portal-header">
<h1>Gestionale Suite</h1>
<p>Accedi al sistema o richiedi la registrazione.</p>
</div>
<?php if ($login_error): ?>
<div class="portal-alert portal-alert--error"><?php echo $login_error; ?></div>
<?php endif; ?>
<?php if ($reg_success): ?>
<div class="portal-alert portal-alert--success"><?php echo $reg_success; ?></div>
<?php endif; ?>
<?php if ($reg_error): ?>
<div class="portal-alert portal-alert--error"><?php echo $reg_error; ?></div>
<?php endif; ?>
<div class="portal-card">
<!-- TAB HEADER -->
<div class="portal-tabs">
<button type="button" class="portal-tab <?php echo $active_tab === 'login' ? 'active' : ''; ?>" data-tab="login">Accedi</button>
<button type="button" class="portal-tab <?php echo $active_tab === 'register' ? 'active' : ''; ?>" data-tab="register">Registrati</button>
</div>
<!-- TAB: LOGIN -->
<div class="portal-tab-content <?php echo $active_tab === 'login' ? 'active' : ''; ?>" id="tab-login">
<form id="loginform-custom" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" method="post">
<input type="hidden" name="action" value="gsp_login_user">
<?php // In case cache complains, we just include the nonce but won't strictly enforce if not needed ?>
<?php wp_nonce_field('gsp_login_action', 'gsp_log_nonce'); ?>
<div class="portal-field">
<label for="user_login">Nome Utente o Email</label>
<input type="text" name="log" id="user_login" required placeholder="Il tuo nome utente" autocomplete="off">
</div>
<div class="portal-field">
<label for="user_pass">Password</label>
<input type="password" name="pwd" id="user_pass" required placeholder="La tua password" autocomplete="new-password">
</div>
<div style="margin-top:-6px; margin-bottom:14px;">
<label style="font-size:0.85rem; color:var(--text-secondary); cursor:pointer;">
<input name="rememberme" type="checkbox" id="rememberme" value="forever"> Ricordami
</label>
</div>
<input type="hidden" name="redirect_to" value="<?php echo esc_url(get_permalink()); ?>">
<button type="submit" name="wp-submit" id="wp-submit" class="portal-submit-btn">Accedi</button>
</form>
</div>
<!-- TAB: REGISTRAZIONE -->
<div class="portal-tab-content <?php echo $active_tab === 'register' ? 'active' : ''; ?>" id="tab-register">
<form id="gsp-register-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
<input type="hidden" name="action" value="gsp_register_user">
<input type="hidden" name="redirect_to" value="<?php echo esc_url(get_permalink()); ?>">
<?php wp_nonce_field('gsp_register_action', 'gsp_reg_nonce'); ?>
<div class="portal-row">
<div class="portal-field">
<label for="reg_firstname">Nome *</label>
<input type="text" id="reg_firstname" name="reg_firstname" required placeholder="Il tuo nome">
</div>
<div class="portal-field">
<label for="reg_lastname">Cognome *</label>
<input type="text" id="reg_lastname" name="reg_lastname" required placeholder="Il tuo cognome">
</div>
</div>
<div class="portal-field">
<label for="reg_email">Email *</label>
<input type="email" id="reg_email" name="reg_email" required placeholder="email@esempio.it">
</div>
<div class="portal-field">
<label for="reg_username">Nome Utente *</label>
<input type="text" id="reg_username" name="reg_username" required placeholder="Scegli un nome utente">
</div>
<div class="portal-row">
<div class="portal-field">
<label for="reg_password">Password *</label>
<input type="password" id="reg_password" name="reg_password" required placeholder="Minimo 8 caratteri">
</div>
<div class="portal-field">
<label for="reg_password2">Conferma Password *</label>
<input type="password" id="reg_password2" name="reg_password2" required placeholder="Ripeti la password">
</div>
</div>
<button type="submit" class="portal-submit-btn">Registrati</button>
<p class="portal-note">Registrandoti potrai accedere immediatamente alle applicazioni dedicate agli utenti.</p>
</form>
</div>
</div>
</div>
</div>
</div>
<script>
document.addEventListener("DOMContentLoaded", function() {
var tabs = document.querySelectorAll('.portal-tab');
var panes = document.querySelectorAll('.portal-tab-content');
// Cambio tab interattivo
tabs.forEach(function(tab) {
tab.addEventListener('click', function(e) {
e.preventDefault();
var target = this.getAttribute('data-tab');
tabs.forEach(function(t) { t.classList.remove('active'); });
this.classList.add('active');
panes.forEach(function(pane) {
if (pane.id === 'tab-' + target) {
pane.classList.add('active');
} else {
pane.classList.remove('active');
}
});
});
});
// Validazione password live
var regForm = document.getElementById('gsp-register-form');
var pass1 = document.getElementById('reg_password');
var pass2 = document.getElementById('reg_password2');
if (regForm && pass1 && pass2) {
regForm.addEventListener('submit', function(e) {
if (pass1.value !== pass2.value) {
e.preventDefault();
pass2.style.borderColor = '#dc2626';
if (!document.getElementById('gsp-pass-error')) {
var msg = document.createElement('p');
msg.id = 'gsp-pass-error';
msg.style.cssText = 'color:#dc2626; font-size:0.82rem; margin-top:4px;';
msg.textContent = 'Le password non coincidono.';
pass2.parentNode.appendChild(msg);
}
}
});
pass2.addEventListener('input', function() {
var err = document.getElementById('gsp-pass-error');
if (err) err.remove();
pass2.style.borderColor = '';
});
}
});
</script>
<?php
}
// ============================
// HANDLER: PROCESS LOGIN
// ============================
add_action('admin_post_nopriv_gsp_login_user', 'gsp_handle_login');
add_action('admin_post_gsp_login_user', 'gsp_handle_login');
function gsp_handle_login() {
$redirect_base = isset($_POST['redirect_to']) ? esc_url_raw($_POST['redirect_to']) : home_url();
$login = $_POST['log'] ?? '';
$pass = $_POST['pwd'] ?? '';
$remember = isset($_POST['rememberme']);
if (empty($login) || empty($pass)) {
wp_redirect(add_query_arg(['tab' => 'login', 'login' => 'failed', 'reason' => urlencode('Dati vuoti')], $redirect_base));
exit;
}
// 1. Troviamo l'utente (tramite Nome Utente oppure Email)
$user = get_user_by('login', $login);
if (!$user) {
$user = get_user_by('email', $login);
}
if (!$user) {
wp_redirect(add_query_arg(['tab' => 'login', 'login' => 'failed', 'reason' => urlencode('Utente inesistente')], $redirect_base));
exit;
}
// 2. Controlliamo se la password corrisponde
if (!wp_check_password($pass, $user->user_pass, $user->ID)) {
wp_redirect(add_query_arg(['tab' => 'login', 'login' => 'failed', 'reason' => urlencode('Password errata')], $redirect_base));
exit;
}
// 3. Forziamo il Login (Bypass completo del CAPTCHA Altervista)
wp_clear_auth_cookie();
wp_set_current_user($user->ID, $user->user_login);
wp_set_auth_cookie($user->ID, $remember);
do_action('wp_login', $user->user_login, $user);
// Successo
wp_redirect($redirect_base);
exit;
}
// ============================
// HANDLER: PROCESS REGISTRAZIONE
// ============================
add_action('admin_post_nopriv_gsp_register_user', 'gsp_handle_registration');
add_action('admin_post_gsp_register_user', 'gsp_handle_registration');
// Creazione Ruolo "Visitatore" se non esiste
add_action('init', 'gsp_register_custom_roles');
function gsp_register_custom_roles() {
if (!get_role('visitatore')) {
add_role('visitatore', 'Visitatore', ['read' => true]);
}
}
function gsp_handle_registration() {
$redirect_base = isset($_POST['redirect_to']) ? esc_url_raw($_POST['redirect_to']) : home_url();
// Verifica disattivata per compatibilità con la Cache di sistema (es. Altervista)
// Se la pagina viene cachata, il nonce scade e blocca le registrazioni legittime.
/*
if (!isset($_POST['gsp_reg_nonce']) || !wp_verify_nonce($_POST['gsp_reg_nonce'], 'gsp_register_action')) {
wp_redirect(add_query_arg(['tab' => 'register', 'reg_error' => urlencode('Richiesta non valida (Errore sicurezza cache).')], $redirect_base));
exit;
}
*/
$username = sanitize_user($_POST['reg_username']);
$email = sanitize_email($_POST['reg_email']);
$password = $_POST['reg_password'];
$password2 = $_POST['reg_password2'];
$firstname = sanitize_text_field($_POST['reg_firstname']);
$lastname = sanitize_text_field($_POST['reg_lastname']);
// Validazioni
if (empty($username) || empty($email) || empty($password)) {
wp_redirect(add_query_arg(['tab' => 'register', 'reg_error' => urlencode('Compila tutti i campi obbligatori.')], $redirect_base));
exit;
}
if ($password !== $password2) {
wp_redirect(add_query_arg(['tab' => 'register', 'reg_error' => urlencode('Le password non coincidono.')], $redirect_base));
exit;
}
if (strlen($password) < 8) {
wp_redirect(add_query_arg(['tab' => 'register', 'reg_error' => urlencode('La password deve essere di almeno 8 caratteri.')], $redirect_base));
exit;
}
if (username_exists($username)) {
wp_redirect(add_query_arg(['tab' => 'register', 'reg_error' => urlencode('Nome utente già in uso.')], $redirect_base));
exit;
}
if (email_exists($email)) {
wp_redirect(add_query_arg(['tab' => 'register', 'reg_error' => urlencode('Email già registrata.')], $redirect_base));
exit;
}
// Crea l'utente con ruolo Visitatore
$user_id = wp_create_user($username, $password, $email);
if (is_wp_error($user_id)) {
wp_redirect(add_query_arg(['tab' => 'register', 'reg_error' => urlencode($user_id->get_error_message())], $redirect_base));
exit;
}
// Assegna il ruolo specifico 'visitatore'
wp_update_user(['ID' => $user_id, 'first_name' => $firstname, 'last_name' => $lastname, 'role' => 'visitatore']);
// Per ora il login è immediato. Se si vorrà bloccarlo, basterà scommentare la riga sotto:
// update_user_meta($user_id, 'gsp_pending_approval', '1');
// Notifica l'amministratore via email
$admin_email = get_option('admin_email');
wp_mail(
$admin_email,
'[Gestionale] Nuova registrazione visitatore: ' . $username,
"L'utente {$firstname} {$lastname} ({$email}) si è registrato come Visitatore al portale."
);
wp_redirect(add_query_arg('registered', '1', $redirect_base));
exit;
}
// ============================
// VIEW: IN ATTESA DI APPROVAZIONE
// ============================
function gsp_render_pending_view() {
?>
<div class="portal-body">
<div class="portal-wrapper portal-wrapper--narrow">
<div class="portal-header">
<h1>Richiesta Ricevuta</h1>
</div>
<div class="portal-card" style="text-align:center; padding: 40px;">
<div style="font-size: 3rem; margin-bottom: 20px;">⏳</div>
<h2 style="margin-bottom: 12px;">Account in attesa di approvazione</h2>
<p style="color: #64748b;">La tua richiesta è stata inviata all'amministratore. Riceverai una notifica via email quando il tuo account sarà attivato.</p>
<div style="margin-top: 30px;">
<a href="<?php echo wp_logout_url(get_permalink()); ?>" style="color: #64748b; font-size: 0.9rem; text-decoration:none;">Esci</a>
</div>
</div>
</div>
</div>
<?php
}
// ============================
// VIEW: DASHBOARD
// ============================
function gsp_render_dashboard_view() {
$current_user = wp_get_current_user();
$is_admin = current_user_can('manage_options');
$apps = [
[
'title' => 'Area Pubblica',
'desc' => 'Sfoglia le pagine pubbliche del sito.',
'icon' => '🌐',
'url' => home_url(),
'admin' => false
],
[
'title' => 'Analytics Pro',
'desc' => 'Analisi dati e reportistica avanzata.',
'icon' => '📊',
'url' => admin_url('admin.php?page=gap-analytics'),
'admin' => true
],
[
'title' => 'Query Studio',
'desc' => 'Creazione e gestione query SQL visive.',
'icon' => '🔍',
'url' => admin_url('admin.php?page=gqs-studio'),
'admin' => true
],
[
'title' => 'SQL Bridge',
'desc' => 'Importazione ed esportazione dati.',
'icon' => '🌉',
'url' => admin_url('admin.php?page=gs-bridge'),
'admin' => true
],
[
'title' => 'Query Manager',
'desc' => 'Gestione delle query salvate e report.',
'icon' => '🗂️',
'url' => admin_url('admin.php?page=gq-manager'),
'admin' => true
],
[
'title' => 'Logistica',
'desc' => 'Gestione magazzino e movimenti merci.',
'icon' => '📦',
'url' => admin_url('admin.php?page=gl-crud-admin'),
'admin' => false
],
[
'title' => 'Log. Inserimento',
'desc' => 'Inserimento di nuovi record in tutte le tabelle.',
'icon' => '➕',
'url' => admin_url('admin.php?page=glpi-admin'),
'admin' => true
],
[
'title' => 'Il mio Profilo',
'desc' => 'Gestisci il tuo account e le preferenze.',
'icon' => '👤',
'url' => admin_url('profile.php'),
'admin' => false
],
];
?>
<div class="portal-body">
<div class="portal-wrapper">
<div class="portal-header">
<h1>Benvenuto, <?php echo esc_html($current_user->display_name); ?></h1>
<p>Seleziona lo strumento che desideri utilizzare.</p>
<div style="margin-top: 12px;">
<a href="<?php echo wp_logout_url(get_permalink()); ?>" class="portal-logout-link">Esci dal sistema</a>
</div>
</div>
<div class="portal-grid">
<?php foreach ($apps as $app):
if ($app['admin'] && !$is_admin) continue;
?>
<a href="<?php echo esc_url($app['url']); ?>" class="portal-btn-card">
<div class="portal-icon-box"><?php echo $app['icon']; ?></div>
<div class="portal-info-box">
<h3><?php echo esc_html($app['title']); ?></h3>
<p><?php echo esc_html($app['desc']); ?></p>
</div>
</a>
<?php endforeach; ?>
</div>
</div>
</div>
<?php
}
// ============================
// ADMIN: PANNELLO UTENTI IN ATTESA
// ============================
add_action('admin_menu', 'gsp_admin_pending_menu');
function gsp_admin_pending_menu() {
add_users_page(
'Richieste di Accesso',
'Richieste Accesso',
'manage_options',
'gsp-pending-users',
'gsp_render_pending_admin'
);
}
function gsp_render_pending_admin() {
// Gestisci approvazione / rifiuto
if (isset($_GET['gsp_action'], $_GET['user_id'], $_GET['_wpnonce'])) {
$user_id = intval($_GET['user_id']);
if (wp_verify_nonce($_GET['_wpnonce'], 'gsp_action_' . $user_id)) {
if ($_GET['gsp_action'] === 'approve') {
delete_user_meta($user_id, 'gsp_pending_approval');
$user = get_userdata($user_id);
wp_mail($user->user_email, 'Accesso approvato - Gestionale Suite',
"Il tuo account è stato approvato. Puoi ora accedere al portale.\n\n" . home_url());
echo '<div class="updated notice"><p>Utente <strong>' . esc_html($user->user_login) . '</strong> approvato.</p></div>';
} elseif ($_GET['gsp_action'] === 'reject') {
$user = get_userdata($user_id);
wp_mail($user->user_email, 'Richiesta di accesso - Gestionale Suite',
"La tua richiesta di accesso non è stata approvata. Contatta l'amministratore per maggiori informazioni.");
wp_delete_user($user_id);
echo '<div class="updated notice"><p>Richiesta rifiutata e utente eliminato.</p></div>';
}
}
}
// Lista utenti in attesa
$pending = get_users(['meta_key' => 'gsp_pending_approval', 'meta_value' => '1']);
echo '<div class="wrap"><h1>Richieste di Accesso in Attesa</h1>';
if (empty($pending)) {
echo '<p>Nessuna richiesta in attesa.</p>';
} else {
echo '<table class="wp-list-table widefat fixed striped" style="margin-top:20px;"><thead><tr><th>Nome</th><th>Username</th><th>Email</th><th>Azioni</th></tr></thead><tbody>';
foreach ($pending as $u) {
$approve_url = wp_nonce_url(add_query_arg(['page' => 'gsp-pending-users', 'gsp_action' => 'approve', 'user_id' => $u->ID], admin_url('users.php')), 'gsp_action_' . $u->ID);
$reject_url = wp_nonce_url(add_query_arg(['page' => 'gsp-pending-users', 'gsp_action' => 'reject', 'user_id' => $u->ID], admin_url('users.php')), 'gsp_action_' . $u->ID);
echo "<tr>
<td>{$u->first_name} {$u->last_name}</td>
<td><strong>{$u->user_login}</strong></td>
<td>{$u->user_email}</td>
<td>
<a href='" . esc_url($approve_url) . "' class='button button-primary'>✅ Approva</a>
<a href='" . esc_url($reject_url) . "' class='button' onclick=\"return confirm('Eliminare questo utente?');\">❌ Rifiuta</a>
</td>
</tr>";
}
echo '</tbody></table>';
}
echo '</div>';
}
// Contatore badge nel menu admin
add_action('admin_menu', 'gsp_pending_badge');
function gsp_pending_badge() {
global $menu;
$count = count(get_users(['meta_key' => 'gsp_pending_approval', 'meta_value' => '1']));
if ($count > 0) {
foreach ($menu as $key => $item) {
if (isset($item[2]) && $item[2] === 'users.php') {
$menu[$key][0] .= ' <span class="update-plugins count-' . $count . '"><span class="plugin-count">' . $count . '</span></span>';
}
}
}
}