Initial Upload

This commit is contained in:
friloo 2026-04-21 17:45:58 +02:00 committed by GitHub
commit dbdc237fa1
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
22 changed files with 7995 additions and 0 deletions

406
Readme.md Normal file
View file

@ -0,0 +1,406 @@
# UniFi Voucher Management System
Ein professionelles, webbasiertes System zur Verwaltung von WLAN-Vouchers für UniFi Controller mit Multi-Site-Unterstützung, Benutzerverwaltung und Microsoft 365 Integration.
## ✨ Features
### Kern-Funktionen
- 🎫 **Voucher-Erstellung**: Einfache Erstellung von zeitbegrenzten WLAN-Zugangscodes
- 🏢 **Multi-Site-Support**: Verwaltung mehrerer UniFi Sites/Standorte
- 👥 **Benutzerverwaltung**: Granulare Zugriffskontrolle auf Site-Ebene
- 🔐 **Authentifizierung**: Lokale Accounts und Microsoft 365 OAuth
- 📊 **Admin-Dashboard**: Übersichtliche Statistiken und Historie
- 🌐 **Öffentlicher Zugriff**: Optional ohne Login nutzbar
- 🎨 **Modernes Design**: Responsives, helles und professionelles UI
### Sicherheit
- CSRF-Schutz für alle Formulare
- Password-Hashing mit bcrypt
- Session-Management mit konfigurierbaren Timeouts
- SQL-Injection-Schutz durch Prepared Statements
- Rollenbasierte Zugriffskontrolle (Admin/User)
## 📋 Anforderungen
### Server-Anforderungen
- PHP 7.4 oder höher
- MySQL 5.7+ oder MariaDB 10.2+
- Apache/Nginx Webserver
- PHP-Extensions:
- PDO
- PDO_MySQL
- cURL
- mbstring
- JSON
### UniFi Controller
- UniFi Network Controller 6.0 oder höher
- API-Zugriff aktiviert
- Lokaler Admin-Account oder dedizierter API-User
## 🚀 Installation
### Schritt 1: Dateien hochladen
```bash
# Repository klonen oder ZIP herunterladen
git clone https://github.com/ihr-username/unifi-voucher-system.git
cd unifi-voucher-system
# Dateien auf den Webserver hochladen
# Stellen Sie sicher, dass der Webserver-User Schreibrechte hat
```
### Schritt 2: Ordnerstruktur
```
/
├── config.php (wird vom Installer erstellt)
├── install.php
├── index.php
├── login.php
├── logout.php
├── database.sql
├── .htaccess (wird vom Installer erstellt)
├── includes/
│ ├── Database.php
│ ├── Auth.php
│ └── UniFiController.php
└── admin/
├── index.php
├── sites.php
├── users.php
├── vouchers.php
└── settings.php
```
### Schritt 3: Installation durchführen
1. Öffnen Sie `http://ihre-domain.de/install.php` im Browser
2. Folgen Sie dem 5-Schritte-Installations-Assistenten:
#### Schritt 1: Datenbank-Konfiguration
- Datenbank-Host (meist `localhost`)
- Datenbankname (z.B. `unifi_voucher`)
- Datenbank-Benutzer
- Datenbank-Passwort
#### Schritt 2: Administrator-Account
- Name
- E-Mail-Adresse
- Passwort (min. 8 Zeichen)
#### Schritt 3: Allgemeine Einstellungen
- Anwendungs-Titel
- Logo-URL (optional)
- Anleitung für Benutzer
- Öffentlicher Zugriff aktivieren (optional)
#### Schritt 4: Microsoft 365 Integration (optional)
- Client ID
- Client Secret
- Tenant ID
#### Schritt 5: Installation abschließen
Nach erfolgreicher Installation wird automatisch:
- Die Datenbank erstellt und initialisiert
- Die `config.php` Datei generiert
- Die `.htaccess` für URL-Rewriting erstellt
- Der Admin-Account angelegt
### Schritt 4: Installation sichern
Nach erfolgreicher Installation:
```bash
# install.php umbenennen oder löschen
mv install.php install.php.bak
# Oder komplett entfernen
rm install.php
```
## 🎯 Erste Schritte
### 1. Als Administrator anmelden
- Öffnen Sie `http://ihre-domain.de/login.php`
- Melden Sie sich mit Ihren Admin-Zugangsdaten an
### 2. Sites konfigurieren
1. Navigieren Sie zu **Administration** → **Sites verwalten**
2. Klicken Sie auf **Neue Site hinzufügen**
3. Geben Sie folgende Daten ein:
- **Name**: Anzeigename (z.B. "Hauptgebäude")
- **Site ID**: UniFi Site ID (z.B. "default")
- **Controller URL**: URL Ihres UniFi Controllers (z.B. "https://unifi.example.com:8443")
- **Benutzername**: UniFi Admin-Username
- **Passwort**: UniFi Admin-Passwort
- **Öffentlicher Zugriff**: Aktivieren für Login-freie Nutzung
4. Klicken Sie auf **Verbindung testen**, um die Einstellungen zu überprüfen
5. Speichern Sie die Site
### 3. Benutzer anlegen
1. Navigieren Sie zu **Administration** → **Benutzer verwalten**
2. Klicken Sie auf **Neuer Benutzer**
3. Geben Sie die Benutzerdaten ein:
- Name
- E-Mail
- Passwort
- Admin-Rechte (optional)
4. Wählen Sie die Sites aus, auf die der Benutzer Zugriff haben soll
5. Speichern Sie den Benutzer
### 4. Vouchers erstellen
1. Gehen Sie zur Startseite
2. Wählen Sie eine Site aus
3. Geben Sie einen Voucher-Namen ein
4. Legen Sie die Anzahl der Geräte fest (1-10)
5. Klicken Sie auf **Voucher erstellen**
6. Der Code wird sofort angezeigt und ist 8 Stunden gültig
## 🔧 Konfiguration
### config.php
Die Datei wird automatisch erstellt, kann aber manuell angepasst werden:
```php
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'unifi_voucher');
define('DB_USER', 'username');
define('DB_PASS', 'password');
define('SESSION_LIFETIME', 3600); // 1 Stunde
date_default_timezone_set('Europe/Berlin');
```
### Microsoft 365 OAuth einrichten
1. **Azure AD App registrieren**:
- Gehen Sie zu https://portal.azure.com
- Navigieren Sie zu "Azure Active Directory" → "App-Registrierungen"
- Klicken Sie auf "Neue Registrierung"
- Name: "UniFi Voucher System"
- Unterstützte Kontotypen: "Nur Konten in diesem Organisationsverzeichnis"
- Umleitungs-URI: `https://ihre-domain.de/login.php`
2. **API-Berechtigungen**:
- Microsoft Graph → Delegierte Berechtigungen
- `User.Read`
- `email`
- `profile`
- `openid`
3. **Client Secret erstellen**:
- Gehen Sie zu "Zertifikate & Geheimnisse"
- Erstellen Sie ein neues Client-Geheimnis
- Notieren Sie den Wert (nur einmal sichtbar!)
4. **In System eintragen**:
- Administration → Einstellungen
- Microsoft 365 Bereich ausfüllen
- Client ID, Client Secret und Tenant ID eintragen
## 🔐 Sicherheitsempfehlungen
### Server-Konfiguration
```apache
# .htaccess zusätzliche Sicherheit
<Files "config.php">
Order Allow,Deny
Deny from all
</Files>
<FilesMatch "\.(sql|md)$">
Order Allow,Deny
Deny from all
</FilesMatch>
```
### Datenbank-Benutzer
Erstellen Sie einen dedizierten Datenbankbenutzer nur für diese Anwendung:
```sql
CREATE USER 'unifi_voucher'@'localhost' IDENTIFIED BY 'sicheres_passwort';
GRANT SELECT, INSERT, UPDATE, DELETE ON unifi_voucher.* TO 'unifi_voucher'@'localhost';
FLUSH PRIVILEGES;
```
### HTTPS erzwingen
```apache
# In .htaccess hinzufügen
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
```
### Regelmäßige Updates
- PHP und MySQL aktuell halten
- Sicherheitspatches zeitnah einspielen
- Passwörter regelmäßig ändern
## 📚 Verwendung
### Für Endbenutzer
**Voucher erstellen:**
1. Startseite öffnen (Login optional je nach Konfiguration)
2. Voucher-Name eingeben
3. Anzahl Geräte wählen
4. Standort auswählen
5. Code erstellen und notieren
**Code verwenden:**
1. Mit dem WLAN verbinden
2. Browser öffnet automatisch Anmeldeseite
3. Voucher-Code eingeben
4. Zugang für 8 Stunden
### Für Administratoren
**Sites verwalten:**
- Neue Standorte hinzufügen
- Verbindungen testen
- Sites deaktivieren
- Zugangsdaten aktualisieren
**Benutzer verwalten:**
- Neue Benutzer anlegen
- Berechtigungen zuweisen
- Sites-Zugriff konfigurieren
- Admin-Rechte vergeben
**Historie einsehen:**
- Alle erstellten Vouchers
- Filterfunktionen nach Site/Benutzer/Datum
- Export-Funktion (optional)
## 🐛 Problembehandlung
### Häufige Probleme
**Login funktioniert nicht:**
- Prüfen Sie die Datenbankverbindung
- Stellen Sie sicher, dass Sessions funktionieren
- Überprüfen Sie die PHP-Session-Konfiguration
**UniFi-Verbindung schlägt fehl:**
- Testen Sie die Controller-URL im Browser
- Prüfen Sie Benutzername und Passwort
- Stellen Sie sicher, dass cURL aktiviert ist
- Prüfen Sie SSL-Zertifikate (CURLOPT_SSL_VERIFYPEER)
**Voucher werden nicht erstellt:**
- Überprüfen Sie die UniFi Controller Logs
- Prüfen Sie API-Berechtigungen
- Stellen Sie sicher, dass die Site-ID korrekt ist
**Microsoft 365 Login funktioniert nicht:**
- Prüfen Sie die Redirect URI
- Überprüfen Sie Client ID und Secret
- Stellen Sie sicher, dass API-Berechtigungen erteilt wurden
### Debugging aktivieren
In `config.php` hinzufügen:
```php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', '/pfad/zu/error.log');
```
## 🔄 Update/Migration
### Von der alten Version migrieren
Das System ist eine komplette Neuentwicklung. Migration erfordert:
1. **Daten-Export** aus dem alten System (falls vorhanden)
2. **Neue Installation** gemäß dieser Anleitung durchführen
3. **Sites manuell neu anlegen**
4. **Benutzer neu erstellen**
### Updates einspielen
```bash
# Backup erstellen
mysqldump -u username -p database_name > backup.sql
cp -r /var/www/html/voucher /backup/voucher-$(date +%Y%m%d)
# Neue Dateien hochladen (config.php nicht überschreiben!)
# Datenbank-Updates ausführen falls vorhanden
```
## 📝 API-Dokumentation
### UniFi Controller API Endpoints
**Login:**
```
POST /api/login
Body: {"username": "admin", "password": "password"}
```
**Voucher erstellen:**
```
POST /api/s/{site_id}/cmd/hotspot
Body: {
"cmd": "create-voucher",
"expire": 480,
"n": 1,
"note": "Voucher Name",
"quota": 1
}
```
**Vouchers abrufen:**
```
GET /api/s/{site_id}/stat/voucher
```
## 🤝 Mitwirken
Contributions sind willkommen! Bitte:
1. Forken Sie das Repository
2. Erstellen Sie einen Feature-Branch (`git checkout -b feature/AmazingFeature`)
3. Committen Sie Ihre Änderungen (`git commit -m 'Add some AmazingFeature'`)
4. Pushen Sie den Branch (`git push origin feature/AmazingFeature`)
5. Öffnen Sie einen Pull Request
## 📄 Lizenz
Dieses Projekt steht unter der MIT-Lizenz. Siehe `LICENSE` Datei für Details.
## 👨‍💻 Autor
**Friederich Loheide**
## 🙏 Danksagungen
- UniFi Controller API Dokumentation
- Microsoft Graph API
- Bootstrap und FontAwesome Icons
## 📞 Support
Bei Fragen oder Problemen:
- Erstellen Sie ein Issue auf GitHub
- E-Mail an support@example.com
## 🗺️ Roadmap
Geplante Features:
- [ ] Voucher-Templates
- [ ] Bulk-Voucher-Erstellung
- [ ] QR-Code-Generierung
- [ ] SMS-Versand von Codes
- [ ] Erweiterte Reporting-Funktionen
- [ ] REST API für externe Integration
- [ ] Docker-Container
- [ ] Mehrsprachigkeit
---
**Version:** 2.0.0
**Letztes Update:** Januar 2026

1027
admin/index.php Normal file

File diff suppressed because it is too large Load diff

799
admin/settings.php Normal file
View file

@ -0,0 +1,799 @@
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/Database.php';
require_once __DIR__ . '/../includes/Auth.php';
$auth = new Auth();
$auth->requireAdmin();
$db = Database::getInstance();
$appTitle = $db->getSetting('app_title', 'UniFi Voucher System');
$error = '';
$success = '';
// Einstellungen speichern
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_settings'])) {
if (!$auth->validateCsrfToken($_POST['csrf_token'] ?? '')) {
$error = 'Ungültiges Sicherheits-Token';
} else {
try {
$settings = [];
$formType = $_POST['form_type'] ?? '';
// Allgemeine Einstellungen
if ($formType === 'general') {
$settings['app_title'] = trim($_POST['app_title'] ?? '');
$settings['logo_url'] = trim($_POST['logo_url'] ?? '');
$settings['favicon_url'] = trim($_POST['favicon_url'] ?? '');
$settings['instruction_header'] = trim($_POST['instruction_header'] ?? '');
$settings['instruction_text'] = $_POST['instruction_text'] ?? '';
$settings['public_access'] = isset($_POST['public_access']) ? '1' : '0';
}
// M365 Einstellungen
if ($formType === 'm365') {
$settings['m365_client_id'] = trim($_POST['m365_client_id'] ?? '');
$settings['m365_client_secret'] = trim($_POST['m365_client_secret'] ?? '');
$settings['m365_tenant_id'] = trim($_POST['m365_tenant_id'] ?? '');
}
// SMTP Einstellungen
if ($formType === 'smtp') {
$settings['smtp_enabled'] = isset($_POST['smtp_enabled']) ? '1' : '0';
$settings['smtp_host'] = trim($_POST['smtp_host'] ?? '');
$settings['smtp_port'] = trim($_POST['smtp_port'] ?? '587');
$settings['smtp_username'] = trim($_POST['smtp_username'] ?? '');
if (!empty($_POST['smtp_password'])) {
$settings['smtp_password'] = trim($_POST['smtp_password']);
}
$settings['smtp_encryption'] = trim($_POST['smtp_encryption'] ?? 'tls');
$settings['smtp_from_email'] = trim($_POST['smtp_from_email'] ?? '');
$settings['smtp_from_name'] = trim($_POST['smtp_from_name'] ?? '');
}
// E-Mail Templates
if ($formType === 'templates') {
$settings['email_voucher_subject'] = trim($_POST['email_voucher_subject'] ?? '');
$settings['email_voucher_body'] = $_POST['email_voucher_body'] ?? '';
$settings['email_user_notification_subject'] = trim($_POST['email_user_notification_subject'] ?? '');
$settings['email_user_notification_body'] = $_POST['email_user_notification_body'] ?? '';
$settings['system_url'] = trim($_POST['system_url'] ?? '');
}
// System Einstellungen
if ($formType === 'system') {
$settings['tinymce_api_key'] = trim($_POST['tinymce_api_key'] ?? '');
$settings['print_template'] = $_POST['print_template'] ?? '';
}
foreach ($settings as $key => $value) {
$db->setSetting($key, $value);
}
$success = 'Einstellungen erfolgreich gespeichert!';
} catch (Exception $e) {
$error = 'Fehler: ' . $e->getMessage();
}
}
}
// Cron-Token generieren
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['generate_cron_token'])) {
if (!$auth->validateCsrfToken($_POST['csrf_token'] ?? '')) {
$error = 'Ungültiges Sicherheits-Token';
} else {
try {
// Sicheren Token generieren
$newToken = bin2hex(random_bytes(32));
$db->setSetting('cron_token', $newToken);
$success = 'Neuer Cron-Token wurde generiert!';
} catch (Exception $e) {
$error = 'Fehler: ' . $e->getMessage();
}
}
}
// Cron-Token löschen
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_cron_token'])) {
if (!$auth->validateCsrfToken($_POST['csrf_token'] ?? '')) {
$error = 'Ungültiges Sicherheits-Token';
} else {
try {
$db->setSetting('cron_token', '');
$success = 'Cron-Token wurde gelöscht!';
} catch (Exception $e) {
$error = 'Fehler: ' . $e->getMessage();
}
}
}
// Passwort ändern
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['change_password'])) {
if (!$auth->validateCsrfToken($_POST['csrf_token'] ?? '')) {
$error = 'Ungültiges Sicherheits-Token';
} else {
try {
$currentPassword = $_POST['current_password'];
$newPassword = $_POST['new_password'];
$confirmPassword = $_POST['confirm_password'];
$user = $auth->getCurrentUser();
if (!password_verify($currentPassword, $user['password_hash'])) {
throw new Exception('Aktuelles Passwort ist falsch');
}
if (strlen($newPassword) < 8) {
throw new Exception('Neues Passwort muss mindestens 8 Zeichen lang sein');
}
if ($newPassword !== $confirmPassword) {
throw new Exception('Passwörter stimmen nicht überein');
}
$newHash = password_hash($newPassword, PASSWORD_DEFAULT);
$db->query("UPDATE users SET password_hash = ? WHERE id = ?", [$newHash, $user['id']]);
$success = 'Passwort erfolgreich geändert!';
} catch (Exception $e) {
$error = $e->getMessage();
}
}
}
// Aktuelle Einstellungen laden
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'];
$scriptPath = dirname($_SERVER['SCRIPT_NAME'], 2);
$scriptPath = $scriptPath === '/' ? '' : $scriptPath;
$autoDetectedUrl = $protocol . '://' . $host . $scriptPath;
$currentSettings = [
'app_title' => $db->getSetting('app_title', 'UniFi Voucher System'),
'logo_url' => $db->getSetting('logo_url', ''),
'favicon_url' => $db->getSetting('favicon_url', ''),
'instruction_header' => $db->getSetting('instruction_header', 'So verwenden Sie Ihren Code'),
'instruction_text' => $db->getSetting('instruction_text', 'Verbinden Sie sich mit dem WLAN und geben Sie den Code ein.'),
'public_access' => $db->getSetting('public_access', '0'),
'm365_client_id' => $db->getSetting('m365_client_id', ''),
'm365_client_secret' => $db->getSetting('m365_client_secret', ''),
'm365_tenant_id' => $db->getSetting('m365_tenant_id', ''),
'smtp_enabled' => $db->getSetting('smtp_enabled', '0'),
'smtp_host' => $db->getSetting('smtp_host', ''),
'smtp_port' => $db->getSetting('smtp_port', '587'),
'smtp_username' => $db->getSetting('smtp_username', ''),
'smtp_password' => $db->getSetting('smtp_password', ''),
'smtp_encryption' => $db->getSetting('smtp_encryption', 'tls'),
'smtp_from_email' => $db->getSetting('smtp_from_email', ''),
'smtp_from_name' => $db->getSetting('smtp_from_name', ''),
'system_url' => $db->getSetting('system_url', $autoDetectedUrl),
'email_voucher_subject' => $db->getSetting('email_voucher_subject', '{APP_TITLE} - Ihr WLAN-Zugang'),
'email_voucher_body' => $db->getSetting('email_voucher_body', "Hallo,\n\nIhr Code: {VOUCHER_CODE}\n\nGültigkeit: 8h\nGeräte: {MAX_USES}\nSite: {SITE_NAME}"),
'email_user_notification_subject' => $db->getSetting('email_user_notification_subject', '{APP_TITLE} - Berechtigungen geändert'),
'email_user_notification_body' => $db->getSetting('email_user_notification_body', "Hallo {USER_NAME},\n\n{CHANGES}"),
'tinymce_api_key' => $db->getSetting('tinymce_api_key', ''),
'print_template' => $db->getSetting('print_template', '<div style="text-align:center;padding:40px"><h1>{APP_TITLE}</h1><h2>WLAN Code</h2><div style="font-size:48px;font-weight:bold;margin:30px 0;font-family:monospace">{VOUCHER_CODE}</div><p><strong>Gültig bis:</strong> {EXPIRY_DATE} {EXPIRY_TIME}</p><p><strong>Site:</strong> {SITE_NAME}</p><p><strong>Geräte:</strong> {MAX_USES}</p><hr style="margin:30px 0"><div>{INSTRUCTIONS}</div></div>'),
'cron_token' => $db->getSetting('cron_token', ''),
'last_cron_sync' => $db->getSetting('last_cron_sync', '')
];
$currentUser = $auth->getCurrentUser();
$faviconUrl = $db->getSetting('favicon_url', '');
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Einstellungen - <?= htmlspecialchars($appTitle) ?></title>
<?php if ($faviconUrl): ?>
<link rel="icon" type="image/x-icon" href="<?= htmlspecialchars($faviconUrl) ?>">
<?php endif; ?>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<!-- TinyMCE -->
<?php if (!empty($currentSettings['tinymce_api_key'])): ?>
<script src="https://cdn.tiny.cloud/1/<?= htmlspecialchars($currentSettings['tinymce_api_key']) ?>/tinymce/6/tinymce.min.js"></script>
<?php else: ?>
<script src="https://cdn.tiny.cloud/1/no-api-key/tinymce/6/tinymce.min.js"></script>
<?php endif; ?>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f7fa; }
.header { background: white; border-bottom: 1px solid #e0e0e0; padding: 0 30px; height: 70px; display: flex; align-items: center; justify-content: space-between; position: sticky; top: 0; z-index: 100; box-shadow: 0 2px 10px rgba(0,0,0,0.05); }
.header-title { font-size: 20px; font-weight: 600; color: #333; }
.sidebar { position: fixed; left: 0; top: 70px; bottom: 0; width: 260px; background: white; border-right: 1px solid #e0e0e0; padding: 30px 0; }
.sidebar-nav { list-style: none; }
.sidebar-nav a { display: flex; align-items: center; gap: 12px; padding: 12px 30px; color: #666; text-decoration: none; transition: all 0.2s; font-size: 15px; }
.sidebar-nav a:hover, .sidebar-nav a.active { background: #f8f9fa; color: #667eea; }
.sidebar-nav i { width: 20px; text-align: center; }
.main-content { margin-left: 260px; padding: 30px; min-height: calc(100vh - 70px); }
.page-header { margin-bottom: 30px; }
.page-title { font-size: 28px; font-weight: 600; color: #333; margin-bottom: 10px; }
.btn { padding: 10px 20px; border-radius: 8px; border: none; font-weight: 500; cursor: pointer; text-decoration: none; display: inline-flex; align-items: center; gap: 8px; transition: all 0.2s; font-size: 14px; }
.btn-primary { background: #667eea; color: white; }
.btn-primary:hover { background: #5568d3; }
.btn-secondary { background: #f8f9fa; color: #666; border: 1px solid #e0e0e0; }
.alert { padding: 14px 20px; border-radius: 10px; margin-bottom: 25px; font-size: 14px; display: flex; align-items: center; gap: 10px; }
.alert-error { background: #fee; border: 1px solid #fcc; color: #c33; }
.alert-success { background: #efe; border: 1px solid #cfc; color: #3c3; }
.tab-container { background: white; border-radius: 15px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); border: 1px solid #e0e0e0; overflow: hidden; }
.tab-navigation { display: flex; background: #f8f9fa; border-bottom: 2px solid #e0e0e0; overflow-x: auto; position: sticky; top: 70px; z-index: 50; }
.tab-button { padding: 18px 25px; background: transparent; border: none; border-bottom: 3px solid transparent; cursor: pointer; font-size: 14px; font-weight: 500; color: #666; transition: all 0.3s; white-space: nowrap; display: flex; align-items: center; gap: 8px; }
.tab-button:hover { background: rgba(102, 126, 234, 0.1); color: #667eea; }
.tab-button.active { color: #667eea; border-bottom-color: #667eea; background: white; }
.tab-content { display: none; padding: 30px; animation: fadeIn 0.3s; }
.tab-content.active { display: block; }
@keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
.form-group { margin-bottom: 20px; }
label { display: block; margin-bottom: 8px; color: #555; font-weight: 500; font-size: 14px; }
input[type="text"], input[type="url"], input[type="password"], input[type="number"], select, textarea { width: 100%; padding: 12px; border: 2px solid #e0e0e0; border-radius: 8px; font-size: 14px; transition: border-color 0.3s; font-family: inherit; }
input:focus, textarea:focus, select:focus { outline: none; border-color: #667eea; }
textarea { resize: vertical; min-height: 100px; }
.checkbox-group { display: flex; align-items: center; gap: 10px; }
.checkbox-group input { width: auto; accent-color: #667eea; }
.help-text { font-size: 12px; color: #999; margin-top: 4px; }
.info-box { background: #e7f3ff; border: 1px solid #b3d9ff; border-radius: 8px; padding: 15px; margin-bottom: 20px; }
.info-box h4 { color: #0066cc; margin-bottom: 8px; font-size: 14px; }
.info-box p { color: #004d99; font-size: 13px; line-height: 1.5; }
.section-divider { border-top: 2px solid #f0f0f0; margin: 30px 0; }
.form-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; }
.placeholder-info { background: #fff9e6; border: 1px solid #ffe066; border-radius: 8px; padding: 15px; margin: 15px 0; }
.placeholder-info h4 { color: #996600; margin-bottom: 8px; font-size: 14px; }
.placeholder-info code { background: #fff; padding: 2px 6px; border-radius: 3px; font-size: 12px; color: #d63384; }
.placeholder-list { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 10px; margin-top: 10px; }
</style>
</head>
<body>
<div class="header">
<div class="header-title"><i class="fas fa-shield-alt"></i> Administration</div>
<a href="../index.php" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> Zurück</a>
</div>
<div class="sidebar">
<nav class="sidebar-nav">
<ul>
<li><a href="index.php"><i class="fas fa-home"></i> Dashboard</a></li>
<li><a href="sites.php"><i class="fas fa-map-marker-alt"></i> Sites verwalten</a></li>
<li><a href="users.php"><i class="fas fa-users"></i> Benutzer verwalten</a></li>
<li><a href="vouchers.php"><i class="fas fa-ticket-alt"></i> Voucher-Historie</a></li>
<li><a href="settings.php" class="active"><i class="fas fa-cog"></i> Einstellungen</a></li>
</ul>
</nav>
</div>
<div class="main-content">
<div class="page-header">
<h1 class="page-title">Einstellungen</h1>
<p style="color: #666; font-size: 14px;">System-Konfiguration und Personalisierung</p>
</div>
<?php if ($error): ?>
<div class="alert alert-error"><i class="fas fa-exclamation-circle"></i><span><?= htmlspecialchars($error) ?></span></div>
<?php endif; ?>
<?php if ($success): ?>
<div class="alert alert-success"><i class="fas fa-check-circle"></i><span><?= htmlspecialchars($success) ?></span></div>
<?php endif; ?>
<div class="tab-container">
<div class="tab-navigation">
<button class="tab-button active" onclick="switchTab('general')"><i class="fas fa-sliders-h"></i> Allgemein</button>
<button class="tab-button" onclick="switchTab('cron')"><i class="fas fa-clock"></i> Cron-Sync</button>
<button class="tab-button" onclick="switchTab('m365')"><i class="fab fa-microsoft"></i> Microsoft 365</button>
<button class="tab-button" onclick="switchTab('smtp')"><i class="fas fa-envelope"></i> SMTP</button>
<button class="tab-button" onclick="switchTab('templates')"><i class="fas fa-file-alt"></i> Templates</button>
<button class="tab-button" onclick="switchTab('system')"><i class="fas fa-cogs"></i> System</button>
<button class="tab-button" onclick="switchTab('password')"><i class="fas fa-key"></i> Passwort</button>
</div>
<!-- TAB: Allgemein -->
<div id="tab-general" class="tab-content active">
<h2 style="margin-bottom: 20px;"><i class="fas fa-sliders-h"></i> Allgemeine Einstellungen</h2>
<form method="post">
<input type="hidden" name="csrf_token" value="<?= $auth->getCsrfToken() ?>">
<input type="hidden" name="form_type" value="general">
<div class="form-group">
<label for="app_title">Anwendungs-Titel *</label>
<input type="text" id="app_title" name="app_title" value="<?= htmlspecialchars($currentSettings['app_title']) ?>" required>
</div>
<div class="form-grid">
<div class="form-group">
<label for="logo_url">Logo-URL</label>
<input type="url" id="logo_url" name="logo_url" value="<?= htmlspecialchars($currentSettings['logo_url']) ?>" placeholder="https://example.com/logo.png">
</div>
<div class="form-group">
<label for="favicon_url">Favicon-URL</label>
<input type="url" id="favicon_url" name="favicon_url" value="<?= htmlspecialchars($currentSettings['favicon_url']) ?>" placeholder="https://example.com/favicon.ico">
<div class="help-text">Icon im Browser-Tab (.ico, .png, .svg)</div>
</div>
</div>
<div class="section-divider"></div>
<div class="form-group">
<label for="instruction_header">Anleitung - Überschrift</label>
<input type="text" id="instruction_header" name="instruction_header" value="<?= htmlspecialchars($currentSettings['instruction_header']) ?>">
</div>
<div class="form-group">
<label for="instruction_text">Anleitung - Text</label>
<textarea id="instruction_text" name="instruction_text" class="tinymce-editor"><?= htmlspecialchars($currentSettings['instruction_text']) ?></textarea>
</div>
<div class="checkbox-group">
<input type="checkbox" id="public_access" name="public_access" <?= $currentSettings['public_access'] == '1' ? 'checked' : '' ?>>
<label for="public_access" style="margin:0;">Öffentlicher Zugriff</label>
</div>
<div style="margin-top: 20px;">
<button type="submit" name="save_settings" class="btn btn-primary"><i class="fas fa-save"></i> Speichern</button>
</div>
</form>
</div>
<!-- TAB: Cron-Sync -->
<div id="tab-cron" class="tab-content">
<h2 style="margin-bottom: 20px;"><i class="fas fa-clock"></i> Automatische Voucher-Synchronisation</h2>
<div class="info-box">
<h4><i class="fas fa-info-circle"></i> Was macht der Cron-Job?</h4>
<p>Der Cron-Job synchronisiert automatisch alle Voucher von Ihren UniFi Controllern in die lokale Datenbank.
Dadurch werden Dashboard und Voucher-Übersicht sofort beim Öffnen angezeigt, ohne auf die API warten zu müssen.</p>
</div>
<div class="section-divider"></div>
<h3 style="margin-bottom: 15px;">Cron-Token</h3>
<?php if (empty($currentSettings['cron_token'])): ?>
<div style="background: #fff3cd; border: 1px solid #ffc107; border-radius: 8px; padding: 20px; margin-bottom: 20px;">
<p style="color: #856404; margin-bottom: 15px;"><i class="fas fa-exclamation-triangle"></i> <strong>Kein Token konfiguriert.</strong> Generieren Sie einen Token, um den Cron-Job zu aktivieren.</p>
<form method="post" style="display: inline;">
<input type="hidden" name="csrf_token" value="<?= $auth->getCsrfToken() ?>">
<button type="submit" name="generate_cron_token" class="btn btn-primary">
<i class="fas fa-key"></i> Token generieren
</button>
</form>
</div>
<?php else: ?>
<div style="background: #d4edda; border: 1px solid #28a745; border-radius: 8px; padding: 20px; margin-bottom: 20px;">
<p style="color: #155724; margin-bottom: 10px;"><i class="fas fa-check-circle"></i> <strong>Token ist aktiv</strong></p>
<div style="background: #f8f9fa; padding: 15px; border-radius: 6px; margin-bottom: 15px; font-family: monospace; word-break: break-all;">
<?= htmlspecialchars($currentSettings['cron_token']) ?>
</div>
<div style="display: flex; gap: 10px; flex-wrap: wrap;">
<button onclick="copyToClipboard('<?= htmlspecialchars($currentSettings['cron_token']) ?>')" class="btn btn-secondary">
<i class="fas fa-copy"></i> Token kopieren
</button>
<form method="post" style="display: inline;">
<input type="hidden" name="csrf_token" value="<?= $auth->getCsrfToken() ?>">
<button type="submit" name="generate_cron_token" class="btn btn-secondary">
<i class="fas fa-sync"></i> Neu generieren
</button>
</form>
<form method="post" style="display: inline;" onsubmit="return confirm('Token wirklich löschen? Der Cron-Job wird deaktiviert.');">
<input type="hidden" name="csrf_token" value="<?= $auth->getCsrfToken() ?>">
<button type="submit" name="delete_cron_token" class="btn btn-secondary" style="color: #dc3545;">
<i class="fas fa-trash"></i> Löschen
</button>
</form>
</div>
</div>
<?php endif; ?>
<div class="section-divider"></div>
<h3 style="margin-bottom: 15px;">Cron-Job einrichten</h3>
<?php
// Basis-Pfad aus dem bereits berechneten $scriptPath verwenden (vermeidet doppelten Slash)
$cronUrl = $protocol . '://' . $_SERVER['HTTP_HOST'] . $scriptPath . '/cron_sync.php?token=' . ($currentSettings['cron_token'] ?: 'DEIN_TOKEN');
?>
<div class="form-group">
<label>Cron-URL (für Webhooks oder externe Aufrufe)</label>
<div style="display: flex; gap: 10px;">
<input type="text" id="cronUrl" value="<?= htmlspecialchars($cronUrl) ?>" readonly style="flex: 1; background: #f8f9fa;">
<button onclick="copyToClipboard(document.getElementById('cronUrl').value)" class="btn btn-secondary">
<i class="fas fa-copy"></i>
</button>
</div>
</div>
<div class="placeholder-info" style="background: #f8f9fa; border-color: #ccc;">
<h4 style="color: #333;">Crontab-Eintrag (Linux/Mac)</h4>
<p style="color: #666; margin-bottom: 10px;">Fügen Sie diese Zeile in Ihre Crontab ein (<code>crontab -e</code>):</p>
<div style="background: #1e1e1e; color: #d4d4d4; padding: 15px; border-radius: 6px; font-family: monospace; font-size: 13px; overflow-x: auto;">
*/30 * * * * curl -s "<?= htmlspecialchars($cronUrl) ?>" > /dev/null 2>&1
</div>
<p style="color: #999; font-size: 12px; margin-top: 10px;">Dies führt die Synchronisation alle 30 Minuten aus.</p>
</div>
<div class="placeholder-info" style="background: #f8f9fa; border-color: #ccc; margin-top: 15px;">
<h4 style="color: #333;">Windows Task Scheduler</h4>
<p style="color: #666; margin-bottom: 10px;">Erstellen Sie eine geplante Aufgabe mit diesem Befehl:</p>
<div style="background: #1e1e1e; color: #d4d4d4; padding: 15px; border-radius: 6px; font-family: monospace; font-size: 13px; overflow-x: auto;">
powershell -Command "Invoke-WebRequest -Uri '<?= htmlspecialchars($cronUrl) ?>' -UseBasicParsing"
</div>
</div>
<div class="section-divider"></div>
<h3 style="margin-bottom: 15px;">Status</h3>
<table style="width: 100%; max-width: 500px;">
<tr>
<td style="padding: 10px 0; color: #666;">Letzte Synchronisation:</td>
<td>
<?php if ($currentSettings['last_cron_sync']): ?>
<strong><?= date('d.m.Y H:i:s', strtotime($currentSettings['last_cron_sync'])) ?></strong>
<?php else: ?>
<em style="color: #999;">Noch nie ausgeführt</em>
<?php endif; ?>
</td>
</tr>
<tr>
<td style="padding: 10px 0; color: #666;">Token-Status:</td>
<td>
<?php if ($currentSettings['cron_token']): ?>
<span style="color: #28a745;"><i class="fas fa-check-circle"></i> Aktiv</span>
<?php else: ?>
<span style="color: #dc3545;"><i class="fas fa-times-circle"></i> Nicht konfiguriert</span>
<?php endif; ?>
</td>
</tr>
</table>
<?php if ($currentSettings['cron_token']): ?>
<div style="margin-top: 20px;">
<button onclick="testCronJob()" class="btn btn-primary" id="testCronBtn">
<i class="fas fa-play"></i> Jetzt manuell ausführen
</button>
<span id="testCronResult" style="margin-left: 15px;"></span>
</div>
<?php endif; ?>
</div>
<!-- TAB: M365 -->
<div id="tab-m365" class="tab-content">
<h2 style="margin-bottom: 20px;"><i class="fab fa-microsoft"></i> Microsoft 365</h2>
<div class="info-box">
<h4><i class="fas fa-info-circle"></i> Azure AD App</h4>
<p>Redirect URI: <strong><?= $protocol . '://' . $host . $scriptPath ?>/m365_callback.php</strong></p>
</div>
<form method="post">
<input type="hidden" name="csrf_token" value="<?= $auth->getCsrfToken() ?>">
<input type="hidden" name="form_type" value="m365">
<div class="form-group">
<label for="m365_client_id">Client ID</label>
<input type="text" id="m365_client_id" name="m365_client_id" value="<?= htmlspecialchars($currentSettings['m365_client_id']) ?>">
</div>
<div class="form-group">
<label for="m365_client_secret">Client Secret</label>
<input type="password" id="m365_client_secret" name="m365_client_secret" value="<?= htmlspecialchars($currentSettings['m365_client_secret']) ?>">
</div>
<div class="form-group">
<label for="m365_tenant_id">Tenant ID</label>
<input type="text" id="m365_tenant_id" name="m365_tenant_id" value="<?= htmlspecialchars($currentSettings['m365_tenant_id']) ?>">
</div>
<button type="submit" name="save_settings" class="btn btn-primary"><i class="fas fa-save"></i> Speichern</button>
</form>
</div>
<!-- TAB: SMTP -->
<div id="tab-smtp" class="tab-content">
<h2 style="margin-bottom: 20px;"><i class="fas fa-envelope"></i> SMTP</h2>
<form method="post">
<input type="hidden" name="csrf_token" value="<?= $auth->getCsrfToken() ?>">
<input type="hidden" name="form_type" value="smtp">
<div class="checkbox-group" style="margin-bottom: 20px;">
<input type="checkbox" id="smtp_enabled" name="smtp_enabled" <?= $currentSettings['smtp_enabled'] == '1' ? 'checked' : '' ?>>
<label for="smtp_enabled" style="margin:0;">SMTP aktivieren</label>
</div>
<div class="form-grid">
<div class="form-group">
<label for="smtp_host">Host</label>
<input type="text" id="smtp_host" name="smtp_host" value="<?= htmlspecialchars($currentSettings['smtp_host']) ?>">
</div>
<div class="form-group">
<label for="smtp_port">Port</label>
<input type="number" id="smtp_port" name="smtp_port" value="<?= htmlspecialchars($currentSettings['smtp_port']) ?>">
</div>
</div>
<div class="form-group">
<label for="smtp_encryption">Verschlüsselung</label>
<select id="smtp_encryption" name="smtp_encryption">
<option value="tls" <?= $currentSettings['smtp_encryption'] === 'tls' ? 'selected' : '' ?>>TLS</option>
<option value="ssl" <?= $currentSettings['smtp_encryption'] === 'ssl' ? 'selected' : '' ?>>SSL</option>
<option value="none" <?= $currentSettings['smtp_encryption'] === 'none' ? 'selected' : '' ?>>Keine</option>
</select>
</div>
<div class="form-grid">
<div class="form-group">
<label for="smtp_username">Benutzername</label>
<input type="text" id="smtp_username" name="smtp_username" value="<?= htmlspecialchars($currentSettings['smtp_username']) ?>">
</div>
<div class="form-group">
<label for="smtp_password">Passwort</label>
<input type="password" id="smtp_password" name="smtp_password" value="<?= htmlspecialchars($currentSettings['smtp_password']) ?>" placeholder="Leer = nicht ändern">
</div>
</div>
<div class="form-grid">
<div class="form-group">
<label for="smtp_from_email">Absender E-Mail</label>
<input type="email" id="smtp_from_email" name="smtp_from_email" value="<?= htmlspecialchars($currentSettings['smtp_from_email']) ?>">
</div>
<div class="form-group">
<label for="smtp_from_name">Absender Name</label>
<input type="text" id="smtp_from_name" name="smtp_from_name" value="<?= htmlspecialchars($currentSettings['smtp_from_name']) ?>">
</div>
</div>
<button type="submit" name="save_settings" class="btn btn-primary"><i class="fas fa-save"></i> Speichern</button>
</form>
</div>
<!-- TEIL 1 ENDET HIER - Fortsetzung in TEIL 2 -->
<!-- TEIL 2 BEGINNT HIER - Füge dies NACH Teil 1 ein -->
<!-- TAB: Templates -->
<div id="tab-templates" class="tab-content">
<h2 style="margin-bottom: 20px;"><i class="fas fa-file-alt"></i> E-Mail Templates</h2>
<form method="post">
<input type="hidden" name="csrf_token" value="<?= $auth->getCsrfToken() ?>">
<input type="hidden" name="form_type" value="templates">
<div class="form-group">
<label for="system_url">System-URL</label>
<input type="url" id="system_url" name="system_url" value="<?= htmlspecialchars($currentSettings['system_url']) ?>" required>
<div class="help-text">Wird in E-Mails als Login-Link verwendet. Auto: <code><?= $autoDetectedUrl ?></code></div>
</div>
<div class="section-divider"></div>
<h3 style="margin-bottom: 15px;">Voucher E-Mail</h3>
<div class="placeholder-info">
<h4>Platzhalter:</h4>
<div class="placeholder-list">
<div><code>{VOUCHER_CODE}</code></div>
<div><code>{SITE_NAME}</code></div>
<div><code>{MAX_USES}</code></div>
<div><code>{APP_TITLE}</code></div>
<div><code>{INSTRUCTIONS}</code></div>
</div>
</div>
<div class="form-group">
<label for="email_voucher_subject">Betreff</label>
<input type="text" id="email_voucher_subject" name="email_voucher_subject" value="<?= htmlspecialchars($currentSettings['email_voucher_subject']) ?>">
</div>
<div class="form-group">
<label for="email_voucher_body">E-Mail Text</label>
<textarea id="email_voucher_body" name="email_voucher_body" class="tinymce-editor"><?= htmlspecialchars($currentSettings['email_voucher_body']) ?></textarea>
</div>
<div class="section-divider"></div>
<h3 style="margin-bottom: 15px;">Benutzer-Benachrichtigung</h3>
<div class="placeholder-info">
<h4>Platzhalter:</h4>
<div class="placeholder-list">
<div><code>{USER_NAME}</code></div>
<div><code>{CHANGES}</code></div>
<div><code>{APP_TITLE}</code></div>
<div><code>{SYSTEM_URL}</code></div>
</div>
</div>
<div class="form-group">
<label for="email_user_notification_subject">Betreff</label>
<input type="text" id="email_user_notification_subject" name="email_user_notification_subject" value="<?= htmlspecialchars($currentSettings['email_user_notification_subject']) ?>">
</div>
<div class="form-group">
<label for="email_user_notification_body">E-Mail Text</label>
<textarea id="email_user_notification_body" name="email_user_notification_body" class="tinymce-editor"><?= htmlspecialchars($currentSettings['email_user_notification_body']) ?></textarea>
</div>
<button type="submit" name="save_settings" class="btn btn-primary"><i class="fas fa-save"></i> Speichern</button>
</form>
</div>
<!-- TAB: System -->
<div id="tab-system" class="tab-content">
<h2 style="margin-bottom: 20px;"><i class="fas fa-cogs"></i> System & Erweitert</h2>
<form method="post">
<input type="hidden" name="csrf_token" value="<?= $auth->getCsrfToken() ?>">
<input type="hidden" name="form_type" value="system">
<div class="info-box">
<h4><i class="fas fa-info-circle"></i> TinyMCE API Key</h4>
<p>Kostenlosen API Key erhalten: <a href="https://www.tiny.cloud/auth/signup/" target="_blank" style="color: #0066cc;">tiny.cloud/signup</a><br>
Ohne Key wird eine eingeschränkte Version geladen.</p>
</div>
<div class="form-group">
<label for="tinymce_api_key">TinyMCE API Key (optional)</label>
<input type="text" id="tinymce_api_key" name="tinymce_api_key" value="<?= htmlspecialchars($currentSettings['tinymce_api_key']) ?>" placeholder="your-api-key-here">
<div class="help-text">Für WYSIWYG-Editor in Anleitungen und E-Mail-Templates</div>
</div>
<div class="section-divider"></div>
<h3 style="margin-bottom: 15px;">Druck-Template</h3>
<div class="placeholder-info">
<h4>Platzhalter:</h4>
<div class="placeholder-list">
<div><code>{VOUCHER_CODE}</code></div>
<div><code>{EXPIRY_DATE}</code></div>
<div><code>{EXPIRY_TIME}</code></div>
<div><code>{SITE_NAME}</code></div>
<div><code>{MAX_USES}</code></div>
<div><code>{APP_TITLE}</code></div>
<div><code>{INSTRUCTIONS}</code></div>
</div>
</div>
<div class="form-group">
<label for="print_template">HTML Template für Voucher-Druck</label>
<textarea id="print_template" name="print_template" class="tinymce-editor" style="min-height: 300px;"><?= htmlspecialchars($currentSettings['print_template']) ?></textarea>
<div class="help-text">HTML/CSS-Code für den Ausdruck von Vouchers</div>
</div>
<button type="submit" name="save_settings" class="btn btn-primary"><i class="fas fa-save"></i> Speichern</button>
</form>
<div class="section-divider"></div>
<h3 style="margin-bottom: 15px;">System-Information</h3>
<table style="width: 100%;">
<tr><td style="padding: 10px 0; color: #666;">PHP Version:</td><td><strong><?= phpversion() ?></strong></td></tr>
<tr><td style="padding: 10px 0; color: #666;">Datenbank:</td><td><strong><?= DB_NAME ?></strong></td></tr>
<tr><td style="padding: 10px 0; color: #666;">Installiert:</td><td><strong><?= date('d.m.Y H:i', filectime(__DIR__ . '/../config.php')) ?></strong></td></tr>
<tr><td style="padding: 10px 0; color: #666;">Version:</td><td><strong>2.0.0</strong></td></tr>
</table>
</div>
<!-- TAB: Passwort -->
<div id="tab-password" class="tab-content">
<h2 style="margin-bottom: 20px;"><i class="fas fa-key"></i> Passwort ändern</h2>
<form method="post" style="max-width: 500px;">
<input type="hidden" name="csrf_token" value="<?= $auth->getCsrfToken() ?>">
<div class="form-group">
<label for="current_password">Aktuelles Passwort</label>
<input type="password" id="current_password" name="current_password" required>
</div>
<div class="form-group">
<label for="new_password">Neues Passwort</label>
<input type="password" id="new_password" name="new_password" required minlength="8">
<div class="help-text">Mindestens 8 Zeichen</div>
</div>
<div class="form-group">
<label for="confirm_password">Passwort bestätigen</label>
<input type="password" id="confirm_password" name="confirm_password" required>
</div>
<button type="submit" name="change_password" class="btn btn-primary"><i class="fas fa-lock"></i> Passwort ändern</button>
</form>
</div>
</div>
</div>
<script>
// Tab-Switching
function switchTab(tabName) {
// Alle Tabs ausblenden
document.querySelectorAll('.tab-content').forEach(tab => {
tab.classList.remove('active');
});
// Alle Tab-Buttons deaktivieren
document.querySelectorAll('.tab-button').forEach(btn => {
btn.classList.remove('active');
});
// Gewählten Tab aktivieren
document.getElementById('tab-' + tabName).classList.add('active');
event.target.classList.add('active');
// URL Hash aktualisieren (optional)
window.location.hash = tabName;
}
// Tab aus URL Hash laden (beim Seitenladen)
window.addEventListener('DOMContentLoaded', function() {
const hash = window.location.hash.substring(1);
if (hash && document.getElementById('tab-' + hash)) {
const tabButton = Array.from(document.querySelectorAll('.tab-button')).find(btn =>
btn.textContent.toLowerCase().includes(hash)
);
if (tabButton) {
tabButton.click();
}
}
// TinyMCE initialisieren
initTinyMCE();
});
// In Zwischenablage kopieren
function copyToClipboard(text) {
navigator.clipboard.writeText(text).then(() => {
alert('In die Zwischenablage kopiert!');
}).catch(err => {
// Fallback für ältere Browser
const textarea = document.createElement('textarea');
textarea.value = text;
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
document.body.removeChild(textarea);
alert('In die Zwischenablage kopiert!');
});
}
// Cron-Job testen
async function testCronJob() {
const btn = document.getElementById('testCronBtn');
const result = document.getElementById('testCronResult');
btn.disabled = true;
btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Läuft...';
result.innerHTML = '';
try {
const response = await fetch('../cron_sync.php?token=<?= htmlspecialchars($currentSettings['cron_token']) ?>');
const data = await response.json();
if (data.success) {
result.innerHTML = '<span style="color: #28a745;"><i class="fas fa-check-circle"></i> ' + data.message + '</span>';
// Seite nach 2 Sekunden neu laden, um Status zu aktualisieren
setTimeout(() => window.location.reload(), 2000);
} else {
result.innerHTML = '<span style="color: #dc3545;"><i class="fas fa-times-circle"></i> ' + data.message + '</span>';
}
} catch (error) {
result.innerHTML = '<span style="color: #dc3545;"><i class="fas fa-times-circle"></i> Fehler: ' + error.message + '</span>';
}
btn.disabled = false;
btn.innerHTML = '<i class="fas fa-play"></i> Jetzt manuell ausführen';
}
// TinyMCE WYSIWYG Editor initialisieren
function initTinyMCE() {
tinymce.init({
selector: '.tinymce-editor',
height: 400,
menubar: false,
plugins: [
'advlist', 'autolink', 'lists', 'link', 'charmap',
'searchreplace', 'visualblocks', 'code', 'fullscreen',
'insertdatetime', 'table', 'help', 'wordcount'
],
toolbar: 'undo redo | blocks | bold italic forecolor | alignleft aligncenter alignright | bullist numlist | removeformat | help',
content_style: 'body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; font-size: 14px; line-height: 1.6; }',
branding: false,
promotion: false
});
}
</script>
</body>
</html>

671
admin/sites.php Normal file
View file

@ -0,0 +1,671 @@
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/Database.php';
require_once __DIR__ . '/../includes/Auth.php';
require_once __DIR__ . '/../includes/UniFiController.php';
$auth = new Auth();
$auth->requireAdmin();
$db = Database::getInstance();
$appTitle = $db->getSetting('app_title', 'UniFi Voucher System');
$error = '';
$success = '';
// Site bearbeiten
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_site'])) {
if (!$auth->validateCsrfToken($_POST['csrf_token'] ?? '')) {
$error = 'Ungültiges Sicherheits-Token';
} else {
try {
$siteId = (int)$_POST['site_id'];
$name = trim($_POST['name']);
$siteIdStr = trim($_POST['site_id_str']);
$controllerUrl = trim($_POST['controller_url']);
$username = trim($_POST['username']);
$password = $_POST['password'];
$publicAccess = isset($_POST['public_access']) ? 1 : 0;
if (empty($name) || empty($siteIdStr) || empty($controllerUrl) || empty($username)) {
throw new Exception('Bitte füllen Sie alle Pflichtfelder aus');
}
// Wenn neues Passwort, Verbindung testen
if (!empty($password)) {
$testResult = UniFiController::testConnection($controllerUrl, $username, $password, $siteIdStr);
if ($testResult !== true) {
throw new Exception('Verbindung fehlgeschlagen: ' . $testResult);
}
// Mit neuem Passwort aktualisieren
$db->execute(
"UPDATE sites SET name = ?, site_id = ?, unifi_controller_url = ?, unifi_username = ?, unifi_password = ?, public_access = ? WHERE id = ?",
[$name, $siteIdStr, $controllerUrl, $username, $password, $publicAccess, $siteId]
);
} else {
// Ohne Passwort-Änderung
$db->execute(
"UPDATE sites SET name = ?, site_id = ?, unifi_controller_url = ?, unifi_username = ?, public_access = ? WHERE id = ?",
[$name, $siteIdStr, $controllerUrl, $username, $publicAccess, $siteId]
);
}
$success = 'Site erfolgreich aktualisiert!';
} catch (Exception $e) {
$error = $e->getMessage();
}
}
}
// Site hinzufügen
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_site'])) {
if (!$auth->validateCsrfToken($_POST['csrf_token'] ?? '')) {
$error = 'Ungültiges Sicherheits-Token';
} else {
try {
$name = trim($_POST['name']);
$siteId = trim($_POST['site_id']);
$controllerUrl = trim($_POST['controller_url']);
$username = trim($_POST['username']);
$password = $_POST['password'];
$publicAccess = isset($_POST['public_access']) ? 1 : 0;
if (empty($name) || empty($siteId) || empty($controllerUrl) || empty($username)) {
throw new Exception('Bitte füllen Sie alle Pflichtfelder aus');
}
// Verbindung testen
$testResult = UniFiController::testConnection($controllerUrl, $username, $password, $siteId);
if ($testResult !== true) {
throw new Exception('Verbindung fehlgeschlagen: ' . $testResult);
}
$db->execute(
"INSERT INTO sites (name, site_id, unifi_controller_url, unifi_username, unifi_password, public_access)
VALUES (?, ?, ?, ?, ?, ?)",
[$name, $siteId, $controllerUrl, $username, $password, $publicAccess]
);
$success = 'Site erfolgreich hinzugefügt!';
} catch (Exception $e) {
$error = $e->getMessage();
}
}
}
// Site löschen
if (isset($_GET['delete']) && isset($_GET['token'])) {
if ($auth->validateCsrfToken($_GET['token'])) {
$db->query("DELETE FROM sites WHERE id = ?", [(int)$_GET['delete']]);
$success = 'Site erfolgreich gelöscht!';
} else {
$error = 'Ungültiges Sicherheits-Token';
}
}
// Site aktivieren/deaktivieren
if (isset($_GET['toggle']) && isset($_GET['token'])) {
if ($auth->validateCsrfToken($_GET['token'])) {
$site = $db->fetchOne("SELECT is_active FROM sites WHERE id = ?", [(int)$_GET['toggle']]);
if ($site) {
$newStatus = $site['is_active'] ? 0 : 1;
$db->query("UPDATE sites SET is_active = ? WHERE id = ?", [$newStatus, (int)$_GET['toggle']]);
$success = 'Site-Status aktualisiert!';
}
}
}
// Alle Sites abrufen
$sites = $db->fetchAll("SELECT * FROM sites ORDER BY name");
$currentUser = $auth->getCurrentUser();
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sites verwalten - <?= htmlspecialchars($appTitle) ?></title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
background: #f5f7fa;
}
.header {
background: white;
border-bottom: 1px solid #e0e0e0;
padding: 0 30px;
height: 70px;
display: flex;
align-items: center;
justify-content: space-between;
position: sticky;
top: 0;
z-index: 100;
box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}
.header-title { font-size: 20px; font-weight: 600; color: #333; }
.sidebar {
position: fixed;
left: 0;
top: 70px;
bottom: 0;
width: 260px;
background: white;
border-right: 1px solid #e0e0e0;
padding: 30px 0;
}
.sidebar-nav { list-style: none; }
.sidebar-nav a {
display: flex;
align-items: center;
gap: 12px;
padding: 12px 30px;
color: #666;
text-decoration: none;
transition: all 0.2s;
font-size: 15px;
}
.sidebar-nav a:hover,
.sidebar-nav a.active {
background: #f8f9fa;
color: #667eea;
}
.sidebar-nav i { width: 20px; text-align: center; }
.main-content {
margin-left: 260px;
padding: 30px;
min-height: calc(100vh - 70px);
}
.page-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 30px;
}
.page-title { font-size: 28px; font-weight: 600; color: #333; }
.btn {
padding: 10px 20px;
border-radius: 8px;
border: none;
font-weight: 500;
cursor: pointer;
text-decoration: none;
display: inline-flex;
align-items: center;
gap: 8px;
transition: all 0.2s;
font-size: 14px;
}
.btn-primary {
background: #667eea;
color: white;
}
.btn-primary:hover { background: #5568d3; }
.btn-secondary {
background: #f8f9fa;
color: #666;
border: 1px solid #e0e0e0;
}
.btn-danger {
background: #dc3545;
color: white;
}
.btn-success {
background: #28a745;
color: white;
}
.btn-small {
padding: 6px 12px;
font-size: 13px;
}
.card {
background: white;
border-radius: 15px;
box-shadow: 0 2px 10px rgba(0,0,0,0.05);
border: 1px solid #e0e0e0;
margin-bottom: 20px;
}
.card-header {
padding: 20px 25px;
border-bottom: 1px solid #e0e0e0;
}
.card-title { font-size: 18px; font-weight: 600; color: #333; }
.card-body { padding: 25px; }
.form-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
margin-bottom: 20px;
}
.form-group { margin-bottom: 20px; }
label {
display: block;
margin-bottom: 8px;
color: #555;
font-weight: 500;
font-size: 14px;
}
input[type="text"],
input[type="password"],
input[type="url"] {
width: 100%;
padding: 12px;
border: 2px solid #e0e0e0;
border-radius: 8px;
font-size: 14px;
transition: border-color 0.3s;
}
input:focus {
outline: none;
border-color: #667eea;
}
.checkbox-group {
display: flex;
align-items: center;
gap: 10px;
}
.checkbox-group input {
width: auto;
}
.alert {
padding: 14px;
border-radius: 10px;
margin-bottom: 25px;
font-size: 14px;
}
.alert-error {
background: #fee;
border: 1px solid #fcc;
color: #c33;
}
.alert-success {
background: #efe;
border: 1px solid #cfc;
color: #3c3;
}
.sites-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
gap: 20px;
}
.site-card {
background: white;
border: 2px solid #e0e0e0;
border-radius: 12px;
padding: 20px;
transition: all 0.3s;
}
.site-card:hover {
border-color: #667eea;
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
}
.site-card-header {
display: flex;
justify-content: space-between;
align-items: start;
margin-bottom: 15px;
}
.site-name {
font-size: 18px;
font-weight: 600;
color: #333;
margin-bottom: 5px;
}
.site-id {
font-size: 12px;
color: #999;
font-family: monospace;
}
.site-info {
margin: 15px 0;
font-size: 13px;
color: #666;
}
.site-info-item {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 8px;
}
.site-actions {
display: flex;
gap: 8px;
margin-top: 15px;
padding-top: 15px;
border-top: 1px solid #f0f0f0;
}
.badge {
display: inline-block;
padding: 4px 10px;
border-radius: 6px;
font-size: 11px;
font-weight: 500;
}
.badge-success {
background: #d4edda;
color: #155724;
}
.badge-warning {
background: #fff3cd;
color: #856404;
}
.badge-info {
background: #d1ecf1;
color: #0c5460;
}
.modal {
display: none;
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0,0,0,0.5);
z-index: 1000;
align-items: center;
justify-content: center;
}
.modal.active { display: flex; }
.modal-content {
background: white;
border-radius: 15px;
max-width: 600px;
width: 90%;
max-height: 90vh;
overflow-y: auto;
}
.modal-header {
padding: 25px;
border-bottom: 1px solid #e0e0e0;
display: flex;
justify-content: space-between;
align-items: center;
}
.modal-title { font-size: 20px; font-weight: 600; }
.modal-close {
background: none;
border: none;
font-size: 24px;
cursor: pointer;
color: #999;
}
.modal-body { padding: 25px; }
</style>
</head>
<body>
<div class="header">
<div class="header-title">
<i class="fas fa-shield-alt"></i> Administration
</div>
<a href="../index.php" class="btn btn-secondary">
<i class="fas fa-arrow-left"></i> Zurück
</a>
</div>
<div class="sidebar">
<nav class="sidebar-nav">
<ul>
<li><a href="index.php"><i class="fas fa-home"></i> Dashboard</a></li>
<li><a href="sites.php" class="active"><i class="fas fa-map-marker-alt"></i> Sites verwalten</a></li>
<li><a href="users.php"><i class="fas fa-users"></i> Benutzer verwalten</a></li>
<li><a href="vouchers.php"><i class="fas fa-ticket-alt"></i> Voucher-Historie</a></li>
<li><a href="settings.php"><i class="fas fa-cog"></i> Einstellungen</a></li>
</ul>
</nav>
</div>
<div class="main-content">
<div class="page-header">
<h1 class="page-title">Sites verwalten</h1>
<button onclick="openModal()" class="btn btn-primary">
<i class="fas fa-plus"></i> Neue Site hinzufügen
</button>
</div>
<?php if ($error): ?>
<div class="alert alert-error"><i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars($error) ?></div>
<?php endif; ?>
<?php if ($success): ?>
<div class="alert alert-success"><i class="fas fa-check-circle"></i> <?= htmlspecialchars($success) ?></div>
<?php endif; ?>
<?php if (empty($sites)): ?>
<div class="card">
<div class="card-body" style="text-align: center; padding: 60px 20px; color: #999;">
<i class="fas fa-map-marker-alt" style="font-size: 48px; margin-bottom: 20px; opacity: 0.3;"></i>
<p>Noch keine Sites konfiguriert.<br>Fügen Sie Ihre erste Site hinzu!</p>
</div>
</div>
<?php else: ?>
<div class="sites-grid">
<?php foreach ($sites as $site): ?>
<div class="site-card">
<div class="site-card-header">
<div>
<div class="site-name"><?= htmlspecialchars($site['name']) ?></div>
<div class="site-id">ID: <?= htmlspecialchars($site['site_id']) ?></div>
</div>
<div>
<?php if ($site['is_active']): ?>
<span class="badge badge-success"><i class="fas fa-check"></i> Aktiv</span>
<?php else: ?>
<span class="badge badge-warning"><i class="fas fa-pause"></i> Inaktiv</span>
<?php endif; ?>
<?php if ($site['public_access']): ?>
<span class="badge badge-info"><i class="fas fa-globe"></i> Öffentlich</span>
<?php endif; ?>
</div>
</div>
<div class="site-info">
<div class="site-info-item">
<i class="fas fa-server" style="color: #667eea;"></i>
<span><?= htmlspecialchars($site['unifi_controller_url']) ?></span>
</div>
<div class="site-info-item">
<i class="fas fa-user" style="color: #667eea;"></i>
<span><?= htmlspecialchars($site['unifi_username']) ?></span>
</div>
<div class="site-info-item">
<i class="fas fa-clock" style="color: #999;"></i>
<span>Erstellt: <?= date('d.m.Y', strtotime($site['created_at'])) ?></span>
</div>
</div>
<div class="site-actions">
<button onclick="openEditModal(<?= $site['id'] ?>, '<?= htmlspecialchars($site['name'], ENT_QUOTES) ?>', '<?= htmlspecialchars($site['site_id'], ENT_QUOTES) ?>', '<?= htmlspecialchars($site['unifi_controller_url'], ENT_QUOTES) ?>', '<?= htmlspecialchars($site['unifi_username'], ENT_QUOTES) ?>', <?= $site['public_access'] ?>)"
class="btn btn-secondary btn-small">
<i class="fas fa-edit"></i> Bearbeiten
</button>
<a href="?toggle=<?= $site['id'] ?>&token=<?= $auth->getCsrfToken() ?>"
class="btn btn-secondary btn-small">
<i class="fas fa-<?= $site['is_active'] ? 'pause' : 'play' ?>"></i>
<?= $site['is_active'] ? 'Deaktivieren' : 'Aktivieren' ?>
</a>
<a href="?delete=<?= $site['id'] ?>&token=<?= $auth->getCsrfToken() ?>"
class="btn btn-danger btn-small"
onclick="return confirm('Möchten Sie diese Site wirklich löschen?')">
<i class="fas fa-trash"></i> Löschen
</a>
</div>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>
</div>
<!-- Modal für neue Site -->
<div id="addSiteModal" class="modal">
<div class="modal-content">
<div class="modal-header">
<h2 class="modal-title">Neue Site hinzufügen</h2>
<button class="modal-close" onclick="closeModal('addSiteModal')">&times;</button>
</div>
<div class="modal-body">
<form method="post" id="addSiteForm">
<input type="hidden" name="csrf_token" value="<?= $auth->getCsrfToken() ?>">
<div class="form-group">
<label for="name">Site-Name *</label>
<input type="text" id="name" name="name" required
placeholder="z.B. Hauptgebäude">
</div>
<div class="form-group">
<label for="site_id">UniFi Site ID *</label>
<input type="text" id="site_id" name="site_id" required
placeholder="z.B. default">
<small style="color: #999; font-size: 12px;">
Zu finden in der UniFi Controller URL oder in den Site-Einstellungen
</small>
</div>
<div class="form-group">
<label for="controller_url">Controller URL *</label>
<input type="url" id="controller_url" name="controller_url" required
placeholder="https://unifi.example.com:8443">
<small style="color: #999; font-size: 12px;">
Vollständige URL inklusive Port (meist 8443)
</small>
</div>
<div class="form-grid">
<div class="form-group">
<label for="username">Benutzername *</label>
<input type="text" id="username" name="username" required
placeholder="admin">
</div>
<div class="form-group">
<label for="password">Passwort *</label>
<input type="password" id="password" name="password" required>
</div>
</div>
<div class="form-group checkbox-group">
<input type="checkbox" id="public_access" name="public_access">
<label for="public_access" style="margin: 0;">
Öffentlicher Zugriff (ohne Login nutzbar)
</label>
</div>
<div style="display: flex; gap: 10px; margin-top: 25px;">
<button type="submit" name="add_site" class="btn btn-primary" style="flex: 1;">
<i class="fas fa-save"></i> Site hinzufügen
</button>
<button type="button" onclick="closeModal('addSiteModal')" class="btn btn-secondary">
Abbrechen
</button>
</div>
</form>
</div>
</div>
</div>
<!-- Modal für Site bearbeiten -->
<div id="editSiteModal" class="modal">
<div class="modal-content">
<div class="modal-header">
<h2 class="modal-title">Site bearbeiten</h2>
<button class="modal-close" onclick="closeModal('editSiteModal')">&times;</button>
</div>
<div class="modal-body">
<form method="post" id="editSiteForm">
<input type="hidden" name="csrf_token" value="<?= $auth->getCsrfToken() ?>">
<input type="hidden" name="site_id" id="edit_site_id">
<div class="form-group">
<label for="edit_name">Site-Name *</label>
<input type="text" id="edit_name" name="name" required>
</div>
<div class="form-group">
<label for="edit_site_id_str">UniFi Site ID *</label>
<input type="text" id="edit_site_id_str" name="site_id_str" required>
</div>
<div class="form-group">
<label for="edit_controller_url">Controller URL *</label>
<input type="url" id="edit_controller_url" name="controller_url" required>
</div>
<div class="form-grid">
<div class="form-group">
<label for="edit_username">Benutzername *</label>
<input type="text" id="edit_username" name="username" required>
</div>
<div class="form-group">
<label for="edit_password">Neues Passwort</label>
<input type="password" id="edit_password" name="password" placeholder="Leer lassen = nicht ändern">
<small style="color: #999; font-size: 12px;">
Nur ausfüllen wenn Sie das Passwort ändern möchten
</small>
</div>
</div>
<div class="form-group checkbox-group">
<input type="checkbox" id="edit_public_access" name="public_access">
<label for="edit_public_access" style="margin: 0;">
Öffentlicher Zugriff (ohne Login nutzbar)
</label>
</div>
<div style="display: flex; gap: 10px; margin-top: 25px;">
<button type="submit" name="edit_site" class="btn btn-primary" style="flex: 1;">
<i class="fas fa-save"></i> Änderungen speichern
</button>
<button type="button" onclick="closeModal('editSiteModal')" class="btn btn-secondary">
Abbrechen
</button>
</div>
</form>
</div>
</div>
</div>
<script>
function openModal() {
document.getElementById('addSiteModal').classList.add('active');
}
function closeModal(modalId) {
document.getElementById(modalId).classList.remove('active');
}
function openEditModal(id, name, siteIdStr, controllerUrl, username, publicAccess) {
document.getElementById('edit_site_id').value = id;
document.getElementById('edit_name').value = name;
document.getElementById('edit_site_id_str').value = siteIdStr;
document.getElementById('edit_controller_url').value = controllerUrl;
document.getElementById('edit_username').value = username;
document.getElementById('edit_password').value = '';
document.getElementById('edit_public_access').checked = publicAccess == 1;
document.getElementById('editSiteModal').classList.add('active');
}
// Modal schließen bei Klick außerhalb
document.getElementById('addSiteModal').addEventListener('click', function(e) {
if (e.target === this) {
closeModal('addSiteModal');
}
});
document.getElementById('editSiteModal').addEventListener('click', function(e) {
if (e.target === this) {
closeModal('editSiteModal');
}
});
</script>
</body>
</html>

767
admin/users.php Normal file
View file

@ -0,0 +1,767 @@
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/Database.php';
require_once __DIR__ . '/../includes/Auth.php';
require_once __DIR__ . '/../includes/Mailer.php';
$auth = new Auth();
$auth->requireAdmin();
$db = Database::getInstance();
$mailer = new Mailer();
$appTitle = $db->getSetting('app_title', 'UniFi Voucher System');
$error = '';
$success = '';
// Benutzer bearbeiten
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_user'])) {
if (!$auth->validateCsrfToken($_POST['csrf_token'] ?? '')) {
$error = 'Ungültiges Sicherheits-Token';
} else {
try {
$userId = (int)$_POST['user_id'];
$isAdmin = isset($_POST['is_admin']) ? 1 : 0;
$siteIds = $_POST['site_ids'] ?? [];
// Alten Status abrufen
$oldUser = $db->fetchOne("SELECT * FROM users WHERE id = ?", [$userId]);
$oldIsAdmin = $oldUser['is_admin'];
$oldSites = $db->fetchAll("SELECT s.name FROM sites s INNER JOIN user_site_access usa ON s.id = usa.site_id WHERE usa.user_id = ?", [$userId]);
// Admin-Status aktualisieren
$db->query("UPDATE users SET is_admin = ? WHERE id = ?", [$isAdmin, $userId]);
// Alte Site-Zugriffe löschen (nur wenn nicht Admin)
$db->query("DELETE FROM user_site_access WHERE user_id = ?", [$userId]);
// Neue Site-Zugriffe zuweisen (nur wenn nicht Admin)
$newSites = [];
if (!$isAdmin && !empty($siteIds)) {
foreach ($siteIds as $siteId) {
$db->execute(
"INSERT INTO user_site_access (user_id, site_id) VALUES (?, ?)",
[$userId, $siteId]
);
$site = $db->fetchOne("SELECT name FROM sites WHERE id = ?", [$siteId]);
if ($site) {
$newSites[] = $site['name'];
}
}
}
// E-Mail-Benachrichtigung vorbereiten
$changes = [];
if ($oldIsAdmin != $isAdmin) {
if ($isAdmin) {
$changes[] = "Sie wurden zum Administrator ernannt";
} else {
$changes[] = "Ihre Administrator-Rechte wurden entfernt";
}
}
// Site-Änderungen erkennen
$oldSiteNames = array_column($oldSites, 'name');
$addedSites = array_diff($newSites, $oldSiteNames);
$removedSites = array_diff($oldSiteNames, $newSites);
if (!empty($addedSites)) {
$changes[] = "Zugriff gewährt auf: " . implode(', ', $addedSites);
}
if (!empty($removedSites)) {
$changes[] = "Zugriff entfernt von: " . implode(', ', $removedSites);
}
if ($isAdmin && !$oldIsAdmin) {
$changes[] = "Sie haben nun Zugriff auf alle Sites";
}
// E-Mail senden wenn Änderungen vorliegen
if (!empty($changes)) {
$mailer->sendUserNotification($oldUser['email'], $oldUser['name'], $changes);
}
$success = 'Benutzer erfolgreich aktualisiert!' . (!empty($changes) ? ' Benachrichtigung wurde versendet.' : '');
} catch (Exception $e) {
$error = $e->getMessage();
}
}
}
// Benutzer hinzufügen
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_user'])) {
if (!$auth->validateCsrfToken($_POST['csrf_token'] ?? '')) {
$error = 'Ungültiges Sicherheits-Token';
} else {
try {
$email = trim($_POST['email']);
$name = trim($_POST['name']);
$password = $_POST['password'];
$isAdmin = isset($_POST['is_admin']) ? 1 : 0;
$siteIds = $_POST['site_ids'] ?? [];
if (empty($email) || empty($name) || empty($password)) {
throw new Exception('Bitte füllen Sie alle Pflichtfelder aus');
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new Exception('Ungültige E-Mail-Adresse');
}
if (strlen($password) < 8) {
throw new Exception('Passwort muss mindestens 8 Zeichen lang sein');
}
// Prüfen ob E-Mail bereits existiert
$existing = $db->fetchOne("SELECT id FROM users WHERE email = ?", [$email]);
if ($existing) {
throw new Exception('Ein Benutzer mit dieser E-Mail existiert bereits');
}
// Benutzer anlegen
$userId = $auth->registerUser($email, $name, $password, $isAdmin);
if (!$userId) {
throw new Exception('Benutzer konnte nicht erstellt werden');
}
// Site-Zugriffe zuweisen (nur wenn nicht Admin)
if (!$isAdmin && !empty($siteIds)) {
foreach ($siteIds as $siteId) {
$db->execute(
"INSERT INTO user_site_access (user_id, site_id) VALUES (?, ?)",
[$userId, $siteId]
);
}
}
$success = 'Benutzer erfolgreich erstellt!';
} catch (Exception $e) {
$error = $e->getMessage();
}
}
}
// Benutzer löschen
if (isset($_GET['delete']) && isset($_GET['token'])) {
if ($auth->validateCsrfToken($_GET['token'])) {
$deleteId = (int)$_GET['delete'];
$currentUserId = $_SESSION['user_id'];
if ($deleteId === $currentUserId) {
$error = 'Sie können sich nicht selbst löschen';
} else {
$db->query("DELETE FROM users WHERE id = ?", [$deleteId]);
$success = 'Benutzer erfolgreich gelöscht!';
}
} else {
$error = 'Ungültiges Sicherheits-Token';
}
}
// Benutzer aktivieren/deaktivieren
if (isset($_GET['toggle']) && isset($_GET['token'])) {
if ($auth->validateCsrfToken($_GET['token'])) {
$toggleId = (int)$_GET['toggle'];
$currentUserId = $_SESSION['user_id'];
if ($toggleId === $currentUserId) {
$error = 'Sie können sich nicht selbst deaktivieren';
} else {
$user = $db->fetchOne("SELECT is_active FROM users WHERE id = ?", [$toggleId]);
if ($user) {
$newStatus = $user['is_active'] ? 0 : 1;
$db->query("UPDATE users SET is_active = ? WHERE id = ?", [$newStatus, $toggleId]);
$success = 'Benutzer-Status aktualisiert!';
}
}
}
}
// Alle Benutzer und Sites abrufen
$users = $db->fetchAll("SELECT * FROM users ORDER BY name");
$sites = $db->fetchAll("SELECT * FROM sites WHERE is_active = 1 ORDER BY name");
// Site-Zugriffe für jeden Benutzer abrufen
$userSiteAccess = [];
foreach ($users as $user) {
$userSiteAccess[$user['id']] = $db->fetchAll(
"SELECT s.name FROM sites s
INNER JOIN user_site_access usa ON s.id = usa.site_id
WHERE usa.user_id = ?",
[$user['id']]
);
}
$currentUser = $auth->getCurrentUser();
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Benutzer verwalten - <?= htmlspecialchars($appTitle) ?></title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
background: #f5f7fa;
}
.header {
background: white;
border-bottom: 1px solid #e0e0e0;
padding: 0 30px;
height: 70px;
display: flex;
align-items: center;
justify-content: space-between;
position: sticky;
top: 0;
z-index: 100;
box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}
.header-title { font-size: 20px; font-weight: 600; color: #333; }
.sidebar {
position: fixed;
left: 0;
top: 70px;
bottom: 0;
width: 260px;
background: white;
border-right: 1px solid #e0e0e0;
padding: 30px 0;
}
.sidebar-nav { list-style: none; }
.sidebar-nav a {
display: flex;
align-items: center;
gap: 12px;
padding: 12px 30px;
color: #666;
text-decoration: none;
transition: all 0.2s;
font-size: 15px;
}
.sidebar-nav a:hover,
.sidebar-nav a.active {
background: #f8f9fa;
color: #667eea;
}
.sidebar-nav i { width: 20px; text-align: center; }
.main-content {
margin-left: 260px;
padding: 30px;
min-height: calc(100vh - 70px);
}
.page-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 30px;
}
.page-title { font-size: 28px; font-weight: 600; color: #333; }
.btn {
padding: 10px 20px;
border-radius: 8px;
border: none;
font-weight: 500;
cursor: pointer;
text-decoration: none;
display: inline-flex;
align-items: center;
gap: 8px;
transition: all 0.2s;
font-size: 14px;
}
.btn-primary {
background: #667eea;
color: white;
}
.btn-primary:hover { background: #5568d3; }
.btn-secondary {
background: #f8f9fa;
color: #666;
border: 1px solid #e0e0e0;
}
.btn-danger {
background: #dc3545;
color: white;
}
.btn-small {
padding: 6px 12px;
font-size: 13px;
}
.card {
background: white;
border-radius: 15px;
box-shadow: 0 2px 10px rgba(0,0,0,0.05);
border: 1px solid #e0e0e0;
overflow: hidden;
}
.card-header {
padding: 20px 25px;
border-bottom: 1px solid #e0e0e0;
}
.card-title { font-size: 18px; font-weight: 600; color: #333; }
.card-body { padding: 0; }
.alert {
padding: 14px 25px;
margin: 0 25px 20px 25px;
border-radius: 10px;
font-size: 14px;
}
.alert-error {
background: #fee;
border: 1px solid #fcc;
color: #c33;
}
.alert-success {
background: #efe;
border: 1px solid #cfc;
color: #3c3;
}
.table {
width: 100%;
border-collapse: collapse;
}
.table th {
text-align: left;
padding: 15px;
background: #f8f9fa;
color: #666;
font-weight: 600;
font-size: 13px;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.table td {
padding: 15px;
border-bottom: 1px solid #f0f0f0;
color: #333;
}
.table tr:last-child td {
border-bottom: none;
}
.badge {
display: inline-block;
padding: 4px 10px;
border-radius: 6px;
font-size: 11px;
font-weight: 500;
margin-right: 5px;
}
.badge-success {
background: #d4edda;
color: #155724;
}
.badge-warning {
background: #fff3cd;
color: #856404;
}
.badge-danger {
background: #f8d7da;
color: #721c24;
}
.badge-info {
background: #d1ecf1;
color: #0c5460;
}
.modal {
display: none;
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0,0,0,0.5);
z-index: 1000;
align-items: center;
justify-content: center;
}
.modal.active { display: flex; }
.modal-content {
background: white;
border-radius: 15px;
max-width: 600px;
width: 90%;
max-height: 90vh;
overflow-y: auto;
}
.modal-header {
padding: 25px;
border-bottom: 1px solid #e0e0e0;
display: flex;
justify-content: space-between;
align-items: center;
}
.modal-title { font-size: 20px; font-weight: 600; }
.modal-close {
background: none;
border: none;
font-size: 24px;
cursor: pointer;
color: #999;
}
.modal-body { padding: 25px; }
.form-group { margin-bottom: 20px; }
label {
display: block;
margin-bottom: 8px;
color: #555;
font-weight: 500;
font-size: 14px;
}
input[type="text"],
input[type="email"],
input[type="password"] {
width: 100%;
padding: 12px;
border: 2px solid #e0e0e0;
border-radius: 8px;
font-size: 14px;
transition: border-color 0.3s;
}
input:focus {
outline: none;
border-color: #667eea;
}
.checkbox-group {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 10px;
}
.checkbox-group input {
width: auto;
}
.site-selection {
border: 1px solid #e0e0e0;
border-radius: 8px;
padding: 15px;
max-height: 200px;
overflow-y: auto;
}
.empty-state {
text-align: center;
padding: 60px 20px;
color: #999;
}
.empty-state i {
font-size: 48px;
margin-bottom: 20px;
opacity: 0.3;
}
</style>
</head>
<body>
<div class="header">
<div class="header-title">
<i class="fas fa-shield-alt"></i> Administration
</div>
<a href="../index.php" class="btn btn-secondary">
<i class="fas fa-arrow-left"></i> Zurück
</a>
</div>
<div class="sidebar">
<nav class="sidebar-nav">
<ul>
<li><a href="index.php"><i class="fas fa-home"></i> Dashboard</a></li>
<li><a href="sites.php"><i class="fas fa-map-marker-alt"></i> Sites verwalten</a></li>
<li><a href="users.php" class="active"><i class="fas fa-users"></i> Benutzer verwalten</a></li>
<li><a href="vouchers.php"><i class="fas fa-ticket-alt"></i> Voucher-Historie</a></li>
<li><a href="settings.php"><i class="fas fa-cog"></i> Einstellungen</a></li>
</ul>
</nav>
</div>
<div class="main-content">
<div class="page-header">
<h1 class="page-title">Benutzer verwalten</h1>
<button onclick="openModal()" class="btn btn-primary">
<i class="fas fa-plus"></i> Neuer Benutzer
</button>
</div>
<?php if ($error): ?>
<div class="alert alert-error"><i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars($error) ?></div>
<?php endif; ?>
<?php if ($success): ?>
<div class="alert alert-success"><i class="fas fa-check-circle"></i> <?= htmlspecialchars($success) ?></div>
<?php endif; ?>
<div class="card">
<div class="card-header">
<h2 class="card-title">Alle Benutzer</h2>
</div>
<div class="card-body">
<?php if (empty($users)): ?>
<div class="empty-state">
<i class="fas fa-users"></i>
<p>Noch keine Benutzer vorhanden</p>
</div>
<?php else: ?>
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>E-Mail</th>
<th>Rolle</th>
<th>Status</th>
<th>Site-Zugriffe</th>
<th>Letzter Login</th>
<th>Aktionen</th>
</tr>
</thead>
<tbody>
<?php foreach ($users as $user): ?>
<tr>
<td>
<strong><?= htmlspecialchars($user['name']) ?></strong>
<?php if ($user['id'] == $_SESSION['user_id']): ?>
<span class="badge badge-info">Sie</span>
<?php endif; ?>
</td>
<td><?= htmlspecialchars($user['email']) ?></td>
<td>
<?php if ($user['is_admin']): ?>
<span class="badge badge-danger"><i class="fas fa-crown"></i> Admin</span>
<?php else: ?>
<span class="badge badge-info">Benutzer</span>
<?php endif; ?>
</td>
<td>
<?php if ($user['is_active']): ?>
<span class="badge badge-success"><i class="fas fa-check"></i> Aktiv</span>
<?php else: ?>
<span class="badge badge-warning"><i class="fas fa-pause"></i> Inaktiv</span>
<?php endif; ?>
</td>
<td>
<?php if ($user['is_admin']): ?>
<em style="color: #999;">Alle Sites</em>
<?php elseif (!empty($userSiteAccess[$user['id']])): ?>
<?php foreach ($userSiteAccess[$user['id']] as $site): ?>
<span class="badge badge-info"><?= htmlspecialchars($site['name']) ?></span>
<?php endforeach; ?>
<?php else: ?>
<em style="color: #999;">Keine</em>
<?php endif; ?>
</td>
<td>
<?php if ($user['last_login']): ?>
<?= date('d.m.Y H:i', strtotime($user['last_login'])) ?>
<?php else: ?>
<em style="color: #999;">Noch nie</em>
<?php endif; ?>
</td>
<td>
<?php if ($user['id'] != $_SESSION['user_id']): ?>
<button onclick="openEditModal(<?= $user['id'] ?>, '<?= htmlspecialchars($user['name'], ENT_QUOTES) ?>', <?= $user['is_admin'] ?>, [<?= implode(',', array_map(function($s) { return $s['site_id'] ?? 0; }, $db->fetchAll("SELECT site_id FROM user_site_access WHERE user_id = ?", [$user['id']]))) ?>])"
class="btn btn-secondary btn-small">
<i class="fas fa-edit"></i>
</button>
<a href="?toggle=<?= $user['id'] ?>&token=<?= $auth->getCsrfToken() ?>"
class="btn btn-secondary btn-small">
<i class="fas fa-<?= $user['is_active'] ? 'pause' : 'play' ?>"></i>
</a>
<a href="?delete=<?= $user['id'] ?>&token=<?= $auth->getCsrfToken() ?>"
class="btn btn-danger btn-small"
onclick="return confirm('Benutzer wirklich löschen?')">
<i class="fas fa-trash"></i>
</a>
<?php else: ?>
<button onclick="openEditModal(<?= $user['id'] ?>, '<?= htmlspecialchars($user['name'], ENT_QUOTES) ?>', <?= $user['is_admin'] ?>, [<?= implode(',', array_map(function($s) { return $s['site_id'] ?? 0; }, $db->fetchAll("SELECT site_id FROM user_site_access WHERE user_id = ?", [$user['id']]))) ?>])"
class="btn btn-secondary btn-small">
<i class="fas fa-edit"></i>
</button>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
</div>
</div>
</div>
<!-- Modal für neuen Benutzer -->
<div id="addUserModal" class="modal">
<div class="modal-content">
<div class="modal-header">
<h2 class="modal-title">Neuen Benutzer anlegen</h2>
<button class="modal-close" onclick="closeModal('addUserModal')">&times;</button>
</div>
<div class="modal-body">
<form method="post" id="addUserForm">
<input type="hidden" name="csrf_token" value="<?= $auth->getCsrfToken() ?>">
<div class="form-group">
<label for="name">Name *</label>
<input type="text" id="name" name="name" required>
</div>
<div class="form-group">
<label for="email">E-Mail *</label>
<input type="email" id="email" name="email" required>
</div>
<div class="form-group">
<label for="password">Passwort *</label>
<input type="password" id="password" name="password" required minlength="8">
<small style="color: #999; font-size: 12px;">Mindestens 8 Zeichen</small>
</div>
<div class="form-group">
<div class="checkbox-group">
<input type="checkbox" id="is_admin" name="is_admin" onchange="toggleSiteSelection('add')">
<label for="is_admin" style="margin: 0;">Administrator-Rechte</label>
</div>
<small style="color: #999; font-size: 12px;">Admins haben Zugriff auf alle Sites und Einstellungen</small>
</div>
<div class="form-group" id="siteSelectionGroup">
<label>Site-Zugriffe</label>
<div class="site-selection">
<?php if (empty($sites)): ?>
<em style="color: #999;">Keine Sites verfügbar. Bitte zuerst Sites anlegen.</em>
<?php else: ?>
<?php foreach ($sites as $site): ?>
<div class="checkbox-group">
<input type="checkbox" name="site_ids[]" value="<?= $site['id'] ?>" id="site_<?= $site['id'] ?>">
<label for="site_<?= $site['id'] ?>" style="margin: 0;"><?= htmlspecialchars($site['name']) ?></label>
</div>
<?php endforeach; ?>
<?php endif; ?>
</div>
<small style="color: #999; font-size: 12px;">Wählen Sie die Sites, auf die dieser Benutzer Zugriff haben soll</small>
</div>
<div style="display: flex; gap: 10px; margin-top: 25px;">
<button type="submit" name="add_user" class="btn btn-primary" style="flex: 1;">
<i class="fas fa-save"></i> Benutzer anlegen
</button>
<button type="button" onclick="closeModal('addUserModal')" class="btn btn-secondary">
Abbrechen
</button>
</div>
</form>
</div>
</div>
</div>
<!-- Modal für Benutzer bearbeiten -->
<div id="editUserModal" class="modal">
<div class="modal-content">
<div class="modal-header">
<h2 class="modal-title">Benutzer bearbeiten</h2>
<button class="modal-close" onclick="closeModal('editUserModal')">&times;</button>
</div>
<div class="modal-body">
<form method="post" id="editUserForm">
<input type="hidden" name="csrf_token" value="<?= $auth->getCsrfToken() ?>">
<input type="hidden" name="user_id" id="edit_user_id">
<div class="form-group">
<label>Name</label>
<input type="text" id="edit_name" readonly style="background: #f5f5f5;">
</div>
<div class="form-group">
<div class="checkbox-group">
<input type="checkbox" id="edit_is_admin" name="is_admin" onchange="toggleSiteSelection('edit')">
<label for="edit_is_admin" style="margin: 0;">Administrator-Rechte</label>
</div>
<small style="color: #999; font-size: 12px;">Admins haben Zugriff auf alle Sites und Einstellungen</small>
</div>
<div class="form-group" id="editSiteSelectionGroup">
<label>Site-Zugriffe</label>
<div class="site-selection" id="editSitesList">
<?php if (!empty($sites)): ?>
<?php foreach ($sites as $site): ?>
<div class="checkbox-group">
<input type="checkbox" name="site_ids[]" value="<?= $site['id'] ?>" id="edit_site_<?= $site['id'] ?>">
<label for="edit_site_<?= $site['id'] ?>" style="margin: 0;"><?= htmlspecialchars($site['name']) ?></label>
</div>
<?php endforeach; ?>
<?php endif; ?>
</div>
</div>
<div style="display: flex; gap: 10px; margin-top: 25px;">
<button type="submit" name="edit_user" class="btn btn-primary" style="flex: 1;">
<i class="fas fa-save"></i> Änderungen speichern
</button>
<button type="button" onclick="closeModal('editUserModal')" class="btn btn-secondary">
Abbrechen
</button>
</div>
</form>
</div>
</div>
</div>
<script>
function openModal() {
document.getElementById('addUserModal').classList.add('active');
}
function closeModal(modalId) {
document.getElementById(modalId).classList.remove('active');
}
function openEditModal(userId, userName, isAdmin, siteIds) {
document.getElementById('edit_user_id').value = userId;
document.getElementById('edit_name').value = userName;
document.getElementById('edit_is_admin').checked = isAdmin == 1;
// Alle Checkboxen erst deaktivieren
document.querySelectorAll('#editSitesList input[type="checkbox"]').forEach(cb => {
cb.checked = false;
});
// Ausgewählte Sites aktivieren
siteIds.forEach(siteId => {
const checkbox = document.getElementById('edit_site_' + siteId);
if (checkbox) checkbox.checked = true;
});
toggleSiteSelection('edit');
document.getElementById('editUserModal').classList.add('active');
}
function toggleSiteSelection(mode) {
const isAdmin = document.getElementById(mode + '_is_admin').checked;
const siteSelection = document.getElementById(mode === 'add' ? 'siteSelectionGroup' : 'editSiteSelectionGroup');
siteSelection.style.display = isAdmin ? 'none' : 'block';
}
// Initial state
toggleSiteSelection('add');
// Modal schließen bei Klick außerhalb
document.getElementById('addUserModal').addEventListener('click', function(e) {
if (e.target === this) {
closeModal('addUserModal');
}
});
document.getElementById('editUserModal').addEventListener('click', function(e) {
if (e.target === this) {
closeModal('editUserModal');
}
});
</script>
</body>
</html>

1004
admin/vouchers.php Normal file

File diff suppressed because it is too large Load diff

13
config.php Normal file
View file

@ -0,0 +1,13 @@
<?php
// UniFi Voucher Management System - Configuration
define('DB_HOST', '');
define('DB_NAME', '');
define('DB_USER', '');
define('DB_PASS', '');
// Sitzungs-Einstellungen
define('SESSION_LIFETIME', 3600); // 1 Stunde
// Zeitzone
date_default_timezone_set('Europe/Berlin');

230
cron_sync.php Normal file
View file

@ -0,0 +1,230 @@
<?php
/**
* Cron-Script für automatische Voucher-Synchronisation
*
* Aufruf via URL: https://domain.de/cron_sync.php?token=DEIN_TOKEN
* Aufruf via CLI: php cron_sync.php DEIN_TOKEN
*
* Empfohlenes Cron-Intervall: Alle 30 Minuten
*/
// Fehlerbehandlung GANZ am Anfang
error_reporting(E_ALL);
ini_set('display_errors', 0);
// CLI oder Web?
$isCli = php_sapi_name() === 'cli';
// JSON-Header setzen bevor irgendwas anderes passiert
if (!$isCli) {
header('Content-Type: application/json');
}
// ============================================
// FUNKTIONEN ZUERST DEFINIEREN
// ============================================
function logMessage($message, $isCli) {
$timestamp = date('Y-m-d H:i:s');
$logLine = "[$timestamp] $message";
if ($isCli) {
echo $logLine . PHP_EOL;
}
}
function outputResponse($response, $isCli) {
if ($isCli) {
if ($response['success']) {
echo "SUCCESS: " . ($response['message'] ?? 'OK') . PHP_EOL;
if (isset($response['results'])) {
foreach ($response['results'] as $result) {
echo " - {$result['site_name']}: ";
if ($result['error']) {
echo "FEHLER - {$result['error']}" . PHP_EOL;
} else {
$s = $result['stats'];
echo "Gesamt: {$s['total']}, Neu: {$s['new']}, Aktualisiert: {$s['updated']}, Gültig: {$s['valid']}" . PHP_EOL;
}
}
}
} else {
echo "ERROR: " . $response['message'] . PHP_EOL;
}
} else {
echo json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
}
}
// ============================================
// ERROR HANDLER
// ============================================
register_shutdown_function(function() use ($isCli) {
$error = error_get_last();
if ($error && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])) {
$response = [
'success' => false,
'message' => 'Fatal Error: ' . $error['message'],
'file' => $error['file'],
'line' => $error['line']
];
outputResponse($response, $isCli);
}
});
set_exception_handler(function($e) use ($isCli) {
$response = [
'success' => false,
'message' => 'Exception: ' . $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine()
];
outputResponse($response, $isCli);
exit;
});
// ============================================
// INCLUDES LADEN
// ============================================
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/includes/Database.php';
require_once __DIR__ . '/includes/UniFiController.php';
$db = Database::getInstance();
// ============================================
// TOKEN VALIDIERUNG
// ============================================
$cronToken = $db->getSetting('cron_token', '');
// Token aus GET oder CLI-Argument holen
$providedToken = '';
if ($isCli && isset($argv[1])) {
$providedToken = $argv[1];
} else {
$providedToken = $_GET['token'] ?? '';
}
// Prüfen ob Token konfiguriert und korrekt ist
if (empty($cronToken)) {
outputResponse([
'success' => false,
'message' => 'Kein Cron-Token konfiguriert. Bitte im Admin-Bereich unter Einstellungen generieren.'
], $isCli);
exit;
}
if ($providedToken !== $cronToken) {
outputResponse([
'success' => false,
'message' => 'Ungültiger Token'
], $isCli);
exit;
}
// ============================================
// SYNCHRONISATION STARTEN
// ============================================
logMessage("Starte Voucher-Synchronisation...", $isCli);
$startTime = microtime(true);
$results = [];
$totalStats = [
'sites_processed' => 0,
'sites_failed' => 0,
'vouchers_total' => 0,
'vouchers_new' => 0,
'vouchers_updated' => 0,
'vouchers_valid' => 0,
'vouchers_used' => 0,
'vouchers_expired' => 0
];
try {
// Alle aktiven Sites abrufen
$sites = $db->fetchAll("SELECT * FROM sites WHERE is_active = 1");
if (empty($sites)) {
outputResponse([
'success' => true,
'message' => 'Keine aktiven Sites gefunden',
'results' => []
], $isCli);
exit;
}
logMessage("Gefunden: " . count($sites) . " aktive Site(s)", $isCli);
foreach ($sites as $site) {
logMessage("Synchronisiere Site: {$site['name']} ({$site['site_id']})...", $isCli);
$siteResult = [
'site_id' => $site['id'],
'site_name' => $site['name'],
'stats' => null,
'error' => null
];
try {
$controller = new UniFiController(
$site['unifi_controller_url'],
$site['unifi_username'],
$site['unifi_password'],
$site['site_id']
);
$stats = $controller->syncVouchersToDatabase($db, $site['id']);
$siteResult['stats'] = $stats;
// Gesamtstatistiken aktualisieren
$totalStats['sites_processed']++;
$totalStats['vouchers_total'] += $stats['total'];
$totalStats['vouchers_new'] += $stats['new'];
$totalStats['vouchers_updated'] += $stats['updated'];
$totalStats['vouchers_valid'] += $stats['valid'];
$totalStats['vouchers_used'] += $stats['used'];
$totalStats['vouchers_expired'] += $stats['expired'];
logMessage(" OK - {$stats['total']} Voucher(s), {$stats['new']} neu, {$stats['updated']} aktualisiert", $isCli);
} catch (Exception $e) {
$siteResult['error'] = $e->getMessage();
$totalStats['sites_failed']++;
logMessage(" FEHLER - " . $e->getMessage(), $isCli);
}
$results[] = $siteResult;
}
// Letzte Sync-Zeit speichern
$db->execute(
"INSERT INTO settings (setting_key, setting_value) VALUES ('last_cron_sync', NOW())
ON DUPLICATE KEY UPDATE setting_value = NOW()"
);
$duration = round(microtime(true) - $startTime, 2);
$response = [
'success' => true,
'message' => "Synchronisation abgeschlossen in {$duration}s",
'duration' => $duration,
'total' => $totalStats,
'results' => $results,
'timestamp' => date('Y-m-d H:i:s')
];
logMessage("Synchronisation abgeschlossen in {$duration}s", $isCli);
logMessage("Gesamt: {$totalStats['vouchers_total']} Voucher(s), {$totalStats['vouchers_new']} neu, {$totalStats['sites_failed']} Fehler", $isCli);
} catch (Exception $e) {
$response = [
'success' => false,
'message' => 'Kritischer Fehler: ' . $e->getMessage()
];
logMessage("KRITISCHER FEHLER: " . $e->getMessage(), $isCli);
}
outputResponse($response, $isCli);

72
cron_test.php Normal file
View file

@ -0,0 +1,72 @@
<?php
// Minimaler Test für Cron-Sync Debugging
header('Content-Type: application/json');
echo json_encode(['step' => 1, 'message' => 'PHP läuft']);
// Test 1: Config laden
try {
require_once __DIR__ . '/config.php';
echo "\n" . json_encode(['step' => 2, 'message' => 'Config geladen']);
} catch (Exception $e) {
echo "\n" . json_encode(['step' => 2, 'error' => $e->getMessage()]);
exit;
}
// Test 2: Database laden
try {
require_once __DIR__ . '/includes/Database.php';
echo "\n" . json_encode(['step' => 3, 'message' => 'Database.php geladen']);
} catch (Exception $e) {
echo "\n" . json_encode(['step' => 3, 'error' => $e->getMessage()]);
exit;
}
// Test 3: DB-Verbindung
try {
$db = Database::getInstance();
echo "\n" . json_encode(['step' => 4, 'message' => 'DB-Verbindung OK']);
} catch (Exception $e) {
echo "\n" . json_encode(['step' => 4, 'error' => $e->getMessage()]);
exit;
}
// Test 4: UniFiController laden
try {
require_once __DIR__ . '/includes/UniFiController.php';
echo "\n" . json_encode(['step' => 5, 'message' => 'UniFiController.php geladen']);
} catch (Exception $e) {
echo "\n" . json_encode(['step' => 5, 'error' => $e->getMessage()]);
exit;
}
// Test 5: Spalten prüfen
try {
$columns = $db->fetchAll("SHOW COLUMNS FROM vouchers");
$columnNames = array_column($columns, 'Field');
echo "\n" . json_encode(['step' => 6, 'message' => 'Voucher-Spalten', 'columns' => $columnNames]);
// Prüfen ob neue Spalten existieren
$required = ['status', 'used_count', 'expires_at', 'synced_from_unifi', 'last_sync'];
$missing = array_diff($required, $columnNames);
if (!empty($missing)) {
echo "\n" . json_encode(['step' => 7, 'warning' => 'Fehlende Spalten', 'missing' => array_values($missing)]);
} else {
echo "\n" . json_encode(['step' => 7, 'message' => 'Alle Spalten vorhanden']);
}
} catch (Exception $e) {
echo "\n" . json_encode(['step' => 6, 'error' => $e->getMessage()]);
exit;
}
// Test 6: Token prüfen
try {
$token = $db->getSetting('cron_token', '');
echo "\n" . json_encode(['step' => 8, 'message' => 'Token Status', 'has_token' => !empty($token)]);
} catch (Exception $e) {
echo "\n" . json_encode(['step' => 8, 'error' => $e->getMessage()]);
exit;
}
echo "\n" . json_encode(['final' => 'Alle Tests erfolgreich!']);

90
database.sql Normal file
View file

@ -0,0 +1,90 @@
-- UniFi Voucher Management System - Datenbankstruktur
CREATE TABLE IF NOT EXISTS `settings` (
`id` INT PRIMARY KEY AUTO_INCREMENT,
`setting_key` VARCHAR(100) UNIQUE NOT NULL,
`setting_value` TEXT,
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS `sites` (
`id` INT PRIMARY KEY AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL,
`site_id` VARCHAR(100) NOT NULL,
`unifi_controller_url` VARCHAR(255) NOT NULL,
`unifi_username` VARCHAR(100) NOT NULL,
`unifi_password` VARCHAR(255) NOT NULL,
`is_active` TINYINT(1) DEFAULT 1,
`public_access` TINYINT(1) DEFAULT 0,
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX `idx_active` (`is_active`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS `users` (
`id` INT PRIMARY KEY AUTO_INCREMENT,
`email` VARCHAR(255) UNIQUE NOT NULL,
`name` VARCHAR(255),
`password_hash` VARCHAR(255),
`is_admin` TINYINT(1) DEFAULT 0,
`is_active` TINYINT(1) DEFAULT 1,
`microsoft_id` VARCHAR(255) UNIQUE,
`last_login` TIMESTAMP NULL,
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX `idx_email` (`email`),
INDEX `idx_microsoft` (`microsoft_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS `user_site_access` (
`id` INT PRIMARY KEY AUTO_INCREMENT,
`user_id` INT NOT NULL,
`site_id` INT NOT NULL,
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE CASCADE,
FOREIGN KEY (`site_id`) REFERENCES `sites`(`id`) ON DELETE CASCADE,
UNIQUE KEY `unique_user_site` (`user_id`, `site_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS `vouchers` (
`id` INT PRIMARY KEY AUTO_INCREMENT,
`site_id` INT NOT NULL,
`user_id` INT,
`voucher_code` VARCHAR(50) NOT NULL,
`voucher_name` VARCHAR(255) NOT NULL,
`max_uses` INT NOT NULL,
`expire_minutes` INT NOT NULL,
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`unifi_voucher_id` VARCHAR(100),
`status` ENUM('valid', 'used', 'expired') DEFAULT 'valid',
`used_count` INT DEFAULT 0,
`expires_at` TIMESTAMP NULL,
`synced_from_unifi` TINYINT(1) DEFAULT 0,
`last_sync` TIMESTAMP NULL,
FOREIGN KEY (`site_id`) REFERENCES `sites`(`id`) ON DELETE CASCADE,
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE SET NULL,
INDEX `idx_site` (`site_id`),
INDEX `idx_created` (`created_at`),
INDEX `idx_unifi_id` (`unifi_voucher_id`),
INDEX `idx_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- Migration für bestehende Tabellen (falls bereits vorhanden):
-- ALTER TABLE vouchers ADD COLUMN `status` ENUM('valid', 'used', 'expired') DEFAULT 'valid';
-- ALTER TABLE vouchers ADD COLUMN `used_count` INT DEFAULT 0;
-- ALTER TABLE vouchers ADD COLUMN `expires_at` TIMESTAMP NULL;
-- ALTER TABLE vouchers ADD COLUMN `synced_from_unifi` TINYINT(1) DEFAULT 0;
-- ALTER TABLE vouchers ADD COLUMN `last_sync` TIMESTAMP NULL;
-- ALTER TABLE vouchers ADD INDEX `idx_unifi_id` (`unifi_voucher_id`);
-- ALTER TABLE vouchers ADD INDEX `idx_status` (`status`);
CREATE TABLE IF NOT EXISTS `sessions` (
`id` VARCHAR(128) PRIMARY KEY,
`user_id` INT NOT NULL,
`data` TEXT,
`expires_at` TIMESTAMP NOT NULL,
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE CASCADE,
INDEX `idx_expires` (`expires_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

201
includes/Auth.php Normal file
View file

@ -0,0 +1,201 @@
<?php
class Auth {
private $db;
public function __construct() {
try {
$this->db = Database::getInstance();
} catch (Exception $e) {
die("Datenbankverbindung fehlgeschlagen: " . $e->getMessage());
}
// Session-Konfiguration
if (session_status() === PHP_SESSION_NONE) {
ini_set('session.cookie_httponly', 1);
ini_set('session.use_strict_mode', 1);
ini_set('session.cookie_samesite', 'Lax');
if (!session_start()) {
die("Session konnte nicht gestartet werden");
}
}
}
// Benutzer einloggen
public function login($email, $password) {
$user = $this->db->fetchOne(
"SELECT * FROM users WHERE email = ? AND is_active = 1",
[$email]
);
if ($user && password_verify($password, $user['password_hash'])) {
$this->setUserSession($user);
$this->updateLastLogin($user['id']);
return true;
}
return false;
}
// Microsoft 365 Login
public function loginWithMicrosoft($microsoftUser) {
// Zuerst nach Microsoft ID suchen
$user = $this->db->fetchOne(
"SELECT * FROM users WHERE microsoft_id = ? AND is_active = 1",
[$microsoftUser['id']]
);
if (!$user) {
// Prüfen ob E-Mail bereits existiert (ohne Microsoft ID)
$existingUser = $this->db->fetchOne(
"SELECT * FROM users WHERE email = ? AND is_active = 1",
[$microsoftUser['email']]
);
if ($existingUser) {
// Benutzer existiert bereits ohne Microsoft ID - verknüpfen
$this->db->query(
"UPDATE users SET microsoft_id = ?, name = ? WHERE id = ?",
[$microsoftUser['id'], $microsoftUser['name'], $existingUser['id']]
);
$user = $this->db->fetchOne("SELECT * FROM users WHERE id = ?", [$existingUser['id']]);
} else {
// Komplett neuer Benutzer - anlegen
$userId = $this->db->execute(
"INSERT INTO users (email, name, microsoft_id, is_active) VALUES (?, ?, ?, 1)",
[$microsoftUser['email'], $microsoftUser['name'], $microsoftUser['id']]
);
$user = $this->db->fetchOne("SELECT * FROM users WHERE id = ?", [$userId]);
}
} else {
// Microsoft-Benutzer existiert bereits - Name aktualisieren falls geändert
$this->db->query(
"UPDATE users SET name = ? WHERE id = ?",
[$microsoftUser['name'], $user['id']]
);
}
$this->setUserSession($user);
$this->updateLastLogin($user['id']);
return true;
}
// Session setzen
private function setUserSession($user) {
$_SESSION['user_id'] = $user['id'];
$_SESSION['user_email'] = $user['email'];
$_SESSION['user_name'] = $user['name'];
$_SESSION['is_admin'] = (bool)$user['is_admin'];
$_SESSION['login_time'] = time();
// CSRF-Token generieren
if (!isset($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
}
// Letzten Login aktualisieren
private function updateLastLogin($userId) {
$this->db->query(
"UPDATE users SET last_login = NOW() WHERE id = ?",
[$userId]
);
}
// Ausloggen
public function logout() {
$_SESSION = [];
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time() - 3600, '/');
}
session_destroy();
}
// Prüfen ob eingeloggt
public function isLoggedIn() {
return isset($_SESSION['user_id']) && isset($_SESSION['login_time']);
}
// Prüfen ob Admin
public function isAdmin() {
return $this->isLoggedIn() && isset($_SESSION['is_admin']) && $_SESSION['is_admin'] === true;
}
// Aktuellen Benutzer abrufen
public function getCurrentUser() {
if (!$this->isLoggedIn()) {
return null;
}
return $this->db->fetchOne(
"SELECT * FROM users WHERE id = ?",
[$_SESSION['user_id']]
);
}
// Prüfen ob Benutzer Zugriff auf Site hat
public function hasAccessToSite($siteId) {
if ($this->isAdmin()) {
return true;
}
if (!$this->isLoggedIn()) {
return false;
}
$access = $this->db->fetchOne(
"SELECT id FROM user_site_access WHERE user_id = ? AND site_id = ?",
[$_SESSION['user_id'], $siteId]
);
return $access !== false;
}
// CSRF-Token validieren
public function validateCsrfToken($token) {
return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}
// CSRF-Token abrufen
public function getCsrfToken() {
if (!isset($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
return $_SESSION['csrf_token'];
}
// Benutzer registrieren (nur für Admins)
public function registerUser($email, $name, $password, $isAdmin = false) {
// Prüfen ob E-Mail bereits existiert
$existing = $this->db->fetchOne("SELECT id FROM users WHERE email = ?", [$email]);
if ($existing) {
return false;
}
$passwordHash = password_hash($password, PASSWORD_DEFAULT);
return $this->db->execute(
"INSERT INTO users (email, name, password_hash, is_admin, is_active) VALUES (?, ?, ?, ?, 1)",
[$email, $name, $passwordHash, $isAdmin ? 1 : 0]
);
}
// Admin-Zugriff erforderlich
public function requireAdmin() {
if (!$this->isAdmin()) {
header('Location: /index.php?error=access_denied');
exit;
}
}
// Login erforderlich
public function requireLogin() {
if (!$this->isLoggedIn()) {
header('Location: /login.php');
exit;
}
}
}

72
includes/Database.php Normal file
View file

@ -0,0 +1,72 @@
<?php
class Database {
private static $instance = null;
private $pdo;
private function __construct() {
try {
$this->pdo = new PDO(
"mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4",
DB_USER,
DB_PASS,
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false
]
);
} catch (PDOException $e) {
die("Datenbankverbindung fehlgeschlagen: " . $e->getMessage());
}
}
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
public function getConnection() {
return $this->pdo;
}
// Helper-Methode für Queries
public function query($sql, $params = []) {
$stmt = $this->pdo->prepare($sql);
$stmt->execute($params);
return $stmt;
}
// Helper für einzelnen Datensatz
public function fetchOne($sql, $params = []) {
$stmt = $this->query($sql, $params);
return $stmt->fetch();
}
// Helper für mehrere Datensätze
public function fetchAll($sql, $params = []) {
$stmt = $this->query($sql, $params);
return $stmt->fetchAll();
}
// Helper für Insert/Update mit Rückgabe der ID
public function execute($sql, $params = []) {
$this->query($sql, $params);
return $this->pdo->lastInsertId();
}
// Settings-Helper
public function getSetting($key, $default = null) {
$result = $this->fetchOne("SELECT setting_value FROM settings WHERE setting_key = ?", [$key]);
return $result ? $result['setting_value'] : $default;
}
public function setSetting($key, $value) {
$this->query(
"INSERT INTO settings (setting_key, setting_value) VALUES (?, ?)
ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)",
[$key, $value]
);
}
}

243
includes/Mailer.php Normal file
View file

@ -0,0 +1,243 @@
<?php
class Mailer {
private $db;
private $smtpEnabled;
private $smtpHost;
private $smtpPort;
private $smtpUsername;
private $smtpPassword;
private $smtpEncryption;
private $fromEmail;
private $fromName;
public function __construct() {
$this->db = Database::getInstance();
$this->loadSettings();
}
private function loadSettings() {
$this->smtpEnabled = $this->db->getSetting('smtp_enabled', '0') === '1';
$this->smtpHost = $this->db->getSetting('smtp_host', '');
$this->smtpPort = (int)$this->db->getSetting('smtp_port', '587');
$this->smtpUsername = $this->db->getSetting('smtp_username', '');
$this->smtpPassword = $this->db->getSetting('smtp_password', '');
$this->smtpEncryption = $this->db->getSetting('smtp_encryption', 'tls');
$this->fromEmail = $this->db->getSetting('smtp_from_email', 'noreply@' . $_SERVER['HTTP_HOST']);
$this->fromName = $this->db->getSetting('smtp_from_name', $this->db->getSetting('app_title', 'UniFi Voucher System'));
}
public function send($to, $subject, $body, $isHtml = false) {
if (!$this->smtpEnabled || empty($this->smtpHost)) {
// Fallback auf PHP mail()
return $this->sendWithPhpMail($to, $subject, $body);
}
return $this->sendWithSmtp($to, $subject, $body, $isHtml);
}
private function sendWithPhpMail($to, $subject, $body) {
$headers = "From: {$this->fromName} <{$this->fromEmail}>\r\n";
$headers .= "Reply-To: {$this->fromEmail}\r\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\r\n";
return mail($to, $subject, $body, $headers);
}
private function sendWithSmtp($to, $subject, $body, $isHtml = false) {
try {
// Verbindung aufbauen
$socket = $this->connectToSmtp();
// EHLO
$this->smtpCommand($socket, "EHLO " . $_SERVER['HTTP_HOST']);
// STARTTLS wenn nötig
if ($this->smtpEncryption === 'tls') {
$this->smtpCommand($socket, "STARTTLS");
stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
$this->smtpCommand($socket, "EHLO " . $_SERVER['HTTP_HOST']);
}
// AUTH LOGIN
$this->smtpCommand($socket, "AUTH LOGIN");
$this->smtpCommand($socket, base64_encode($this->smtpUsername));
$this->smtpCommand($socket, base64_encode($this->smtpPassword));
// MAIL FROM
$this->smtpCommand($socket, "MAIL FROM:<{$this->fromEmail}>");
// RCPT TO
$this->smtpCommand($socket, "RCPT TO:<{$to}>");
// DATA
$this->smtpCommand($socket, "DATA");
// Headers
$message = "From: {$this->fromName} <{$this->fromEmail}>\r\n";
$message .= "To: {$to}\r\n";
$message .= "Subject: =?UTF-8?B?" . base64_encode($subject) . "?=\r\n";
$message .= "MIME-Version: 1.0\r\n";
if ($isHtml) {
$message .= "Content-Type: text/html; charset=UTF-8\r\n";
} else {
$message .= "Content-Type: text/plain; charset=UTF-8\r\n";
}
$message .= "\r\n";
// Body - bei Plain Text Zeilenumbrüche konvertieren
if (!$isHtml) {
$body = nl2br($body, false); // Für Plain Text
$body = str_replace('<br>', "\r\n", $body);
}
$message .= $body;
$message .= "\r\n.\r\n";
fwrite($socket, $message);
$response = fgets($socket);
// QUIT
$this->smtpCommand($socket, "QUIT");
fclose($socket);
return strpos($response, '250') === 0;
} catch (Exception $e) {
error_log("SMTP Error: " . $e->getMessage());
return false;
}
}
private function connectToSmtp() {
$context = stream_context_create([
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
]
]);
if ($this->smtpEncryption === 'ssl') {
$host = 'ssl://' . $this->smtpHost;
} else {
$host = $this->smtpHost;
}
$socket = stream_socket_client(
$host . ':' . $this->smtpPort,
$errno,
$errstr,
30,
STREAM_CLIENT_CONNECT,
$context
);
if (!$socket) {
throw new Exception("SMTP Connection failed: $errstr ($errno)");
}
// Willkommensnachricht lesen
fgets($socket);
return $socket;
}
private function smtpCommand($socket, $command) {
fwrite($socket, $command . "\r\n");
$response = fgets($socket);
// Prüfen auf Fehler (4xx oder 5xx)
if (preg_match('/^[45]/', $response)) {
throw new Exception("SMTP Error: $response");
}
return $response;
}
// Vordefinierte E-Mail-Templates
public function sendVoucherEmail($to, $voucherCode, $siteName, $maxUses) {
$appTitle = $this->db->getSetting('app_title', 'UniFi Voucher System');
$instructionHeader = $this->db->getSetting('instruction_header', '');
$instructionText = $this->db->getSetting('instruction_text', '');
// System-URL aus Einstellungen oder automatisch erkennen
$systemUrl = $this->db->getSetting('system_url', '');
if (empty($systemUrl)) {
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'];
$scriptPath = dirname($_SERVER['SCRIPT_NAME']);
$scriptPath = $scriptPath === '/' ? '' : $scriptPath;
$systemUrl = $protocol . '://' . $host . $scriptPath;
}
// Template aus Datenbank laden
$subjectTemplate = $this->db->getSetting('email_voucher_subject', '{APP_TITLE} - Ihr WLAN-Zugang');
$bodyTemplate = $this->db->getSetting('email_voucher_body', "Hallo,\n\nIhr WLAN-Zugangscode lautet:\n\n<strong>{VOUCHER_CODE}</strong>\n\nGültigkeit: 8 Stunden ab Erstellung\nMaximale Geräte: {MAX_USES}\nStandort: {SITE_NAME}\n\n{INSTRUCTIONS}\n\nMit freundlichen Grüßen\n{APP_TITLE}");
// Anleitung formatieren
$instructions = '';
if ($instructionText) {
$instructions = $instructionHeader . "\n" . $instructionText;
}
// Platzhalter ersetzen
$placeholders = [
'{VOUCHER_CODE}' => $voucherCode,
'{SITE_NAME}' => $siteName,
'{MAX_USES}' => $maxUses,
'{APP_TITLE}' => $appTitle,
'{INSTRUCTIONS}' => $instructions,
'{SYSTEM_URL}' => $systemUrl
];
$subject = str_replace(array_keys($placeholders), array_values($placeholders), $subjectTemplate);
$body = str_replace(array_keys($placeholders), array_values($placeholders), $bodyTemplate);
// HTML oder Plain Text prüfen
$isHtml = strip_tags($body) !== $body;
return $this->send($to, $subject, $body, $isHtml);
}
public function sendUserNotification($to, $userName, $changes) {
$appTitle = $this->db->getSetting('app_title', 'UniFi Voucher System');
// System-URL aus Einstellungen oder automatisch erkennen
$systemUrl = $this->db->getSetting('system_url', '');
if (empty($systemUrl)) {
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'];
$scriptPath = dirname($_SERVER['SCRIPT_NAME']);
$scriptPath = $scriptPath === '/' ? '' : $scriptPath;
$systemUrl = $protocol . '://' . $host . $scriptPath;
}
// Template aus Datenbank laden
$subjectTemplate = $this->db->getSetting('email_user_notification_subject', '{APP_TITLE} - Ihre Berechtigungen wurden geändert');
$bodyTemplate = $this->db->getSetting('email_user_notification_body', "Hallo {USER_NAME},\n\nEin Administrator hat Ihre Berechtigungen im {APP_TITLE} geändert:\n\n{CHANGES}\n\nSie können sich unter folgender Adresse anmelden:\n{SYSTEM_URL}\n\nMit freundlichen Grüßen\n{APP_TITLE}");
// Änderungen formatieren
$changesText = '';
foreach ($changes as $change) {
$changesText .= "$change\n";
}
// Platzhalter ersetzen
$placeholders = [
'{USER_NAME}' => $userName,
'{CHANGES}' => $changesText,
'{APP_TITLE}' => $appTitle,
'{SYSTEM_URL}' => $systemUrl
];
$subject = str_replace(array_keys($placeholders), array_values($placeholders), $subjectTemplate);
$body = str_replace(array_keys($placeholders), array_values($placeholders), $bodyTemplate);
// HTML oder Plain Text prüfen
$isHtml = strip_tags($body) !== $body;
return $this->send($to, $subject, $body, $isHtml);
}
}

View file

@ -0,0 +1,329 @@
<?php
class UniFiController {
private $controllerUrl;
private $username;
private $password;
private $siteId;
private $cookieFile;
public function __construct($controllerUrl, $username, $password, $siteId) {
$this->controllerUrl = rtrim($controllerUrl, '/');
$this->username = $username;
$this->password = $password;
$this->siteId = $siteId;
$this->cookieFile = tempnam(sys_get_temp_dir(), 'UNIFI_');
}
public function __destruct() {
if (file_exists($this->cookieFile)) {
unlink($this->cookieFile);
}
}
// Login zum Controller
private function login() {
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $this->controllerUrl . "/api/login",
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode([
'username' => $this->username,
'password' => $this->password
]),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_COOKIEJAR => $this->cookieFile,
CURLOPT_COOKIEFILE => $this->cookieFile,
CURLOPT_HTTPHEADER => ['Content-Type: application/json']
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
throw new Exception("Login fehlgeschlagen: HTTP $httpCode");
}
$data = json_decode($response, true);
if (!isset($data['meta']['rc']) || $data['meta']['rc'] !== 'ok') {
throw new Exception("Login fehlgeschlagen: Ungültige Antwort");
}
return true;
}
// API-Request ausführen
private function apiRequest($endpoint, $data = null, $method = 'POST') {
$this->login();
$ch = curl_init();
$url = $this->controllerUrl . $endpoint;
$options = [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_COOKIEFILE => $this->cookieFile,
CURLOPT_HTTPHEADER => ['Content-Type: application/json']
];
if ($method === 'POST' && $data !== null) {
$options[CURLOPT_POST] = true;
$options[CURLOPT_POSTFIELDS] = json_encode($data);
}
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
throw new Exception("cURL Fehler: $error");
}
if ($httpCode !== 200) {
throw new Exception("API Request fehlgeschlagen: HTTP $httpCode");
}
return json_decode($response, true);
}
// Voucher erstellen
public function createVoucher($voucherName, $maxUses, $expireMinutes = 480) {
$data = [
'cmd' => 'create-voucher',
'expire' => (int)$expireMinutes,
'n' => 1,
'note' => $voucherName,
'quota' => (int)$maxUses
];
$response = $this->apiRequest("/api/s/{$this->siteId}/cmd/hotspot", $data);
if (!isset($response['data'][0]['create_time'])) {
throw new Exception("Voucher konnte nicht erstellt werden");
}
// Voucher-Code abrufen
$vouchers = $this->getVouchers();
if (empty($vouchers)) {
throw new Exception("Voucher-Code konnte nicht abgerufen werden");
}
// Neuesten Voucher zurückgeben
$latestVoucher = reset($vouchers);
return [
'code' => $latestVoucher['code'],
'formatted_code' => $this->formatVoucherCode($latestVoucher['code']),
'unifi_id' => $latestVoucher['_id'] ?? null,
'create_time' => $latestVoucher['create_time'] ?? null
];
}
// Alle Voucher abrufen
public function getVouchers() {
$response = $this->apiRequest("/api/s/{$this->siteId}/stat/voucher");
return $response['data'] ?? [];
}
// Voucher mit formatierten Details abrufen
public function getVouchersWithDetails() {
$vouchers = $this->getVouchers();
$result = [];
foreach ($vouchers as $voucher) {
$createTime = isset($voucher['create_time']) ? $voucher['create_time'] : 0;
$duration = isset($voucher['duration']) ? $voucher['duration'] : 0; // in Minuten
$expireTime = $createTime + ($duration * 60);
$now = time();
// Status bestimmen
$status = 'valid';
$usedCount = isset($voucher['used']) ? $voucher['used'] : 0;
$quota = isset($voucher['quota']) ? $voucher['quota'] : 0;
if ($now > $expireTime) {
$status = 'expired';
} elseif ($quota > 0 && $usedCount >= $quota) {
$status = 'used';
}
$result[] = [
'_id' => $voucher['_id'] ?? '',
'code' => $voucher['code'] ?? '',
'formatted_code' => $this->formatVoucherCode($voucher['code'] ?? ''),
'note' => $voucher['note'] ?? '',
'quota' => $quota,
'used' => $usedCount,
'duration' => $duration,
'create_time' => $createTime,
'expire_time' => $expireTime,
'status' => $status,
'status_expires' => isset($voucher['status_expires']) ? $voucher['status_expires'] : null,
'for_hotspot' => isset($voucher['for_hotspot']) ? $voucher['for_hotspot'] : false,
'qos_overwrite' => isset($voucher['qos_overwrite']) ? $voucher['qos_overwrite'] : false,
'qos_usage_quota' => isset($voucher['qos_usage_quota']) ? $voucher['qos_usage_quota'] : null,
'qos_rate_max_up' => isset($voucher['qos_rate_max_up']) ? $voucher['qos_rate_max_up'] : null,
'qos_rate_max_down' => isset($voucher['qos_rate_max_down']) ? $voucher['qos_rate_max_down'] : null
];
}
// Nach Erstellungsdatum sortieren (neueste zuerst)
usort($result, function($a, $b) {
return $b['create_time'] - $a['create_time'];
});
return $result;
}
// Voucher-Code formatieren (xxxxx-xxxxx-xxxxx)
private function formatVoucherCode($code) {
$chunks = str_split($code, 5);
return implode('-', $chunks);
}
// Voucher löschen
public function deleteVoucher($voucherId) {
$data = [
'cmd' => 'delete-voucher',
'_id' => $voucherId
];
$response = $this->apiRequest("/api/s/{$this->siteId}/cmd/hotspot", $data);
return isset($response['meta']['rc']) && $response['meta']['rc'] === 'ok';
}
// Verbindung testen
public static function testConnection($controllerUrl, $username, $password, $siteId) {
try {
$controller = new self($controllerUrl, $username, $password, $siteId);
$controller->login();
return true;
} catch (Exception $e) {
return $e->getMessage();
}
}
/**
* Synchronisiert alle Voucher vom UniFi Controller in die Datenbank
* @param Database $db Datenbank-Instanz
* @param int $dbSiteId Die Site-ID in der lokalen Datenbank
* @return array Statistiken über die Synchronisation
*/
public function syncVouchersToDatabase($db, $dbSiteId) {
$vouchers = $this->getVouchersWithDetails();
$stats = [
'total' => count($vouchers),
'new' => 0,
'updated' => 0,
'deleted' => 0,
'valid' => 0,
'used' => 0,
'expired' => 0
];
// Alle aktuellen UniFi-IDs sammeln
$unifiIds = [];
foreach ($vouchers as $voucher) {
$unifiIds[] = $voucher['_id'];
// Status zählen
$stats[$voucher['status']]++;
// Prüfen ob Voucher bereits existiert
$existing = $db->fetchOne(
"SELECT id, status, used_count FROM vouchers WHERE unifi_voucher_id = ? AND site_id = ?",
[$voucher['_id'], $dbSiteId]
);
$expiresAt = date('Y-m-d H:i:s', $voucher['expire_time']);
$createdAt = date('Y-m-d H:i:s', $voucher['create_time']);
if ($existing) {
// Voucher aktualisieren
$db->execute(
"UPDATE vouchers SET
status = ?,
used_count = ?,
expires_at = ?,
last_sync = NOW()
WHERE id = ?",
[$voucher['status'], $voucher['used'], $expiresAt, $existing['id']]
);
$stats['updated']++;
} else {
// Neuen Voucher einfügen
$db->execute(
"INSERT INTO vouchers
(site_id, voucher_code, voucher_name, max_uses, expire_minutes,
unifi_voucher_id, status, used_count, expires_at, created_at,
synced_from_unifi, last_sync)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, NOW())",
[
$dbSiteId,
$voucher['formatted_code'],
$voucher['note'] ?: 'Importiert aus UniFi',
$voucher['quota'],
$voucher['duration'],
$voucher['_id'],
$voucher['status'],
$voucher['used'],
$expiresAt,
$createdAt
]
);
$stats['new']++;
}
}
// Voucher die nicht mehr im Controller existieren als gelöscht markieren
if (!empty($unifiIds)) {
$placeholders = implode(',', array_fill(0, count($unifiIds), '?'));
$params = array_merge($unifiIds, [$dbSiteId]);
// Alle Voucher mit UniFi-ID die nicht mehr existieren auf "expired" setzen
$deleted = $db->execute(
"UPDATE vouchers SET status = 'expired', last_sync = NOW()
WHERE unifi_voucher_id IS NOT NULL
AND unifi_voucher_id NOT IN ($placeholders)
AND site_id = ?
AND status != 'expired'",
$params
);
$stats['deleted'] = $deleted;
}
return $stats;
}
/**
* Holt Live-Statistiken für das Dashboard
* @return array
*/
public function getLiveStats() {
$vouchers = $this->getVouchersWithDetails();
$stats = [
'total' => count($vouchers),
'valid' => 0,
'used' => 0,
'expired' => 0,
'vouchers' => $vouchers
];
foreach ($vouchers as $voucher) {
$stats[$voucher['status']]++;
}
return $stats;
}
}

654
index.php Normal file
View file

@ -0,0 +1,654 @@
<?php
// Error Reporting für Debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/includes/Database.php';
require_once __DIR__ . '/includes/Auth.php';
require_once __DIR__ . '/includes/UniFiController.php';
require_once __DIR__ . '/includes/Mailer.php';
$auth = new Auth();
$db = Database::getInstance();
$mailer = new Mailer();
// Settings laden
$appTitle = $db->getSetting('app_title', 'UniFi Voucher System');
$logoUrl = $db->getSetting('logo_url', '');
$instructionHeader = $db->getSetting('instruction_header', 'So verwenden Sie Ihren Code');
$instructionText = $db->getSetting('instruction_text', '');
$publicAccess = $db->getSetting('public_access', 0);
$printTemplate = $db->getSetting('print_template', '<div style="text-align: center; padding: 40px;">
<h1>{APP_TITLE}</h1>
<h2>WLAN Zugangscode</h2>
<div style="font-size: 48px; font-weight: bold; margin: 30px 0; font-family: monospace; letter-spacing: 4px;">{VOUCHER_CODE}</div>
<p><strong>Gültig bis:</strong> {EXPIRY_DATE} um {EXPIRY_TIME} Uhr</p>
<p><strong>Standort:</strong> {SITE_NAME}</p>
<p><strong>Maximale Geräte:</strong> {MAX_USES}</p>
<hr style="margin: 30px 0;">
<div style="font-size: 14px; text-align: left;">
{INSTRUCTIONS}
</div>
</div>');
// Prüfen ob Login erforderlich - aber nur wenn nicht auf login.php
if (!$publicAccess && !$auth->isLoggedIn()) {
header('Location: login.php');
exit;
}
$error = '';
$success = '';
$voucherCode = '';
$voucherCreated = false;
$voucherData = [];
// Sites abrufen
if ($auth->isLoggedIn()) {
if ($auth->isAdmin()) {
$sites = $db->fetchAll("SELECT * FROM sites WHERE is_active = 1 ORDER BY name");
} else {
$sites = $db->fetchAll(
"SELECT s.* FROM sites s
INNER JOIN user_site_access usa ON s.id = usa.site_id
WHERE s.is_active = 1 AND usa.user_id = ?
ORDER BY s.name",
[$_SESSION['user_id']]
);
}
} else {
// Öffentlicher Zugriff - nur Sites mit public_access
$sites = $db->fetchAll("SELECT * FROM sites WHERE is_active = 1 AND public_access = 1 ORDER BY name");
}
// Voucher erstellen
// WICHTIG: create_voucher kommt jetzt aus einem hidden input, nicht vom Button (disabled Buttons werden teils nicht gesendet)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_voucher'])) {
if (!$publicAccess && !$auth->isLoggedIn()) {
$error = 'Sie müssen angemeldet sein';
} elseif ($auth->isLoggedIn() && !$auth->validateCsrfToken($_POST['csrf_token'] ?? '')) {
$error = 'Ungültiges Sicherheits-Token';
} else {
try {
$siteId = (int)($_POST['site_id'] ?? 0);
$voucherName = trim((string)($_POST['voucher_name'] ?? ''));
$maxUses = (int)($_POST['max_uses'] ?? 0);
$sendEmail = isset($_POST['send_email']) && !empty($_POST['recipient_email']);
$recipientEmail = trim((string)($_POST['recipient_email'] ?? ''));
// Validierung
if (empty($voucherName)) {
throw new Exception('Bitte geben Sie einen Voucher-Namen ein');
}
if ($maxUses < 1 || $maxUses > 10) {
throw new Exception('Anzahl der Geräte muss zwischen 1 und 10 liegen');
}
if ($siteId <= 0) {
throw new Exception('Bitte wählen Sie einen Standort');
}
if ($sendEmail && !filter_var($recipientEmail, FILTER_VALIDATE_EMAIL)) {
throw new Exception('Ungültige E-Mail-Adresse');
}
// Site-Zugriff prüfen
if ($auth->isLoggedIn() && !$auth->hasAccessToSite($siteId)) {
throw new Exception('Keine Berechtigung für diese Site');
}
// Site-Daten abrufen
$site = $db->fetchOne("SELECT * FROM sites WHERE id = ? AND is_active = 1", [$siteId]);
if (!$site) {
throw new Exception('Site nicht gefunden');
}
// Voucher-Namen formatieren
$datum = date('Y-m-d');
$fullVoucherName = $datum . '_' . $voucherName;
// UniFi Controller initialisieren
$controller = new UniFiController(
$site['unifi_controller_url'],
$site['unifi_username'],
$site['unifi_password'],
$site['site_id']
);
// Voucher erstellen
$voucher = $controller->createVoucher($fullVoucherName, $maxUses, 480);
if (!is_array($voucher) || empty($voucher['formatted_code']) || empty($voucher['code'])) {
throw new Exception('UniFi hat keinen gültigen Voucher zurückgegeben');
}
$voucherCode = $voucher['formatted_code'];
// In Datenbank speichern
$userId = $auth->isLoggedIn() ? ($_SESSION['user_id'] ?? null) : null;
$db->execute(
"INSERT INTO vouchers (site_id, user_id, voucher_code, voucher_name, max_uses, expire_minutes, unifi_voucher_id)
VALUES (?, ?, ?, ?, ?, 480, ?)",
[$siteId, $userId, $voucher['code'], $fullVoucherName, $maxUses, ($voucher['unifi_id'] ?? null)]
);
// Voucher-Daten für Druck speichern
$expiryTimestamp = time() + (480 * 60);
$voucherData = [
'code' => $voucherCode,
'site_name' => $site['name'],
'max_uses' => $maxUses,
'expiry_date' => date('d.m.Y', $expiryTimestamp),
'expiry_time' => date('H:i', $expiryTimestamp)
];
// E-Mail versenden falls gewünscht
if ($sendEmail && !empty($recipientEmail)) {
if ($mailer->sendVoucherEmail($recipientEmail, $voucherCode, $site['name'], $maxUses)) {
$success .= ' E-Mail wurde erfolgreich versendet!';
} else {
$success .= ' (E-Mail konnte nicht versendet werden)';
}
}
$voucherCreated = true;
$success = 'Voucher erfolgreich erstellt!' . ($sendEmail ? ' E-Mail wurde versendet.' : '');
} catch (Exception $e) {
$error = 'Fehler: ' . $e->getMessage();
}
}
}
$currentUser = $auth->isLoggedIn() ? $auth->getCurrentUser() : null;
// Auto-select wenn nur eine Site
$autoSelectSite = (count($sites) === 1) ? $sites[0]['id'] : 0;
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= htmlspecialchars($appTitle) ?></title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
padding: 20px;
}
.header {
max-width: 1200px;
margin: 0 auto 30px;
display: flex;
justify-content: space-between;
align-items: center;
background: rgba(255,255,255,0.15);
backdrop-filter: blur(10px);
padding: 15px 25px;
border-radius: 15px;
}
.header-left {
display: flex;
align-items: center;
gap: 20px;
}
.header-logo { max-height: 40px; }
.header-title {
color: white;
font-size: 20px;
font-weight: 600;
}
.header-right {
display: flex;
align-items: center;
gap: 15px;
}
.user-info { color: white; font-size: 14px; }
.btn-header {
background: white;
color: #667eea;
padding: 10px 20px;
border-radius: 8px;
text-decoration: none;
font-weight: 500;
font-size: 14px;
transition: all 0.3s;
border: none;
cursor: pointer;
}
.btn-header:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0,0,0,0.2);
}
.container {
max-width: 600px;
margin: 0 auto;
background: white;
border-radius: 20px;
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
padding: 40px;
}
.logo {
max-width: 250px;
display: block;
margin: 0 auto 30px;
}
h1 {
text-align: center;
color: #333;
margin-bottom: 30px;
font-size: 28px;
}
.alert {
padding: 14px;
border-radius: 10px;
margin-bottom: 25px;
font-size: 14px;
}
.alert-error {
background: #fee;
border: 1px solid #fcc;
color: #c33;
}
.alert-success {
background: #efe;
border: 1px solid #cfc;
color: #3c3;
}
.form-group { margin-bottom: 20px; }
label {
display: block;
margin-bottom: 8px;
color: #555;
font-weight: 500;
font-size: 14px;
}
input[type="text"],
input[type="number"],
input[type="email"],
select {
width: 100%;
padding: 14px;
border: 2px solid #e0e0e0;
border-radius: 10px;
font-size: 15px;
transition: all 0.3s;
}
input:focus, select:focus {
outline: none;
border-color: #667eea;
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
.btn {
width: 100%;
padding: 16px;
background: #667eea;
color: white;
border: none;
border-radius: 10px;
font-size: 16px;
font-weight: 600;
cursor: pointer;
transition: all 0.3s;
}
.btn:hover {
background: #5568d3;
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}
.btn:disabled {
background: #ccc;
cursor: not-allowed;
transform: none;
}
.voucher-result {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 30px;
border-radius: 15px;
text-align: center;
margin-bottom: 25px;
}
.voucher-code {
font-size: 32px;
font-weight: bold;
letter-spacing: 2px;
margin: 20px 0;
font-family: 'Courier New', monospace;
}
.voucher-info {
font-size: 14px;
opacity: 0.9;
margin-top: 15px;
}
.instruction-box {
background: #f8f9fa;
padding: 20px;
border-radius: 10px;
margin-top: 25px;
}
.instruction-box h3 {
color: #333;
margin-bottom: 10px;
font-size: 16px;
}
.instruction-box p {
color: #666;
line-height: 1.6;
font-size: 14px;
}
.empty-state {
text-align: center;
padding: 40px;
color: #999;
}
.empty-state svg {
width: 80px;
height: 80px;
margin-bottom: 20px;
opacity: 0.3;
}
/* Verbessertes E-Mail Option Design */
.email-option {
background: #f8f9fa;
border: 2px solid #e0e0e0;
border-radius: 12px;
padding: 20px;
margin: 20px 0;
transition: all 0.3s ease;
}
.email-option.active {
background: linear-gradient(135deg, #e7f3ff 0%, #f0e7ff 100%);
border-color: #667eea;
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
}
.email-checkbox-wrapper {
display: flex;
align-items: center;
gap: 12px;
cursor: pointer;
margin-bottom: 0;
}
.email-checkbox-wrapper input[type="checkbox"] {
width: 20px;
height: 20px;
cursor: pointer;
margin: 0;
accent-color: #667eea;
}
.email-checkbox-wrapper label {
margin: 0;
cursor: pointer;
font-size: 16px;
font-weight: 600;
color: #333;
display: flex;
align-items: center;
gap: 8px;
}
.email-input-wrapper {
max-height: 0;
overflow: hidden;
opacity: 0;
transition: all 0.3s ease;
margin-top: 0;
}
.email-input-wrapper.show {
max-height: 200px;
opacity: 1;
margin-top: 15px;
}
.email-input-wrapper input {
background: white;
border: 2px solid #e0e0e0;
}
.email-input-wrapper input:focus {
border-color: #667eea;
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
.print-button {
background: white;
color: #667eea;
border: 2px solid #667eea;
margin-top: 10px;
display: inline-flex;
align-items: center;
justify-content: center;
gap: 8px;
}
.print-button:hover {
background: #667eea;
color: white;
}
.print-button svg {
width: 20px;
height: 20px;
}
/* Print Styles */
@media print {
body * { visibility: hidden; }
#printArea, #printArea * { visibility: visible; }
#printArea {
position: absolute;
left: 0;
top: 0;
width: 100%;
background: white;
}
.btn, .header, form, .no-print { display: none !important; }
}
</style>
</head>
<body>
<?php if ($currentUser): ?>
<div class="header no-print">
<div class="header-left">
<div class="header-title">👋 Hallo, <?= htmlspecialchars($currentUser['name']) ?></div>
</div>
<div class="header-right">
<?php if ($auth->isAdmin()): ?>
<a href="admin/" class="btn-header">⚙️ Administration</a>
<?php endif; ?>
<a href="logout.php" class="btn-header">Abmelden</a>
</div>
</div>
<?php elseif ($publicAccess): ?>
<div class="header no-print">
<div class="header-left">
<div class="header-title"><?= htmlspecialchars($appTitle) ?></div>
</div>
<div class="header-right">
<a href="login.php" class="btn-header">
<span style="margin-right: 5px;">🔐</span> Anmelden
</a>
</div>
</div>
<?php endif; ?>
<div class="container">
<?php if ($logoUrl && !$voucherCreated): ?>
<img src="<?= htmlspecialchars($logoUrl) ?>" alt="Logo" class="logo">
<?php endif; ?>
<h1><?= htmlspecialchars($appTitle) ?></h1>
<?php if ($error): ?>
<div class="alert alert-error"><?= htmlspecialchars($error) ?></div>
<?php endif; ?>
<?php if ($voucherCreated): ?>
<div id="printArea">
<div class="voucher-result">
<div style="font-size: 18px; margin-bottom: 10px;"> Ihr Zugangs-Code</div>
<div class="voucher-code"><?= htmlspecialchars($voucherCode) ?></div>
<div class="voucher-info">
Der Code ist 8 Stunden ab Erstellung gültig
</div>
</div>
<?php if ($instructionHeader || $instructionText): ?>
<div class="instruction-box">
<?php if ($instructionHeader): ?>
<h3><?= htmlspecialchars($instructionHeader) ?></h3>
<?php endif; ?>
<?php if ($instructionText): ?>
<div><?= $instructionText ?></div>
<?php endif; ?>
</div>
<?php endif; ?>
</div>
<form method="get" class="no-print">
<button type="submit" class="btn">Weiteren Code erstellen</button>
</form>
<button onclick="window.print()" class="btn print-button no-print">
<svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z"/>
</svg>
Code ausdrucken
</button>
<?php elseif (empty($sites)): ?>
<div class="empty-state">
<svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4"></path>
</svg>
<p>Keine verfügbaren Sites gefunden.<br>
<?php if ($auth->isAdmin()): ?>
<a href="admin/" style="color: #667eea;">Klicken Sie hier, um Sites anzulegen</a>
<?php else: ?>
Bitte kontaktieren Sie Ihren Administrator.
<?php endif; ?>
</p>
</div>
<?php else: ?>
<form method="post" id="voucherForm">
<!-- FIX: Trigger-Feld kommt nicht mehr vom Submit-Button -->
<input type="hidden" name="create_voucher" value="1">
<?php if ($auth->isLoggedIn()): ?>
<input type="hidden" name="csrf_token" value="<?= $auth->getCsrfToken() ?>">
<?php endif; ?>
<div class="form-group">
<label for="voucher_name">Voucher-Name *</label>
<input type="text" id="voucher_name" name="voucher_name"
placeholder="z.B. Besprechung UL, Vertretername Firma XY" required>
</div>
<div class="form-group">
<label for="max_uses">Wie viele Geräte dürfen sich einloggen? *</label>
<input type="number" id="max_uses" name="max_uses"
min="1" max="10" value="1" required>
</div>
<div class="form-group">
<label for="site_id">Standort *</label>
<select id="site_id" name="site_id" required>
<?php if (count($sites) > 1): ?>
<option value="">Bitte wählen...</option>
<?php endif; ?>
<?php foreach ($sites as $site): ?>
<option value="<?= (int)$site['id'] ?>" <?= ($autoSelectSite == $site['id']) ? 'selected' : '' ?>>
<?= htmlspecialchars($site['name']) ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="email-option" id="email-option-box">
<div class="email-checkbox-wrapper">
<input type="checkbox" id="send_email" name="send_email" onchange="toggleEmailField()">
<label for="send_email">
<svg width="20" height="20" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/>
</svg>
Code per E-Mail versenden
</label>
</div>
<div class="email-input-wrapper" id="email_field">
<label for="recipient_email">E-Mail-Adresse des Empfängers</label>
<input type="email" id="recipient_email" name="recipient_email" placeholder="gast@example.com">
</div>
</div>
<!-- Button ohne name=create_voucher, damit disabled keinen Einfluss hat -->
<button type="submit" class="btn" id="submitBtn">
Voucher erstellen
</button>
</form>
<?php if ($instructionHeader || $instructionText): ?>
<div class="instruction-box">
<?php if ($instructionHeader): ?>
<h3><?= htmlspecialchars($instructionHeader) ?></h3>
<?php endif; ?>
<?php if ($instructionText): ?>
<div><?= $instructionText ?></div>
<?php endif; ?>
</div>
<?php endif; ?>
<?php endif; ?>
</div>
<script>
function toggleEmailField() {
const checkbox = document.getElementById('send_email');
const emailField = document.getElementById('email_field');
const emailBox = document.getElementById('email-option-box');
const emailInput = document.getElementById('recipient_email');
if (!checkbox || !emailField || !emailBox || !emailInput) return;
if (checkbox.checked) {
emailField.classList.add('show');
emailBox.classList.add('active');
emailInput.required = true;
setTimeout(() => emailInput.focus(), 300);
} else {
emailField.classList.remove('show');
emailBox.classList.remove('active');
emailInput.required = false;
}
}
// Initialzustand (z.B. nach Browser-Autofill)
document.addEventListener('DOMContentLoaded', () => {
toggleEmailField();
});
// Form Submit mit Loading State + Double-Submit-Schutz
document.getElementById('voucherForm')?.addEventListener('submit', function(e) {
const btn = document.getElementById('submitBtn');
if (!btn) return;
// falls schon disabled: Double-Submit verhindern
if (btn.disabled) {
e.preventDefault();
return;
}
btn.disabled = true;
btn.innerHTML = '<span style="display: inline-block; animation: spin 1s linear infinite;">⏳</span> Erstelle Voucher...';
});
</script>
<style>
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
</style>
</body>
</html>

461
install.php Normal file
View file

@ -0,0 +1,461 @@
<?php
session_start();
// Prüfen ob bereits installiert
if (file_exists(__DIR__ . '/config.php') && !isset($_GET['reinstall'])) {
die('System bereits installiert. Wenn Sie neu installieren möchten, löschen Sie die config.php oder rufen Sie install.php?reinstall=1 auf.');
}
$step = isset($_POST['step']) ? (int)$_POST['step'] : 1;
$errors = [];
$success = false;
// Step 1: Datenbankverbindung testen
if ($step === 2 && $_SERVER['REQUEST_METHOD'] === 'POST') {
$db_host = $_POST['db_host'] ?? '';
$db_name = $_POST['db_name'] ?? '';
$db_user = $_POST['db_user'] ?? '';
$db_pass = $_POST['db_pass'] ?? '';
try {
$pdo = new PDO("mysql:host=$db_host;charset=utf8mb4", $db_user, $db_pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Datenbank erstellen falls nicht vorhanden
$pdo->exec("CREATE DATABASE IF NOT EXISTS `$db_name` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
$pdo->exec("USE `$db_name`");
// Tabellen erstellen
$sql = file_get_contents(__DIR__ . '/database.sql');
$pdo->exec($sql);
$_SESSION['install_db'] = [
'host' => $db_host,
'name' => $db_name,
'user' => $db_user,
'pass' => $db_pass
];
} catch (PDOException $e) {
$errors[] = "Datenbankfehler: " . $e->getMessage();
$step = 1;
}
}
// Step 2: Admin-Account erstellen
if ($step === 3 && $_SERVER['REQUEST_METHOD'] === 'POST') {
$admin_email = filter_var($_POST['admin_email'] ?? '', FILTER_VALIDATE_EMAIL);
$admin_name = $_POST['admin_name'] ?? '';
$admin_password = $_POST['admin_password'] ?? '';
$admin_password_confirm = $_POST['admin_password_confirm'] ?? '';
if (!$admin_email) {
$errors[] = "Ungültige E-Mail-Adresse";
$step = 2;
} elseif (strlen($admin_password) < 8) {
$errors[] = "Passwort muss mindestens 8 Zeichen lang sein";
$step = 2;
} elseif ($admin_password !== $admin_password_confirm) {
$errors[] = "Passwörter stimmen nicht überein";
$step = 2;
} else {
$_SESSION['install_admin'] = [
'email' => $admin_email,
'name' => $admin_name,
'password' => password_hash($admin_password, PASSWORD_DEFAULT)
];
}
}
// Step 3: Allgemeine Einstellungen
if ($step === 4 && $_SERVER['REQUEST_METHOD'] === 'POST') {
$app_title = $_POST['app_title'] ?? 'UniFi Voucher System';
$logo_url = $_POST['logo_url'] ?? '';
$instruction_header = $_POST['instruction_header'] ?? '';
$instruction_text = $_POST['instruction_text'] ?? '';
$public_access = isset($_POST['public_access']) ? 1 : 0;
// Microsoft 365 OAuth (optional)
$m365_client_id = $_POST['m365_client_id'] ?? '';
$m365_client_secret = $_POST['m365_client_secret'] ?? '';
$m365_tenant_id = $_POST['m365_tenant_id'] ?? '';
$_SESSION['install_settings'] = [
'app_title' => $app_title,
'logo_url' => $logo_url,
'instruction_header' => $instruction_header,
'instruction_text' => $instruction_text,
'public_access' => $public_access,
'm365_client_id' => $m365_client_id,
'm365_client_secret' => $m365_client_secret,
'm365_tenant_id' => $m365_tenant_id
];
}
// Step 4: Installation abschließen
if ($step === 5 && $_SERVER['REQUEST_METHOD'] === 'POST') {
try {
$db = $_SESSION['install_db'];
$admin = $_SESSION['install_admin'];
$settings = $_SESSION['install_settings'];
$pdo = new PDO("mysql:host={$db['host']};dbname={$db['name']};charset=utf8mb4", $db['user'], $db['pass']);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Admin-User erstellen
$stmt = $pdo->prepare("INSERT INTO users (email, name, password_hash, is_admin, is_active) VALUES (?, ?, ?, 1, 1)");
$stmt->execute([$admin['email'], $admin['name'], $admin['password']]);
// Settings speichern
$settingsData = [
'app_title' => $settings['app_title'],
'logo_url' => $settings['logo_url'],
'instruction_header' => $settings['instruction_header'],
'instruction_text' => $settings['instruction_text'],
'public_access' => $settings['public_access'],
'm365_client_id' => $settings['m365_client_id'],
'm365_client_secret' => $settings['m365_client_secret'],
'm365_tenant_id' => $settings['m365_tenant_id']
];
$stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)");
foreach ($settingsData as $key => $value) {
$stmt->execute([$key, $value]);
}
// config.php erstellen
$configContent = "<?php\n";
$configContent .= "// UniFi Voucher Management System - Configuration\n\n";
$configContent .= "define('DB_HOST', '{$db['host']}');\n";
$configContent .= "define('DB_NAME', '{$db['name']}');\n";
$configContent .= "define('DB_USER', '{$db['user']}');\n";
$configContent .= "define('DB_PASS', '" . addslashes($db['pass']) . "');\n\n";
$configContent .= "// Sitzungs-Einstellungen\n";
$configContent .= "define('SESSION_LIFETIME', 3600); // 1 Stunde\n\n";
$configContent .= "// Zeitzone\n";
$configContent .= "date_default_timezone_set('Europe/Berlin');\n";
file_put_contents(__DIR__ . '/config.php', $configContent);
// .htaccess erstellen (ohne Rewrite Rules die Probleme machen)
$htaccess = "# UniFi Voucher System\n\n";
$htaccess .= "# Security\n";
$htaccess .= "<FilesMatch \"(config\\.php|database\\.sql|install\\.php|test\\.php|\\.md)$\">\n";
$htaccess .= " Order Allow,Deny\n";
$htaccess .= " Deny from all\n";
$htaccess .= "</FilesMatch>\n\n";
$htaccess .= "DirectoryIndex index.php\n";
file_put_contents(__DIR__ . '/.htaccess', $htaccess);
$success = true;
// Session-Daten löschen
unset($_SESSION['install_db'], $_SESSION['install_admin'], $_SESSION['install_settings']);
} catch (Exception $e) {
$errors[] = "Fehler bei der Installation: " . $e->getMessage();
$step = 4;
}
}
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>UniFi Voucher System - Installation</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
}
.container {
background: white;
border-radius: 16px;
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
max-width: 600px;
width: 100%;
padding: 40px;
}
h1 { color: #333; margin-bottom: 10px; font-size: 28px; }
h2 { color: #667eea; margin-bottom: 20px; font-size: 20px; font-weight: 500; }
.progress {
display: flex;
justify-content: space-between;
margin: 30px 0;
position: relative;
}
.progress::before {
content: '';
position: absolute;
top: 15px;
left: 0;
right: 0;
height: 2px;
background: #e0e0e0;
z-index: 0;
}
.progress-step {
width: 30px;
height: 30px;
border-radius: 50%;
background: #e0e0e0;
display: flex;
align-items: center;
justify-content: center;
font-weight: bold;
color: #999;
position: relative;
z-index: 1;
}
.progress-step.active {
background: #667eea;
color: white;
}
.progress-step.completed {
background: #4caf50;
color: white;
}
.form-group {
margin-bottom: 20px;
}
label {
display: block;
margin-bottom: 8px;
color: #555;
font-weight: 500;
}
input[type="text"],
input[type="email"],
input[type="password"],
textarea {
width: 100%;
padding: 12px;
border: 2px solid #e0e0e0;
border-radius: 8px;
font-size: 14px;
transition: border-color 0.3s;
}
input:focus, textarea:focus {
outline: none;
border-color: #667eea;
}
textarea {
resize: vertical;
min-height: 80px;
}
.checkbox-group {
display: flex;
align-items: center;
}
.checkbox-group input {
width: auto;
margin-right: 10px;
}
.btn {
background: #667eea;
color: white;
padding: 14px 30px;
border: none;
border-radius: 8px;
font-size: 16px;
font-weight: 600;
cursor: pointer;
transition: background 0.3s;
width: 100%;
}
.btn:hover {
background: #5568d3;
}
.error {
background: #fee;
border: 1px solid #fcc;
color: #c33;
padding: 12px;
border-radius: 8px;
margin-bottom: 20px;
}
.success {
background: #efe;
border: 1px solid #cfc;
color: #3c3;
padding: 12px;
border-radius: 8px;
margin-bottom: 20px;
}
.help-text {
font-size: 12px;
color: #999;
margin-top: 4px;
}
.section {
background: #f8f9fa;
padding: 20px;
border-radius: 8px;
margin-bottom: 20px;
}
.section h3 {
margin-bottom: 15px;
color: #333;
font-size: 16px;
}
</style>
</head>
<body>
<div class="container">
<h1>🚀 UniFi Voucher System</h1>
<h2>Installation</h2>
<div class="progress">
<div class="progress-step <?= $step >= 1 ? 'completed' : '' ?>">1</div>
<div class="progress-step <?= $step >= 2 ? 'completed' : ($step === 1 ? 'active' : '') ?>">2</div>
<div class="progress-step <?= $step >= 3 ? 'completed' : ($step === 2 ? 'active' : '') ?>">3</div>
<div class="progress-step <?= $step >= 4 ? 'completed' : ($step === 3 ? 'active' : '') ?>">4</div>
<div class="progress-step <?= $step >= 5 ? 'active' : '' ?>">5</div>
</div>
<?php if (!empty($errors)): ?>
<div class="error">
<?php foreach ($errors as $error): ?>
<div><?= htmlspecialchars($error) ?></div>
<?php endforeach; ?>
</div>
<?php endif; ?>
<?php if ($success): ?>
<div class="success">
<strong> Installation erfolgreich abgeschlossen!</strong><br>
Sie können sich jetzt mit Ihren Admin-Zugangsdaten anmelden.
</div>
<a href="index.php" class="btn">Zum Login</a>
<?php elseif ($step === 1): ?>
<form method="post">
<input type="hidden" name="step" value="2">
<h3>Schritt 1: Datenbank-Konfiguration</h3>
<div class="form-group">
<label>Datenbank-Host</label>
<input type="text" name="db_host" value="localhost" required>
<div class="help-text">Meist "localhost"</div>
</div>
<div class="form-group">
<label>Datenbankname</label>
<input type="text" name="db_name" value="unifi_voucher" required>
<div class="help-text">Name der Datenbank (wird erstellt falls nicht vorhanden)</div>
</div>
<div class="form-group">
<label>Datenbank-Benutzer</label>
<input type="text" name="db_user" required>
</div>
<div class="form-group">
<label>Datenbank-Passwort</label>
<input type="password" name="db_pass">
</div>
<button type="submit" class="btn">Weiter </button>
</form>
<?php elseif ($step === 2): ?>
<form method="post">
<input type="hidden" name="step" value="3">
<h3>Schritt 2: Administrator-Account</h3>
<div class="form-group">
<label>Name</label>
<input type="text" name="admin_name" required>
</div>
<div class="form-group">
<label>E-Mail</label>
<input type="email" name="admin_email" required>
</div>
<div class="form-group">
<label>Passwort</label>
<input type="password" name="admin_password" required minlength="8">
<div class="help-text">Mindestens 8 Zeichen</div>
</div>
<div class="form-group">
<label>Passwort bestätigen</label>
<input type="password" name="admin_password_confirm" required>
</div>
<button type="submit" class="btn">Weiter </button>
</form>
<?php elseif ($step === 3): ?>
<form method="post">
<input type="hidden" name="step" value="4">
<h3>Schritt 3: Allgemeine Einstellungen</h3>
<div class="form-group">
<label>Anwendungs-Titel</label>
<input type="text" name="app_title" value="UniFi Voucher System" required>
</div>
<div class="form-group">
<label>Logo-URL (optional)</label>
<input type="text" name="logo_url" placeholder="https://example.com/logo.png">
</div>
<div class="form-group">
<label>Anleitung Überschrift</label>
<input type="text" name="instruction_header" value="So verwenden Sie Ihren Code">
</div>
<div class="form-group">
<label>Anleitung Text</label>
<textarea name="instruction_text">Verbinden Sie sich mit dem WLAN und geben Sie den Code auf der Anmeldeseite ein.</textarea>
</div>
<div class="form-group checkbox-group">
<input type="checkbox" name="public_access" id="public_access">
<label for="public_access" style="margin: 0;">Öffentlicher Zugriff auf Code-Erstellung</label>
</div>
<div class="section">
<h3>Microsoft 365 Login (Optional)</h3>
<div class="form-group">
<label>Client ID</label>
<input type="text" name="m365_client_id">
</div>
<div class="form-group">
<label>Client Secret</label>
<input type="password" name="m365_client_secret">
</div>
<div class="form-group">
<label>Tenant ID</label>
<input type="text" name="m365_tenant_id">
</div>
<div class="help-text">Leer lassen, wenn M365-Login nicht verwendet werden soll</div>
</div>
<button type="submit" class="btn">Weiter </button>
</form>
<?php elseif ($step === 4): ?>
<form method="post">
<input type="hidden" name="step" value="5">
<h3>Schritt 4: Installation abschließen</h3>
<p style="margin-bottom: 20px; color: #666;">
Klicken Sie auf "Installation abschließen", um die Einrichtung zu beenden.
Die Datenbank und alle notwendigen Dateien werden erstellt.
</p>
<button type="submit" class="btn">Installation abschließen</button>
</form>
<?php endif; ?>
</div>
</body>
</html>

329
login.php Normal file
View file

@ -0,0 +1,329 @@
<?php
// Error Reporting (kann nach erfolgreicher Einrichtung entfernt werden)
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Absolute Pfade verwenden
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/includes/Database.php';
require_once __DIR__ . '/includes/Auth.php';
try {
$auth = new Auth();
// Wenn bereits eingeloggt, weiterleiten
if ($auth->isLoggedIn()) {
header('Location: index.php');
exit;
}
} catch (Exception $e) {
die('Fehler beim Initialisieren: ' . $e->getMessage());
}
$error = '';
$success = '';
// Login-Verarbeitung
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
try {
$email = trim($_POST['email'] ?? '');
$password = $_POST['password'] ?? '';
if (empty($email) || empty($password)) {
$error = 'Bitte E-Mail und Passwort eingeben';
} elseif ($auth->login($email, $password)) {
// Nach erfolgreichem Login zu index.php
header('Location: index.php');
exit;
} else {
$error = 'Ungültige E-Mail oder Passwort';
}
} catch (Exception $e) {
$error = 'Login-Fehler: ' . $e->getMessage();
}
}
try {
$db = Database::getInstance();
$appTitle = $db->getSetting('app_title', 'UniFi Voucher System');
$logoUrl = $db->getSetting('logo_url', '');
// M365 aktiviert prüfen - ALLE drei Felder müssen ausgefüllt sein
$m365ClientId = $db->getSetting('m365_client_id', '');
$m365ClientSecret = $db->getSetting('m365_client_secret', '');
$m365TenantId = $db->getSetting('m365_tenant_id', '');
$m365Enabled = !empty($m365ClientId) &&
!empty($m365ClientSecret) &&
!empty($m365TenantId);
$publicAccess = $db->getSetting('public_access', 0);
// M365 OAuth URL generieren falls aktiviert
$m365LoginUrl = '';
if ($m365Enabled) {
// Dynamische Redirect URI basierend auf aktuellem Pfad
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'];
$scriptPath = dirname($_SERVER['SCRIPT_NAME']);
$scriptPath = $scriptPath === '/' ? '' : $scriptPath;
$redirectUri = $protocol . '://' . $host . $scriptPath . '/m365_callback.php';
$params = [
'client_id' => $m365ClientId,
'response_type' => 'code',
'redirect_uri' => $redirectUri,
'response_mode' => 'query',
'scope' => 'openid profile email User.Read',
'state' => bin2hex(random_bytes(16))
];
$_SESSION['m365_state'] = $params['state'];
$m365LoginUrl = "https://login.microsoftonline.com/$m365TenantId/oauth2/v2.0/authorize?" . http_build_query($params);
}
// Prüfen ob alternative Login-Form (Benutzername/Passwort) angezeigt werden soll
$showLocalLogin = isset($_GET['local']) && $_GET['local'] === '1';
} catch (Exception $e) {
die('Datenbankfehler: ' . $e->getMessage());
}
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login - <?= htmlspecialchars($appTitle) ?></title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
}
.login-container {
background: white;
border-radius: 20px;
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
max-width: 420px;
width: 100%;
padding: 50px 40px;
text-align: center;
}
.logo {
max-width: 200px;
height: auto;
margin-bottom: 30px;
}
h1 {
color: #333;
font-size: 28px;
margin-bottom: 10px;
}
.subtitle {
color: #666;
font-size: 14px;
margin-bottom: 30px;
}
.form-group {
margin-bottom: 20px;
text-align: left;
}
label {
display: block;
margin-bottom: 8px;
color: #555;
font-weight: 500;
font-size: 14px;
}
input[type="email"],
input[type="password"] {
width: 100%;
padding: 14px;
border: 2px solid #e0e0e0;
border-radius: 10px;
font-size: 15px;
transition: all 0.3s;
}
input:focus {
outline: none;
border-color: #667eea;
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
.btn {
width: 100%;
padding: 14px;
background: #667eea;
color: white;
border: none;
border-radius: 10px;
font-size: 16px;
font-weight: 600;
cursor: pointer;
transition: all 0.3s;
margin-top: 10px;
}
.btn:hover {
background: #5568d3;
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}
.btn-microsoft {
background: #2f2f2f;
color: white;
border: none;
margin-top: 0;
text-decoration: none;
display: inline-flex;
align-items: center;
justify-content: center;
gap: 12px;
padding: 16px 24px;
}
.btn-microsoft:hover {
background: #1a1a1a;
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
text-decoration: none;
}
.btn-microsoft svg {
width: 20px;
height: 20px;
}
.divider {
margin: 25px 0;
text-align: center;
position: relative;
}
.divider::before {
content: '';
position: absolute;
top: 50%;
left: 0;
right: 0;
height: 1px;
background: #e0e0e0;
}
.divider span {
background: white;
padding: 0 15px;
color: #999;
font-size: 13px;
position: relative;
z-index: 1;
}
.alert {
padding: 12px;
border-radius: 8px;
margin-bottom: 20px;
font-size: 14px;
}
.alert-error {
background: #fee;
border: 1px solid #fcc;
color: #c33;
}
.alert-success {
background: #efe;
border: 1px solid #cfc;
color: #3c3;
}
.back-link {
display: block;
margin-top: 20px;
color: #667eea;
text-decoration: none;
font-size: 14px;
}
.back-link:hover {
text-decoration: underline;
}
.local-login-link {
display: block;
margin-top: 25px;
color: #999;
text-decoration: none;
font-size: 13px;
text-align: center;
}
.local-login-link:hover {
color: #667eea;
text-decoration: underline;
}
</style>
</head>
<body>
<div class="login-container">
<?php if ($logoUrl): ?>
<img src="<?= htmlspecialchars($logoUrl) ?>" alt="Logo" class="logo">
<?php else: ?>
<h1><?= htmlspecialchars($appTitle) ?></h1>
<?php endif; ?>
<p class="subtitle">Melden Sie sich an, um fortzufahren</p>
<?php if ($error): ?>
<div class="alert alert-error"><?= htmlspecialchars($error) ?></div>
<?php endif; ?>
<?php if ($success): ?>
<div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
<?php endif; ?>
<?php if ($m365Enabled && !$showLocalLogin): ?>
<!-- M365 Login als Hauptoption -->
<a href="<?= htmlspecialchars($m365LoginUrl) ?>" class="btn btn-microsoft">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 23 23">
<path fill="#f35325" d="M1 1h10v10H1z"/>
<path fill="#81bc06" d="M12 1h10v10H12z"/>
<path fill="#05a6f0" d="M1 12h10v10H1z"/>
<path fill="#ffba08" d="M12 12h10v10H12z"/>
</svg>
Mit Microsoft anmelden
</a>
<a href="?local=1" class="local-login-link">Mit Benutzername und Passwort anmelden</a>
<?php else: ?>
<!-- Lokales Login-Formular -->
<form method="post">
<div class="form-group">
<label for="email">E-Mail</label>
<input type="email" id="email" name="email" required autofocus>
</div>
<div class="form-group">
<label for="password">Passwort</label>
<input type="password" id="password" name="password" required>
</div>
<button type="submit" class="btn">Anmelden</button>
</form>
<?php if ($m365Enabled): ?>
<div class="divider"><span>oder</span></div>
<a href="<?= htmlspecialchars($m365LoginUrl) ?>" class="btn btn-microsoft">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 23 23">
<path fill="#f35325" d="M1 1h10v10H1z"/>
<path fill="#81bc06" d="M12 1h10v10H12z"/>
<path fill="#05a6f0" d="M1 12h10v10H1z"/>
<path fill="#ffba08" d="M12 12h10v10H12z"/>
</svg>
Mit Microsoft anmelden
</a>
<?php endif; ?>
<?php endif; ?>
<?php if ($publicAccess): ?>
<a href="index.php" class="back-link"> Zurück zur Code-Erstellung</a>
<?php endif; ?>
</div>
</body>
</html>

328
login_simple.php Normal file
View file

@ -0,0 +1,328 @@
<?php
// Umfassendes Error Reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
// Versuche Dateien zu laden
$loadErrors = [];
try {
if (!file_exists(__DIR__ . '/config.php')) {
throw new Exception('config.php nicht gefunden');
}
require_once __DIR__ . '/config.php';
} catch (Exception $e) {
$loadErrors[] = "Config: " . $e->getMessage();
}
try {
if (!file_exists(__DIR__ . '/includes/Database.php')) {
throw new Exception('includes/Database.php nicht gefunden');
}
require_once __DIR__ . '/includes/Database.php';
} catch (Exception $e) {
$loadErrors[] = "Database: " . $e->getMessage();
}
try {
if (!file_exists(__DIR__ . '/includes/Auth.php')) {
throw new Exception('includes/Auth.php nicht gefunden');
}
require_once __DIR__ . '/includes/Auth.php';
} catch (Exception $e) {
$loadErrors[] = "Auth: " . $e->getMessage();
}
// Wenn Ladefehler aufgetreten sind, zeige sie an
if (!empty($loadErrors)) {
die('<h1>Fehler beim Laden der Dateien</h1><ul><li>' . implode('</li><li>', $loadErrors) . '</li></ul>');
}
// Ab hier normal weiter
try {
$auth = new Auth();
} catch (Exception $e) {
die('<h1>Fehler bei Auth-Initialisierung</h1><p>' . $e->getMessage() . '</p>');
}
// Wenn bereits eingeloggt, weiterleiten
if ($auth->isLoggedIn()) {
header('Location: index.php');
exit;
}
$error = '';
$success = '';
// Login-Verarbeitung
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
try {
$email = $_POST['email'] ?? '';
$password = $_POST['password'] ?? '';
if (empty($email) || empty($password)) {
$error = 'Bitte E-Mail und Passwort eingeben';
} elseif ($auth->login($email, $password)) {
header('Location: index.php');
exit;
} else {
$error = 'Ungültige E-Mail oder Passwort';
}
} catch (Exception $e) {
$error = 'Login-Fehler: ' . $e->getMessage();
}
}
try {
$db = Database::getInstance();
$appTitle = $db->getSetting('app_title', 'UniFi Voucher System');
$logoUrl = $db->getSetting('logo_url', '');
$m365Enabled = !empty($db->getSetting('m365_client_id')) &&
!empty($db->getSetting('m365_client_secret')) &&
!empty($db->getSetting('m365_tenant_id'));
$publicAccess = $db->getSetting('public_access', 0);
// M365 OAuth URL generieren falls aktiviert
$m365LoginUrl = '';
if ($m365Enabled) {
$clientId = $db->getSetting('m365_client_id');
$tenantId = $db->getSetting('m365_tenant_id');
// Dynamische Redirect URI basierend auf aktuellem Pfad
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'];
$scriptPath = dirname($_SERVER['SCRIPT_NAME']);
$scriptPath = $scriptPath === '/' ? '' : $scriptPath;
$redirectUri = $protocol . '://' . $host . $scriptPath . '/m365_callback.php';
$params = [
'client_id' => $clientId,
'response_type' => 'code',
'redirect_uri' => $redirectUri,
'response_mode' => 'query',
'scope' => 'openid profile email User.Read',
'state' => bin2hex(random_bytes(16))
];
$_SESSION['m365_state'] = $params['state'];
$m365LoginUrl = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/authorize?" . http_build_query($params);
}
} catch (Exception $e) {
die('<h1>Datenbankfehler</h1><p>' . $e->getMessage() . '</p>');
}
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login - <?= htmlspecialchars($appTitle) ?></title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
}
.login-container {
background: white;
border-radius: 20px;
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
max-width: 420px;
width: 100%;
padding: 50px 40px;
text-align: center;
}
.logo {
max-width: 200px;
height: auto;
margin-bottom: 30px;
}
h1 {
color: #333;
font-size: 28px;
margin-bottom: 10px;
}
.subtitle {
color: #666;
font-size: 14px;
margin-bottom: 30px;
}
.form-group {
margin-bottom: 20px;
text-align: left;
}
label {
display: block;
margin-bottom: 8px;
color: #555;
font-weight: 500;
font-size: 14px;
}
input[type="email"],
input[type="password"] {
width: 100%;
padding: 14px;
border: 2px solid #e0e0e0;
border-radius: 10px;
font-size: 15px;
transition: all 0.3s;
}
input:focus {
outline: none;
border-color: #667eea;
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
.btn {
width: 100%;
padding: 14px;
background: #667eea;
color: white;
border: none;
border-radius: 10px;
font-size: 16px;
font-weight: 600;
cursor: pointer;
transition: all 0.3s;
margin-top: 10px;
}
.btn:hover {
background: #5568d3;
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}
.btn-microsoft {
background: white;
color: #333;
border: 2px solid #e0e0e0;
margin-top: 15px;
text-decoration: none;
display: inline-flex;
align-items: center;
justify-content: center;
}
.btn-microsoft:hover {
background: #f8f9fa;
border-color: #667eea;
transform: translateY(-2px);
text-decoration: none;
}
.divider {
margin: 25px 0;
text-align: center;
position: relative;
}
.divider::before {
content: '';
position: absolute;
top: 50%;
left: 0;
right: 0;
height: 1px;
background: #e0e0e0;
}
.divider span {
background: white;
padding: 0 15px;
color: #999;
font-size: 13px;
position: relative;
z-index: 1;
}
.alert {
padding: 12px;
border-radius: 8px;
margin-bottom: 20px;
font-size: 14px;
}
.alert-error {
background: #fee;
border: 1px solid #fcc;
color: #c33;
}
.alert-success {
background: #efe;
border: 1px solid #cfc;
color: #3c3;
}
.back-link {
display: block;
margin-top: 20px;
color: #667eea;
text-decoration: none;
font-size: 14px;
}
.back-link:hover {
text-decoration: underline;
}
.debug-info {
background: #f8f9fa;
border: 1px solid #e0e0e0;
padding: 15px;
margin-top: 20px;
border-radius: 8px;
text-align: left;
font-size: 12px;
color: #666;
}
</style>
</head>
<body>
<div class="login-container">
<?php if ($logoUrl): ?>
<img src="<?= htmlspecialchars($logoUrl) ?>" alt="Logo" class="logo">
<?php else: ?>
<h1><?= htmlspecialchars($appTitle) ?></h1>
<?php endif; ?>
<p class="subtitle">Melden Sie sich an, um fortzufahren</p>
<?php if ($error): ?>
<div class="alert alert-error"><?= htmlspecialchars($error) ?></div>
<?php endif; ?>
<?php if ($success): ?>
<div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
<?php endif; ?>
<form method="post" action="">
<div class="form-group">
<label for="email">E-Mail</label>
<input type="email" id="email" name="email" required autofocus>
</div>
<div class="form-group">
<label for="password">Passwort</label>
<input type="password" id="password" name="password" required>
</div>
<button type="submit" class="btn">Anmelden</button>
</form>
<?php if ($m365Enabled): ?>
<div class="divider"><span>oder</span></div>
<a href="<?= htmlspecialchars($m365LoginUrl) ?>" class="btn btn-microsoft">
🔷 Mit Microsoft 365 anmelden
</a>
<?php endif; ?>
<?php if ($publicAccess): ?>
<a href="index.php" class="back-link"> Zurück zur Code-Erstellung</a>
<?php endif; ?>
<!-- Debug Info (kann nach erfolgreicher Einrichtung entfernt werden) -->
<div class="debug-info">
<strong>System-Status:</strong><br>
PHP Version: <?= phpversion() ?><br>
Session Status: <?= session_status() === PHP_SESSION_ACTIVE ? 'Aktiv' : 'Inaktiv' ?><br>
Eingeloggt: <?= $auth->isLoggedIn() ? 'Ja' : 'Nein' ?>
</div>
</div>
</body>
</html>

10
logout.php Normal file
View file

@ -0,0 +1,10 @@
<?php
require_once 'config.php';
require_once 'includes/Database.php';
require_once 'includes/Auth.php';
$auth = new Auth();
$auth->logout();
header('Location: index.php');
exit;

118
m365_callback.php Normal file
View file

@ -0,0 +1,118 @@
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/includes/Database.php';
require_once __DIR__ . '/includes/Auth.php';
session_start();
$db = Database::getInstance();
$auth = new Auth();
// M365 Einstellungen abrufen
$clientId = $db->getSetting('m365_client_id', '');
$clientSecret = $db->getSetting('m365_client_secret', '');
$tenantId = $db->getSetting('m365_tenant_id', '');
if (empty($clientId) || empty($clientSecret) || empty($tenantId)) {
die('Microsoft 365 ist nicht konfiguriert. Bitte kontaktieren Sie Ihren Administrator. <a href="login.php">Zurück zum Login</a>');
}
// Dynamische Redirect URI
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'];
$scriptPath = dirname($_SERVER['SCRIPT_NAME']);
$scriptPath = $scriptPath === '/' ? '' : $scriptPath;
$redirectUri = $protocol . '://' . $host . $scriptPath . '/m365_callback.php';
// Fehlerbehandlung
if (isset($_GET['error'])) {
$error = htmlspecialchars($_GET['error']);
$errorDesc = htmlspecialchars($_GET['error_description'] ?? 'Unbekannter Fehler');
die("Microsoft 365 Login-Fehler: $error<br>$errorDesc<br><a href='login.php'>Zurück zum Login</a>");
}
// Authorization Code erhalten
if (isset($_GET['code'])) {
$code = $_GET['code'];
// Token anfordern
$tokenUrl = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token";
$postData = [
'client_id' => $clientId,
'client_secret' => $clientSecret,
'code' => $code,
'redirect_uri' => $redirectUri,
'grant_type' => 'authorization_code',
'scope' => 'openid profile email User.Read'
];
$ch = curl_init($tokenUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
die("Fehler beim Token-Abruf (HTTP $httpCode): " . htmlspecialchars($response) . "<br><a href='login.php'>Zurück zum Login</a>");
}
$tokenData = json_decode($response, true);
if (!isset($tokenData['access_token'])) {
die("Kein Access Token erhalten: " . htmlspecialchars($response) . "<br><a href='login.php'>Zurück zum Login</a>");
}
$accessToken = $tokenData['access_token'];
// Benutzer-Informationen abrufen
$userUrl = 'https://graph.microsoft.com/v1.0/me';
$ch = curl_init($userUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $accessToken,
'Content-Type: application/json'
]);
$userResponse = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
die("Fehler beim Abrufen der Benutzer-Daten (HTTP $httpCode): " . htmlspecialchars($userResponse) . "<br><a href='login.php'>Zurück zum Login</a>");
}
$userData = json_decode($userResponse, true);
if (!isset($userData['id']) || !isset($userData['mail'])) {
die("Ungültige Benutzer-Daten erhalten: " . htmlspecialchars($userResponse) . "<br><a href='login.php'>Zurück zum Login</a>");
}
// Benutzer einloggen oder anlegen
$microsoftUser = [
'id' => $userData['id'],
'email' => $userData['mail'] ?? $userData['userPrincipalName'],
'name' => $userData['displayName'] ?? $userData['givenName'] . ' ' . $userData['surname']
];
try {
$auth->loginWithMicrosoft($microsoftUser);
header('Location: index.php');
exit;
} catch (Exception $e) {
die("Login-Fehler: " . $e->getMessage() . "<br><a href='login.php'>Zurück zum Login</a>");
}
} else {
// Keine Authorization Code - Redirect zu Microsoft Login
die("Kein Authorization Code erhalten.<br><a href='login.php'>Zurück zum Login</a>");
}
?>

81
m365_debug.php Normal file
View file

@ -0,0 +1,81 @@
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/includes/Database.php';
$db = Database::getInstance();
// M365 Einstellungen abrufen
$clientId = $db->getSetting('m365_client_id', '');
$clientSecret = $db->getSetting('m365_client_secret', '');
$tenantId = $db->getSetting('m365_tenant_id', '');
// Dynamische URLs
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'];
$scriptPath = dirname($_SERVER['SCRIPT_NAME']);
$scriptPath = $scriptPath === '/' ? '' : $scriptPath;
$redirectUri = $protocol . '://' . $host . $scriptPath . '/m365_callback.php';
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>M365 Debug</title>
<style>
body {
font-family: monospace;
padding: 20px;
background: #f5f5f5;
}
.section {
background: white;
padding: 20px;
margin-bottom: 20px;
border-radius: 8px;
border: 1px solid #ddd;
}
h2 {
margin-top: 0;
color: #333;
}
.ok {
color: green;
font-weight: bold;
}
.error {
color: red;
font-weight: bold;
}
.info {
color: #666;
font-size: 12px;
margin-top: 5px;
}
code {
background: #f0f0f0;
padding: 2px 6px;
border-radius: 3px;
}
.copyable {
background: #f9f9f9;
border: 1px solid #ddd;
padding: 10px;
border-radius: 4px;
margin: 10px 0;
word-break: break-all;
}
</style>
</head>
<body>
<h1>🔍 Microsoft 365 OAuth Debug</h1>
<div class="section">
<h2>1. Konfiguration Status</h2>
<p>Client ID: <?= !empty($clientId) ? '<span class="ok">✓ Gesetzt</span>' : '<span class="error">✗ Fehlt</span>' ?></p>
<p>Client Secret: <?= !empty($clientSecret) ? '<span class="ok">✓ Gesetzt</span>' : '<span class="error">✗ Fehlt</span>' ?></p>
<p>Tenant ID: <?= !empty($tenant

90
test.php Normal file
View file

@ -0,0 +1,90 @@
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
echo "<h1>System Test</h1>";
// 1. PHP Version
echo "<h2>1. PHP Version</h2>";
echo "PHP Version: " . phpversion() . "<br>";
// 2. Config.php vorhanden?
echo "<h2>2. Config.php Check</h2>";
if (file_exists('config.php')) {
echo "✓ config.php existiert<br>";
require_once 'config.php';
echo "✓ config.php geladen<br>";
echo "DB_HOST: " . DB_HOST . "<br>";
echo "DB_NAME: " . DB_NAME . "<br>";
} else {
echo "✗ config.php nicht gefunden!<br>";
}
// 3. Datenbankverbindung
echo "<h2>3. Datenbankverbindung</h2>";
try {
$pdo = new PDO(
"mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4",
DB_USER,
DB_PASS
);
echo "✓ Datenbankverbindung erfolgreich<br>";
// Tabellen prüfen
$tables = $pdo->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);
echo "✓ Gefundene Tabellen: " . implode(", ", $tables) . "<br>";
} catch (PDOException $e) {
echo "✗ Datenbankfehler: " . $e->getMessage() . "<br>";
}
// 4. Includes prüfen
echo "<h2>4. Include-Dateien</h2>";
$files = ['includes/Database.php', 'includes/Auth.php', 'includes/UniFiController.php'];
foreach ($files as $file) {
if (file_exists($file)) {
echo "$file existiert<br>";
try {
require_once $file;
echo "$file geladen<br>";
} catch (Exception $e) {
echo "✗ Fehler beim Laden von $file: " . $e->getMessage() . "<br>";
}
} else {
echo "$file nicht gefunden!<br>";
}
}
// 5. Database-Klasse testen
echo "<h2>5. Database-Klasse</h2>";
try {
$db = Database::getInstance();
echo "✓ Database::getInstance() erfolgreich<br>";
$result = $db->fetchOne("SELECT COUNT(*) as count FROM users");
echo "✓ Anzahl Benutzer: " . $result['count'] . "<br>";
} catch (Exception $e) {
echo "✗ Database-Fehler: " . $e->getMessage() . "<br>";
}
// 6. Auth-Klasse testen
echo "<h2>6. Auth-Klasse</h2>";
try {
$auth = new Auth();
echo "✓ Auth-Klasse initialisiert<br>";
echo "Eingeloggt: " . ($auth->isLoggedIn() ? 'Ja' : 'Nein') . "<br>";
} catch (Exception $e) {
echo "✗ Auth-Fehler: " . $e->getMessage() . "<br>";
}
// 7. Session-Test
echo "<h2>7. Session</h2>";
echo "Session Status: " . session_status() . " (1=disabled, 2=active)<br>";
echo "Session ID: " . session_id() . "<br>";
echo "<hr>";
echo "<h2>✓ Test abgeschlossen</h2>";
echo "<p><a href='login.php'>Zum Login</a> | <a href='index.php'>Zur Startseite</a></p>";
?>