Upload via GUI (94 Dateien)

This commit is contained in:
2026-10-24 20:15:16 +00:00
parent cbf6139e74
commit e7a6ba0b86
34 changed files with 2102 additions and 0 deletions
+24
View File
@@ -0,0 +1,24 @@
<?php
/**
* Optional: echter Server-Cronjob für die Überwachung, unabhängig vom Besucherverkehr.
*
* Ohne diese Datei prüft das Plugin über den eingebauten Hintergrund-Betrieb von DeskHub (höchstens alle 5 Minuten, und nur solange jemand
* die Seite oder das Backend aufruft). Wer auch nachts ohne Besucher prüfen will, trägt im Hosting-Panel (zum Beispiel Plesk → Geplante Aufgaben)
* alle 5 Minuten diesen Befehl ein:
*
* php /pfad/zu/deskhub/plugins/ueberwachung/cron.php
*
* Die Adresse im Browser aufzurufen ist nicht möglich (nur Kommandozeile).
*/
if (PHP_SAPI !== 'cli') {
http_response_code(403);
exit('Nur über die Kommandozeile.');
}
require_once getenv('DESKHUB_BOOTSTRAP') ?: dirname(__DIR__, 2) . '/includes/bootstrap.php';
if (!function_exists('ueberwachung_tick')) {
fwrite(STDERR, "Das Plugin „Überwachung“ ist nicht aktiv.\n");
exit(1);
}
$n = ueberwachung_tick(get_db());
echo $n . " Ziel(e) geprüft.\n";
+432
View File
@@ -0,0 +1,432 @@
<?php
// Website- und Server-Überwachung. Alle Funktionen beginnen mit ueberwachung_.
const UEBERWACHUNG = 'ueberwachung';
require_once __DIR__ . '/meldung.php';
/**
* Selbstheilung: Fehlt nach einem Update eine Datenbank-Änderung des Plugins (ältere DeskHub-Dateien spielen sie nicht von selbst ein),
* wird sie hier nachgeholt, statt dass das Plugin mit Datenbankfehlern abgeschaltet wird.
*/
function ueberwachung_ensure_schema(bool $force = false): void
{
static $done = false;
if ($done && !$force) return;
$done = true;
try {
get_db()->query('SELECT first_fail_at, verify_tls, last_status, last_title FROM plugin_ueberwachung_monitors LIMIT 1');
} catch (Throwable $e) {
try {
plugin_run_migrations(get_db(), UEBERWACHUNG);
} catch (Throwable $e2) {
error_log('ueberwachung schema: ' . $e2->getMessage());
}
}
}
function ueberwachung_config(): array
{
$mail = trim((string) plugin_setting(UEBERWACHUNG, 'alert_email', ''));
return [
'threshold' => max(1, min(10, (int) plugin_setting(UEBERWACHUNG, 'threshold', '2'))),
'department_id' => (int) plugin_setting(UEBERWACHUNG, 'department_id', '0'),
'priority_id' => (int) plugin_setting(UEBERWACHUNG, 'priority_id', '0'),
'create_tickets' => plugin_setting(UEBERWACHUNG, 'create_tickets', '1') === '1',
'auto_resolve' => plugin_setting(UEBERWACHUNG, 'auto_resolve', '1') === '1',
'mail' => plugin_setting(UEBERWACHUNG, 'mail', '1') === '1',
'alert_email' => $mail !== '' ? $mail : (string) (get_setting('admin_email', '') ?: (config()['site']['admin_email'] ?? '')),
];
}
function ueberwachung_types(): array
{
return ['http' => 'Webseite (HTTP/HTTPS)', 'port' => 'Port (TCP)', 'tls' => 'Zertifikat eines Dienstes (TLS-Port)'];
}
/** Prüft die Eingaben eines Überwachungsziels. @return array{ok:bool,error?:string,data?:array} */
function ueberwachung_validate(array $in): array
{
$name = trim((string) ($in['name'] ?? ''));
$type = (string) ($in['type'] ?? 'http');
$target = trim((string) ($in['target'] ?? ''));
if ($name === '' || mb_strlen($name) > 120) return ['ok' => false, 'error' => 'Bitte einen Namen angeben (höchstens 120 Zeichen).'];
if (!isset(ueberwachung_types()[$type])) return ['ok' => false, 'error' => 'Unbekannte Art der Prüfung.'];
if ($type === 'http') {
$p = parse_url($target);
if (!$p || !in_array($p['scheme'] ?? '', ['http', 'https'], true) || empty($p['host']) || preg_match('/[\s\x00-\x1F]/', $target)) return ['ok' => false, 'error' => 'Bitte eine Adresse mit http:// oder https:// angeben.'];
} else {
if (!preg_match('/^([A-Za-z0-9.-]{1,253}|\[[0-9a-fA-F:]+\]):(\d{1,5})$/', $target, $m) || (int) $m[2] < 1 || (int) $m[2] > 65535) return ['ok' => false, 'error' => 'Bitte Host und Port im Format host:port angeben (zum Beispiel mail.example.de:993).'];
}
return ['ok' => true, 'data' => [
'name' => $name, 'type' => $type, 'target' => mb_substr($target, 0, 500),
'expect_text' => $type === 'http' ? mb_substr(trim((string) ($in['expect_text'] ?? '')), 0, 200) : '',
'interval_min' => max(1, min(1440, (int) ($in['interval_min'] ?? 5))),
'timeout_sec' => max(2, min(30, (int) ($in['timeout_sec'] ?? 8))),
'cert_warn_days' => max(1, min(90, (int) ($in['cert_warn_days'] ?? 14))),
'verify_tls' => array_key_exists('verify_tls', $in) ? (!empty($in['verify_tls']) ? 1 : 0) : 1,
'is_active' => array_key_exists('is_active', $in) ? (!empty($in['is_active']) ? 1 : 0) : 1,
]];
}
function ueberwachung_save(PDO $pdo, array $in, int $id = 0): array
{
$v = ueberwachung_validate($in);
if (!$v['ok']) return $v;
$d = $v['data'];
if ($id === 0) {
$pdo->prepare('INSERT INTO plugin_ueberwachung_monitors (name, type, target, expect_text, interval_min, timeout_sec, cert_warn_days, verify_tls, is_active, created_at) VALUES (?,?,?,?,?,?,?,?,?,?)')
->execute([$d['name'], $d['type'], $d['target'], $d['expect_text'], $d['interval_min'], $d['timeout_sec'], $d['cert_warn_days'], $d['verify_tls'], $d['is_active'], db_now()]);
return ['ok' => true, 'id' => (int) $pdo->lastInsertId()];
}
$pdo->prepare('UPDATE plugin_ueberwachung_monitors SET name=?, type=?, target=?, expect_text=?, interval_min=?, timeout_sec=?, cert_warn_days=?, verify_tls=?, is_active=? WHERE id=?')
->execute([$d['name'], $d['type'], $d['target'], $d['expect_text'], $d['interval_min'], $d['timeout_sec'], $d['cert_warn_days'], $d['verify_tls'], $d['is_active'], $id]);
return ['ok' => true, 'id' => $id];
}
function ueberwachung_delete(PDO $pdo, int $id): void
{
$pdo->prepare('DELETE FROM plugin_ueberwachung_events WHERE monitor_id = ?')->execute([$id]);
$pdo->prepare('DELETE FROM plugin_ueberwachung_monitors WHERE id = ?')->execute([$id]);
}
// ── Prüfung ────────────────────────────────────────────────────────────────
/** Eine Prüfung ausführen. @return array{ok:bool,error:?string,ms:int,cert_expires:?int} (für Tests über $GLOBALS['ueberwachung_probe'] austauschbar) */
function ueberwachung_probe(array $m): array
{
if (isset($GLOBALS['ueberwachung_probe']) && is_callable($GLOBALS['ueberwachung_probe'])) return ($GLOBALS['ueberwachung_probe'])($m);
$timeout = max(2, (int) $m['timeout_sec']);
$start = microtime(true);
$ms = fn() => (int) round((microtime(true) - $start) * 1000);
$verifyTls = !isset($m['verify_tls']) || (int) $m['verify_tls'] === 1;
$ssl = ['capture_peer_cert' => true, 'verify_peer' => $verifyTls, 'verify_peer_name' => $verifyTls];
$certInfo = [];
$certTs = function ($ctx) use (&$certInfo): ?int {
$params = stream_context_get_params($ctx);
$cert = $params['options']['ssl']['peer_certificate'] ?? null;
if (!$cert) return null;
$info = @openssl_x509_parse($cert);
if (!$info) return null;
$certInfo = ['issuer' => (string) ($info['issuer']['O'] ?? $info['issuer']['CN'] ?? ''), 'cert_subject' => (string) ($info['subject']['CN'] ?? '')];
return (int) $info['validTo_time_t'];
};
if ($m['type'] === 'http' && function_exists('curl_init') && empty($GLOBALS['ueberwachung_no_curl'])) return ueberwachung_probe_curl($m, $timeout);
if ($m['type'] === 'http') {
$ctx = stream_context_create(['http' => ['method' => 'GET', 'timeout' => $timeout, 'ignore_errors' => true, 'follow_location' => 1, 'max_redirects' => 5, 'header' => "User-Agent: DeskHub-Ueberwachung\r\nAccept: */*\r\n"], 'ssl' => $ssl]);
$old = ini_set('default_socket_timeout', (string) $timeout);
$warnings = [];
set_error_handler(function (int $no, string $str) use (&$warnings): bool { $warnings[] = $str; return true; });
try {
$fh = fopen((string) $m['target'], 'r', false, $ctx);
} finally {
restore_error_handler();
}
if ($old !== false) ini_set('default_socket_timeout', (string) $old);
if (!$fh) {
return ['ok' => false, 'error' => ueberwachung_describe_error(implode(' | ', $warnings)), 'ms' => $ms(), 'cert_expires' => null];
}
stream_set_timeout($fh, $timeout);
$body = (string) stream_get_contents($fh, 65536);
$meta = stream_get_meta_data($fh);
fclose($fh);
$status = 0;
foreach ((array) ($meta['wrapper_data'] ?? []) as $h) if (is_string($h) && preg_match('#^HTTP/\S+\s+(\d+)#', $h, $mm)) $status = (int) $mm[1];
$cert = $certTs($ctx);
$extra = $certInfo + ['status' => $status, 'title' => ueberwachung_page_title($body)];
if ($status < 200 || $status >= 400) return ['ok' => false, 'error' => 'HTTP-Status ' . ($status ?: 'unbekannt'), 'ms' => $ms(), 'cert_expires' => $cert] + $extra;
if ($m['expect_text'] !== '' && !str_contains($body, (string) $m['expect_text'])) return ['ok' => false, 'error' => 'Der erwartete Text fehlt auf der Seite.', 'ms' => $ms(), 'cert_expires' => $cert] + $extra;
if ($m['expect_text'] === '' && ($why = ueberwachung_default_page($extra['title'], $body))) return ['ok' => false, 'error' => $why, 'ms' => $ms(), 'cert_expires' => $cert] + $extra;
return ['ok' => true, 'error' => null, 'ms' => $ms(), 'cert_expires' => $cert] + $extra;
}
[$host, $port] = [preg_replace('/:\d+$/', '', (string) $m['target']), (int) substr((string) strrchr((string) $m['target'], ':'), 1)];
$isTls = $m['type'] === 'tls';
$ctx = stream_context_create(['ssl' => $ssl + ['peer_name' => trim($host, '[]')]]);
$fh = @stream_socket_client(($isTls ? 'ssl://' : 'tcp://') . $host . ':' . $port, $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $ctx);
if (!$fh) return ['ok' => false, 'error' => ueberwachung_describe_error((string) $errstr ?: 'connection refused'), 'ms' => $ms(), 'cert_expires' => null];
$cert = $isTls ? $certTs($ctx) : null;
fclose($fh);
return ['ok' => true, 'error' => null, 'ms' => $ms(), 'cert_expires' => $cert] + $certInfo;
}
/** Kennt dieses PHP keine vertrauenswürdigen Zertifizierungsstellen? Dann scheitert jede HTTPS-Prüfung mit „Zertifikat ungültig“, auch bei gesunden Seiten. */
function ueberwachung_ca_bundle_missing(): bool
{
// Mit open_basedir (bei Plesk üblich) lassen sich die Dateien nicht prüfen: dann nichts behaupten
if ((string) ini_get('open_basedir') !== '') return false;
foreach ([(string) ini_get('curl.cainfo'), (string) ini_get('openssl.cafile'), '/etc/ssl/certs/ca-certificates.crt', '/etc/pki/tls/certs/ca-bundle.crt', '/etc/ssl/cert.pem'] as $file) {
if ($file !== '' && is_file($file)) return false;
}
$loc = function_exists('openssl_get_cert_locations') ? openssl_get_cert_locations() : [];
if (!empty($loc['default_cert_file']) && is_file($loc['default_cert_file'])) return false;
$dir = (string) ($loc['default_cert_dir'] ?? '');
return !($dir !== '' && is_dir($dir) && (glob($dir . '/*') ?: []));
}
/** Prüfung einer Webseite mit cURL: genaue Fehlertexte, HTTP-Status und Zertifikatsdaten. */
function ueberwachung_probe_curl(array $m, int $timeout): array
{
$verify = !isset($m['verify_tls']) || (int) $m['verify_tls'] === 1;
$body = '';
$ch = curl_init((string) $m['target']);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_MAXREDIRS => 5,
CURLOPT_TIMEOUT => $timeout, CURLOPT_CONNECTTIMEOUT => min($timeout, 10),
CURLOPT_USERAGENT => 'DeskHub-Ueberwachung', CURLOPT_HTTPHEADER => ['Accept: */*'],
CURLOPT_SSL_VERIFYPEER => $verify, CURLOPT_SSL_VERIFYHOST => $verify ? 2 : 0, CURLOPT_CERTINFO => true,
CURLOPT_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS,
// nur die ersten 64 KB lesen (reicht für den erwarteten Text)
CURLOPT_WRITEFUNCTION => function ($c, string $data) use (&$body): int {
$body .= $data;
return strlen($body) > 65536 ? 0 : strlen($data);
},
]);
$start = microtime(true);
$ok = curl_exec($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
$status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
$ms = (int) round((microtime(true) - $start) * 1000);
$cert = null;
$extra = [];
$info = curl_getinfo($ch, CURLINFO_CERTINFO);
if (is_array($info) && !empty($info[0]['Expire date'])) {
$ts = strtotime((string) $info[0]['Expire date']);
if ($ts) $cert = $ts;
$issuer = (string) ($info[0]['Issuer'] ?? '');
$subject = (string) ($info[0]['Subject'] ?? '');
$extra = ['issuer' => preg_match('/O\s*=\s*([^,\/]+)/', $issuer, $x) ? trim($x[1]) : (preg_match('/CN\s*=\s*([^,\/]+)/', $issuer, $x) ? trim($x[1]) : ''), 'cert_subject' => preg_match('/CN\s*=\s*([^,\/]+)/', $subject, $x) ? trim($x[1]) : ''];
}
curl_close($ch);
$extra += ['status' => $status];
// Zertifikatsfehler: ohne Prüfung nachsehen, ob die Seite antwortet und was für ein Zertifikat sie hat
if ($ok === false && $verify && preg_match('/certificate|ssl|tls/i', $error)) {
$r2 = ueberwachung_probe_curl(array_merge($m, ['verify_tls' => 0]), $timeout);
$msg = ueberwachung_describe_error($error);
if (!empty($r2['cert_expires']) && $r2['cert_expires'] < time()) $msg = 'Zertifikat/TLS-Fehler (Zertifikat abgelaufen): Die gesicherte Verbindung kam nicht zustande';
if (ueberwachung_ca_bundle_missing()) $msg .= ' – möglicherweise fehlt auf diesem Server die Liste vertrauenswürdiger Zertifizierungsstellen (CA-Bundle). Das Ziel kann in Ordnung sein: Zertifikatsprüfung für dieses Ziel abschalten oder curl.cainfo/openssl.cafile in der PHP-Konfiguration setzen';
elseif (!empty($r2['status'])) $msg .= ' (die Seite antwortet ohne Prüfung mit HTTP ' . $r2['status'] . ')';
return ['ok' => false, 'error' => $msg, 'ms' => $ms, 'cert_expires' => $r2['cert_expires'] ?? null] + array_intersect_key($r2, ['issuer' => 1, 'cert_subject' => 1, 'status' => 1]);
}
// Abbruch durch unsere 64-KB-Grenze (Fehler 23) ist kein Fehler
if ($ok === false && !($errno === 23 && strlen($body) > 65536 && $status > 0)) {
return ['ok' => false, 'error' => ueberwachung_describe_error($error !== '' ? $error : 'curl error ' . $errno), 'ms' => $ms, 'cert_expires' => $cert] + $extra;
}
$extra['title'] = ueberwachung_page_title($body);
if ($status < 200 || $status >= 400) return ['ok' => false, 'error' => 'HTTP-Status ' . ($status ?: 'unbekannt'), 'ms' => $ms, 'cert_expires' => $cert] + $extra;
if ($m['expect_text'] !== '' && !str_contains($body, (string) $m['expect_text'])) return ['ok' => false, 'error' => 'Der erwartete Text fehlt auf der Seite.', 'ms' => $ms, 'cert_expires' => $cert] + $extra;
if ($m['expect_text'] === '' && ($why = ueberwachung_default_page($extra['title'], $body))) return ['ok' => false, 'error' => $why, 'ms' => $ms, 'cert_expires' => $cert] + $extra;
return ['ok' => true, 'error' => null, 'ms' => $ms, 'cert_expires' => $cert] + $extra;
}
function ueberwachung_event(PDO $pdo, int $monitorId, string $kind, string $message): void
{
$pdo->prepare('INSERT INTO plugin_ueberwachung_events (monitor_id, kind, message, created_at) VALUES (?,?,?,?)')->execute([$monitorId, $kind, mb_substr($message, 0, 400), db_now()]);
}
/** Mail an den Administrator (für Tests über $GLOBALS['ueberwachung_mail'] austauschbar). */
function ueberwachung_alert(string $subject, string $html): void
{
$cfg = ueberwachung_config();
if (!$cfg['mail']) return;
foreach (preg_split('/[,;\s]+/', $cfg['alert_email'], -1, PREG_SPLIT_NO_EMPTY) ?: [] as $to) {
if (!filter_var($to, FILTER_VALIDATE_EMAIL)) continue;
try {
if (isset($GLOBALS['ueberwachung_mail']) && is_callable($GLOBALS['ueberwachung_mail'])) ($GLOBALS['ueberwachung_mail'])($to, $subject, $html);
else send_mail($to, $subject, $html);
} catch (Throwable $e) {
error_log('ueberwachung mail: ' . $e->getMessage());
}
}
}
function ueberwachung_duration(int $seconds): string
{
if ($seconds < 90) return $seconds . ' Sekunden';
if ($seconds < 5400) return round($seconds / 60) . ' Minuten';
if ($seconds < 172800) return round($seconds / 3600, 1) . ' Stunden';
return round($seconds / 86400, 1) . ' Tage';
}
/**
* Legt ein Ticket ohne Ticket-Regeln, Absender-Sperre und Antwort-Mail an. Das ist der Rückfall, wenn das normale Anlegen scheitert:
* Eine Störungsmeldung darf nicht daran hängen, dass eine Regel („Spam ablehnen“) oder die Sperrliste die eigene Adresse trifft.
*/
function ueberwachung_create_direct(PDO $pdo, string $email, string $subject, string $message, ?int $deptId, ?int $prioId): int
{
$deptId = active_department_id($pdo, $deptId ?: (int) get_setting('default_department_id', '1'));
if (!$deptId) throw new RuntimeException('Es ist keine Abteilung eingerichtet.');
if (!$prioId) $prioId = (int) $pdo->query('SELECT id FROM priorities ORDER BY sort_order LIMIT 1')->fetchColumn();
$p = $pdo->prepare('SELECT * FROM priorities WHERE id = ?');
$p->execute([$prioId]);
$priority = $p->fetch();
if (!$priority) throw new RuntimeException('Die Priorität gibt es nicht.');
$sla = ['first_response_due_at' => null, 'resolution_due_at' => null];
try { $sla = calc_sla_dates($priority, null, $deptId, null); } catch (Throwable $e) { /* ohne Fristen */ }
$number = generate_ticket_number($pdo);
$now = db_now();
$pdo->prepare('INSERT INTO tickets (ticket_number, subject, requester_name, requester_email, department_id, priority_id, status, source, requester_ip, first_response_due_at, resolution_due_at, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)')
->execute([$number, mb_substr($subject, 0, 250), 'Überwachung', $email, $deptId, $prioId, 'open', 'api', '0.0.0.0', $sla['first_response_due_at'] ?? null, $sla['resolution_due_at'] ?? null, $now, $now]);
$id = (int) $pdo->lastInsertId();
$pdo->prepare("INSERT INTO ticket_threads (ticket_id, author_type, message, is_internal_note, created_at) VALUES (?, 'customer', ?, 0, ?)")->execute([$id, $message, $now]);
log_activity($pdo, $id, null, 'Ticket von der Überwachung angelegt');
apply_tag_to_ticket($pdo, $id, 'Überwachung');
$d = $pdo->prepare('SELECT name FROM departments WHERE id = ?');
$d->execute([$deptId]);
try {
notify_staff_new_ticket(['ticket_number' => $number, 'subject' => $subject, 'requester_name' => 'Überwachung', 'requester_email' => $email, 'department_id' => $deptId, 'department_name' => $d->fetchColumn() ?: null]);
} catch (Throwable $e) { /* Benachrichtigung ist nachrangig */ }
try { webhook_dispatch($pdo, 'ticket.created', $id); } catch (Throwable $e) { /* dito */ }
return $id;
}
/** Legt ein Ticket an (erst auf dem normalen Weg, sonst direkt). Merkt sich den letzten Fehler für die Seite. @return int|null Ticket-ID */
function ueberwachung_open_ticket(PDO $pdo, string $subject, string $message): ?int
{
$cfg = ueberwachung_config();
if (!$cfg['create_tickets']) return null;
$first = preg_split('/[,;\s]+/', $cfg['alert_email'], -1, PREG_SPLIT_NO_EMPTY)[0] ?? '';
$email = filter_var($first, FILTER_VALIDATE_EMAIL) ? $first : 'ueberwachung@system.invalid';
$why = '';
try {
$r = public_ticket_create($pdo, [
'name' => 'Überwachung', 'email' => $email, 'subject' => mb_substr($subject, 0, 250), 'message' => $message,
'departmentId' => $cfg['department_id'] ?: null, 'priorityId' => $cfg['priority_id'] ?: null,
], '0.0.0.0', ['activity' => 'Ticket von der Überwachung angelegt', 'tag' => 'Überwachung']);
plugin_set_setting(UEBERWACHUNG, 'ticket_error', '');
return (int) $r['id'];
} catch (Throwable $e) {
$why = $e->getMessage();
error_log('ueberwachung ticket: ' . $why);
}
// Ist das Ticket trotz Fehler (zum Beispiel bei der Benachrichtigung) schon angelegt worden, nicht doppelt anlegen
$dup = $pdo->prepare("SELECT id FROM tickets WHERE subject = ? AND requester_name = 'Überwachung' AND created_at >= ? ORDER BY id DESC LIMIT 1");
$dup->execute([mb_substr($subject, 0, 250), date('Y-m-d H:i:s', time() - 120)]);
if ($id = $dup->fetchColumn()) { plugin_set_setting(UEBERWACHUNG, 'ticket_error', db_now() . ': ' . $why . ' (Ticket wurde trotzdem angelegt)'); return (int) $id; }
try {
$id = ueberwachung_create_direct($pdo, $email, $subject, $message, $cfg['department_id'] ?: null, $cfg['priority_id'] ?: null);
plugin_set_setting(UEBERWACHUNG, 'ticket_error', db_now() . ': Das Ticket musste am normalen Weg vorbei angelegt werden, weil dort abgelehnt wurde: ' . $why);
return $id;
} catch (Throwable $e) {
error_log('ueberwachung ticket (direkt): ' . $e->getMessage());
plugin_set_setting(UEBERWACHUNG, 'ticket_error', db_now() . ': Ticket konnte nicht angelegt werden: ' . $why . ' / ' . $e->getMessage());
return null;
}
}
/** Setzt das Ticket auf „Gelöst“ und vermerkt die Entwarnung (nur wenn es noch offen ist und die Einstellung es erlaubt). */
function ueberwachung_resolve_ticket(PDO $pdo, ?int $ticketId, string $note): void
{
if (!$ticketId) return;
$s = $pdo->prepare('SELECT status FROM tickets WHERE id = ?');
$s->execute([$ticketId]);
$status = $s->fetchColumn();
if ($status === false) return;
$pdo->prepare("INSERT INTO ticket_threads (ticket_id, author_type, message, is_internal_note, created_at) VALUES (?, 'system', ?, 1, ?)")->execute([$ticketId, $note, db_now()]);
log_activity($pdo, $ticketId, null, 'Überwachung: ' . $note);
if (!ueberwachung_config()['auto_resolve'] || in_array($status, ['resolved', 'closed'], true)) return;
$now = db_now();
$pdo->prepare("UPDATE tickets SET status = 'resolved', resolved_at = ?, updated_at = ? WHERE id = ?")->execute([$now, $now, $ticketId]);
webhook_dispatch($pdo, 'ticket.status_changed', $ticketId, ['previousStatus' => (string) $status]);
}
/** Wertet ein Prüfergebnis aus: Zustand, Ticket, Mail, Entwarnung. */
function ueberwachung_apply(PDO $pdo, array $m, array $res): void
{
$cfg = ueberwachung_config();
$now = db_now();
$id = (int) $m['id'];
$certStr = $res['cert_expires'] ? date('Y-m-d H:i:s', (int) $res['cert_expires']) : ($m['cert_expires'] ?? null);
$upd = $pdo->prepare('UPDATE plugin_ueberwachung_monitors SET last_check_at = ?, last_ms = ?, cert_expires = ?, last_status = ?, last_title = ? WHERE id = ?');
$upd->execute([$now, $res['ms'], $certStr, !empty($res['status']) ? (int) $res['status'] : null, isset($res['title']) && $res['title'] !== '' ? mb_substr((string) $res['title'], 0, 150) : null, $id]);
if ($res['ok']) {
$wasDown = $m['state'] === 'down';
$pdo->prepare("UPDATE plugin_ueberwachung_monitors SET state = 'up', fails = 0, last_ok_at = ?, last_error = NULL, down_since = NULL, first_fail_at = NULL, ticket_id = ? WHERE id = ?")->execute([$now, $wasDown ? null : $m['ticket_id'], $id]);
if ($wasDown) {
$dur = $m['down_since'] ? ueberwachung_duration(max(0, time() - (int) strtotime((string) $m['down_since']))) : 'unbekannt';
ueberwachung_event($pdo, $id, 'up', 'Wieder erreichbar nach ' . $dur . '.');
ueberwachung_resolve_ticket($pdo, $m['ticket_id'] ? (int) $m['ticket_id'] : null, ueberwachung_up_note($m, $dur));
ueberwachung_alert(ueberwachung_subject('Entwarnung', $m) . ' ist wieder erreichbar', '<p><strong>' . e($m['name']) . '</strong> ist wieder erreichbar.</p>' . ueberwachung_table([['Dienst', (string) $m['name']], ['Adresse', (string) $m['target']], ['Ausfall', ueberwachung_dt((string) ($m['first_fail_at'] ?? $m['down_since'] ?? '')) . ' bis ' . date('d.m.Y H:i:s')], ['Dauer', $dur], ['Antwortzeit jetzt', (int) $res['ms'] . ' ms']]));
}
} else {
$fails = (int) $m['fails'] + 1;
$firstFail = ($fails === 1 || empty($m['first_fail_at'])) ? $now : (string) $m['first_fail_at'];
$pdo->prepare('UPDATE plugin_ueberwachung_monitors SET fails = ?, last_error = ?, first_fail_at = ? WHERE id = ?')->execute([$fails, mb_substr((string) $res['error'], 0, 300), $firstFail, $id]);
if ($fails >= $cfg['threshold'] && $m['state'] !== 'down') {
$body = ueberwachung_down_body($m, $res, $fails, $firstFail);
$ticket = ueberwachung_open_ticket($pdo, ueberwachung_subject('Ausfall', $m), $body);
$pdo->prepare("UPDATE plugin_ueberwachung_monitors SET state = 'down', down_since = ?, ticket_id = ? WHERE id = ?")->execute([$firstFail, $ticket, $id]);
ueberwachung_event($pdo, $id, 'down', 'Ausfall: ' . $res['error'] . ($ticket ? '' : ($cfg['create_tickets'] ? ' (Ticket konnte nicht angelegt werden, siehe Hinweis oben)' : ' (Tickets sind ausgeschaltet)')));
ueberwachung_alert(ueberwachung_subject('Ausfall', $m), $body);
} elseif ($fails < $cfg['threshold'] && $m['state'] === 'unknown') {
$pdo->prepare("UPDATE plugin_ueberwachung_monitors SET state = 'up' WHERE id = ? AND state = 'unknown'")->execute([$id]);
}
}
// Zertifikat
if ($res['cert_expires']) {
$days = (int) floor(((int) $res['cert_expires'] - time()) / 86400);
$warn = (int) $m['cert_warn_days'];
if ($days <= $warn && !$m['cert_ticket_id']) {
$text = $days < 0 ? 'Das Zertifikat von ' . $m['name'] . ' ist seit ' . abs($days) . ' Tagen abgelaufen.' : 'Das Zertifikat von ' . $m['name'] . ' läuft in ' . $days . ' Tagen ab (' . date('d.m.Y', (int) $res['cert_expires']) . ').';
$certBody = ueberwachung_cert_body($m, $res, $days);
$ticket = ueberwachung_open_ticket($pdo, ueberwachung_subject('Zertifikat', $m), $certBody);
$pdo->prepare('UPDATE plugin_ueberwachung_monitors SET cert_ticket_id = ? WHERE id = ?')->execute([$ticket ?: -1, $id]);
ueberwachung_event($pdo, $id, 'cert', $text);
ueberwachung_alert(ueberwachung_subject($days < 0 ? 'Zertifikat abgelaufen' : 'Zertifikat läuft bald ab', $m), $certBody);
} elseif ($days > $warn && $m['cert_ticket_id']) {
$pdo->prepare('UPDATE plugin_ueberwachung_monitors SET cert_ticket_id = NULL WHERE id = ?')->execute([$id]);
ueberwachung_event($pdo, $id, 'cert_ok', 'Zertifikat erneuert, gültig bis ' . date('d.m.Y', (int) $res['cert_expires']) . '.');
ueberwachung_resolve_ticket($pdo, (int) $m['cert_ticket_id'] > 0 ? (int) $m['cert_ticket_id'] : null, 'Zertifikat erneuert (' . $m['name'] . '), gültig bis ' . date('d.m.Y', (int) $res['cert_expires']) . '.');
ueberwachung_alert('Zertifikat erneuert: ' . $m['name'], '<p>Das Zertifikat von <strong>' . e($m['name']) . '</strong> wurde erneuert und ist gültig bis ' . e(date('d.m.Y', (int) $res['cert_expires'])) . '.</p>');
}
}
}
/** Prüft ein Ziel jetzt. */
function ueberwachung_check(PDO $pdo, int $id): bool
{
$s = $pdo->prepare('SELECT * FROM plugin_ueberwachung_monitors WHERE id = ?');
$s->execute([$id]);
$m = $s->fetch();
if (!$m) return false;
try {
$res = ueberwachung_probe($m);
} catch (Throwable $e) {
$res = ['ok' => false, 'error' => 'Prüfung fehlgeschlagen: ' . mb_substr($e->getMessage(), 0, 150), 'ms' => 0, 'cert_expires' => null];
}
ueberwachung_apply($pdo, $m, $res);
return true;
}
/** Wartezeit bis zur nächsten Prüfung in Sekunden: der eingestellte Abstand, nach einem ersten Fehlschlag (Ausfall noch nicht gemeldet) nur eine Minute. */
function ueberwachung_next_wait(array $m): int
{
if ((int) ($m['fails'] ?? 0) > 0 && ($m['state'] ?? '') !== 'down') return 45;
return max(45, (int) $m['interval_min'] * 60 - 15);
}
/** Hintergrundlauf: fällige Ziele prüfen (höchstens 6 pro Lauf, damit der Lauf kurz bleibt). */
function ueberwachung_tick(PDO $pdo): int
{
plugin_set_setting(UEBERWACHUNG, 'last_tick', (string) time());
$due = [];
foreach ($pdo->query('SELECT id, interval_min, last_check_at, fails, state FROM plugin_ueberwachung_monitors WHERE is_active = 1 ORDER BY last_check_at')->fetchAll() as $m) {
if ($m['last_check_at'] === null || time() - (int) strtotime((string) $m['last_check_at']) >= ueberwachung_next_wait($m)) $due[] = (int) $m['id'];
if (count($due) >= 6) break;
}
foreach ($due as $id) ueberwachung_check($pdo, $id);
if ($due && time() - (int) plugin_setting(UEBERWACHUNG, 'last_prune', '0') > 86400) {
plugin_set_setting(UEBERWACHUNG, 'last_prune', (string) time());
$pdo->prepare('DELETE FROM plugin_ueberwachung_events WHERE created_at < ?')->execute([date('Y-m-d H:i:s', time() - 90 * 86400)]);
}
return count($due);
}
plugin_add_hook('plugin.uninstall.' . UEBERWACHUNG, function () {
try {
get_db()->exec('DROP TABLE IF EXISTS plugin_ueberwachung_events');
get_db()->exec('DROP TABLE IF EXISTS plugin_ueberwachung_monitors');
} catch (Throwable $e) {
}
});
+168
View File
@@ -0,0 +1,168 @@
<?php
// Texte der Überwachung: lesbare Fehler und der Aufbau der Tickets und Mails. Alle Funktionen beginnen mit ueberwachung_.
/** Rohe PHP-Fehlermeldung in verständliches Deutsch übersetzen. Beginnt mit „Nicht erreichbar:“ oder „Zertifikat/TLS-Fehler:“. */
function ueberwachung_describe_error(string $raw): string
{
$r = strtolower($raw);
if (preg_match('/getaddrinfo|php_network_getaddresses|name or service not known|nodename nor servname|temporary failure in name resolution|no address associated|could not resolve host/', $r)) return 'Nicht erreichbar: Der Name der Adresse lässt sich nicht auflösen (DNS)';
if (str_contains($r, 'connection refused')) return 'Nicht erreichbar: Verbindung abgelehnt (der Dienst läuft nicht oder der Port ist gesperrt)';
if (preg_match('/timed out|timeout|zeitüberschreitung/', $r)) return 'Nicht erreichbar: Zeitüberschreitung (keine Antwort vom Server)';
if (preg_match('/no route to host|network is unreachable/', $r)) return 'Nicht erreichbar: Der Server ist aus dem Netz nicht erreichbar';
if (preg_match('/certificate|ssl|tls|handshake/', $r)) {
$why = preg_match('/expired/', $r) ? ' (Zertifikat abgelaufen)' : (preg_match('/verify failed|self.signed|unable to get local issuer|certificate problem|does not match|no alternative certificate subject/', $r) ? ' (Zertifikat ungültig oder nicht vertrauenswürdig)' : '');
return 'Zertifikat/TLS-Fehler' . $why . ': Die gesicherte Verbindung kam nicht zustande';
}
return 'Nicht erreichbar: Die Verbindung kam nicht zustande (Dienst aus, Port zu oder Problem mit der gesicherten Verbindung)';
}
function ueberwachung_host(string $target): string
{
$h = parse_url($target, PHP_URL_HOST);
return (string) ($h ?: preg_replace('/:\d+$/', '', $target));
}
/** Betreff mit Name und Adresse (die Adresse entfällt, wenn der Name sie schon enthält). */
function ueberwachung_subject(string $prefix, array $m): string
{
$host = ueberwachung_host((string) $m['target']);
return $prefix . ': ' . $m['name'] . (stripos((string) $m['name'], $host) === false ? ' (' . $host . ')' : '');
}
function ueberwachung_type_label(string $type): string
{
return ueberwachung_types()[$type] ?? $type;
}
/** Zweispaltige Tabelle: Bezeichnung → Wert (beides wird maskiert). @param list<array{0:string,1:string}> $rows */
function ueberwachung_table(array $rows): string
{
$html = '<table border="0" cellpadding="5" cellspacing="0">';
foreach ($rows as [$k, $v]) $html .= '<tr><td><strong>' . e($k) . '</strong></td><td>' . e($v) . '</td></tr>';
return $html . '</table>';
}
function ueberwachung_dt(?string $dt): string
{
return $dt ? date('d.m.Y H:i:s', (int) strtotime($dt)) : '–';
}
/** Zeilen zu einem Zertifikat. @return list<array{0:string,1:string}> */
function ueberwachung_cert_rows(array $m, array $res, ?int $days = null): array
{
if (empty($res['cert_expires'])) return [];
$days ??= (int) floor(((int) $res['cert_expires'] - time()) / 86400);
$rows = [['Zertifikat gültig bis', date('d.m.Y H:i', (int) $res['cert_expires']) . ($days < 0 ? ' (seit ' . abs($days) . ' Tagen abgelaufen)' : ' (noch ' . $days . ' Tage)')]];
if (!empty($res['issuer'])) $rows[] = ['Aussteller', (string) $res['issuer']];
if (!empty($res['cert_subject'])) $rows[] = ['Ausgestellt für', (string) $res['cert_subject']];
return $rows;
}
/** Hinweise zur Fehlersuche je nach Art und Fehler. @return list<string> */
function ueberwachung_hints(array $m, string $error): array
{
$e = strtolower($error);
if (str_starts_with($error, 'Zertifikat')) return ['Zertifikat prüfen: abgelaufen, falscher Name oder fehlende Zwischenzertifikate?', 'Zertifikat erneuern (zum Beispiel Let’s Encrypt in Plesk) und die Seite im Browser öffnen.'];
if (preg_match('/http-status 5\d\d/', $e)) return ['Der Server antwortet, aber die Anwendung meldet einen Fehler: Fehlerprotokoll des Webservers und der Anwendung ansehen.', 'Datenbank, Speicherplatz und PHP-Prozess prüfen.', 'Kürzlich eingespielte Änderungen oder Updates zurücknehmen.'];
if (preg_match('/http-status 4\d\d/', $e)) return ['Die Adresse antwortet mit einem Fehler (zum Beispiel 404 oder 403): Adresse, Weiterleitung und Zugriffsschutz prüfen.'];
if (str_contains($e, 'standard- oder fehlerseite')) return ['Der Server liefert nur seine Standard- oder Fehlerseite aus: Ist der Eintrag im Reverse-Proxy (zum Beispiel Nginx Proxy Manager) aktiviert, und läuft der Dienst dahinter?', 'Adresse und Port des Ziels im Proxy prüfen und den Dienst dahinter ansehen.'];
if (str_contains($e, 'text fehlt')) return ['Die Seite antwortet, enthält aber nicht den erwarteten Text: Wartungsseite, Fehlerseite oder veränderter Inhalt?'];
if (str_contains($e, 'dns')) return ['DNS-Eintrag der Adresse prüfen (Domain abgelaufen? Eintrag geändert?).'];
$hints = ['Läuft der Server und der Dienst? Neustart des Webservers bzw. Dienstes versuchen.', 'Firewall und Port-Freigaben prüfen.'];
if ($m['type'] === 'http') $hints[] = 'Die Seite einmal im Browser und von einem anderen Netz aus öffnen, um ein lokales Problem auszuschließen.';
return $hints;
}
function ueberwachung_hint_list(array $hints): string
{
return '<h3>Mögliche Ursachen und nächste Schritte</h3><ul>' . implode('', array_map(fn($h) => '<li>' . e($h) . '</li>', $hints)) . '</ul>';
}
/** Text des Ausfall-Tickets. */
function ueberwachung_down_body(array $m, array $res, int $fails, ?string $firstFail): string
{
$rows = [
['Dienst', (string) $m['name']],
['Art der Prüfung', ueberwachung_type_label((string) $m['type'])],
['Adresse', (string) $m['target']],
['Zustand', 'Ausfall'],
['Fehler', (string) $res['error']],
];
if (!empty($res['status'])) $rows[] = ['HTTP-Status', (string) $res['status']];
$rows[] = ['Seit', ueberwachung_dt($firstFail) . ($firstFail ? ' (vor ' . ueberwachung_duration(max(0, time() - (int) strtotime($firstFail))) . ')' : '')];
$rows[] = ['Fehlgeschlagene Prüfungen in Folge', $fails . ' (Prüfung alle ' . (int) $m['interval_min'] . ' Minuten, Ausfall ab ' . ueberwachung_config()['threshold'] . ' in Folge)'];
$rows[] = ['Letzter erfolgreicher Abruf', $m['last_ok_at'] ? ueberwachung_dt((string) $m['last_ok_at']) : 'noch nie'];
$rows[] = ['Dauer der letzten Prüfung', (int) $res['ms'] . ' ms (Zeitlimit ' . (int) $m['timeout_sec'] . ' Sekunden)'];
if (!empty($m['expect_text'])) $rows[] = ['Erwarteter Text', (string) $m['expect_text']];
foreach (ueberwachung_cert_rows($m, $res) as $r) $rows[] = $r;
$rows[] = ['Geprüft von', (string) (gethostname() ?: 'DeskHub-Server') . ', ' . date('d.m.Y H:i:s')];
return '<p><strong>' . e($m['name']) . '</strong> ist nicht erreichbar bzw. fehlerhaft.</p>' . ueberwachung_table($rows)
. ueberwachung_hint_list(ueberwachung_hints($m, (string) $res['error']))
. '<p><em>Diese Meldung stammt von der automatischen Überwachung. Sobald der Dienst wieder erreichbar ist, wird das Ticket automatisch gelöst.</em></p>';
}
/** Text des Zertifikat-Tickets. */
function ueberwachung_cert_body(array $m, array $res, int $days): string
{
$headline = $days < 0 ? 'Das Zertifikat ist seit ' . abs($days) . ' Tagen abgelaufen.' : 'Das Zertifikat läuft in ' . $days . ' Tagen ab.';
$rows = array_merge([
['Dienst', (string) $m['name']],
['Art der Prüfung', ueberwachung_type_label((string) $m['type'])],
['Adresse', (string) $m['target']],
], ueberwachung_cert_rows($m, $res, $days), [
['Warnung ab', (int) $m['cert_warn_days'] . ' Tagen vor Ablauf'],
['Geprüft von', (string) (gethostname() ?: 'DeskHub-Server') . ', ' . date('d.m.Y H:i:s')],
]);
return '<p><strong>' . e($headline) . '</strong></p>' . ueberwachung_table($rows)
. ueberwachung_hint_list(['Zertifikat erneuern (zum Beispiel Let’s Encrypt in Plesk oder beim Anbieter).', 'Nach der Erneuerung die Seite im Browser öffnen und die Kette prüfen.', 'Bei automatischer Erneuerung: prüfen, warum sie nicht gelaufen ist.'])
. '<p><em>Nach der Erneuerung wird dieses Ticket automatisch gelöst.</em></p>';
}
/** Interne Notiz bei Entwarnung (Ausfall). */
function ueberwachung_up_note(array $m, string $dur): string
{
$since = $m['first_fail_at'] ?? $m['down_since'] ?? null;
return 'Wieder erreichbar (' . $m['name'] . '). Der Ausfall dauerte ' . $dur . '.'
. ($since ? ' Von ' . ueberwachung_dt((string) $since) . ' bis ' . date('d.m.Y H:i:s') . '.' : '');
}
/** Titel der Seite (für Anzeige und die Erkennung von Standard- und Fehlerseiten). */
function ueberwachung_page_title(string $body): string
{
if (!preg_match('/<title[^>]*>(.*?)<\/title>/is', $body, $m)) return '';
return mb_substr(trim((string) preg_replace('/\s+/u', ' ', html_entity_decode(strip_tags($m[1]), ENT_QUOTES | ENT_HTML5, 'UTF-8'))), 0, 150);
}
/**
* Antwortet ein Server mit 200, liefert aber nur seine Standard- oder Fehlerseite (zum Beispiel ein abgeschalteter Eintrag im Proxy), ist das
* Ziel trotzdem ausgefallen. Erkannt wird das am Seitentitel. Mit „erwartetem Text“ am Ziel entfällt diese Prüfung. @return string|null Fehlertext
*/
function ueberwachung_default_page(string $title, string $body = ''): ?string
{
// Titel bekannter Standard- und Fehlerseiten (Nginx Proxy Manager: „Default Site“)
if ($title !== '' && preg_match('/^default site$|congratulations|welcome to nginx|nginx.*default|default (web )?(server )?page|test page for|apache2? .*default page|^it works!?$|^index of \/|iis windows server|^welcome to openresty|bad gateway|service (temporarily )?unavailable|gateway time-?out|^50[234]\b|^404\b|not found$/i', $title)) {
return 'Der Server antwortet mit einer Standard- oder Fehlerseite statt mit der Anwendung (Seitentitel: „' . mb_substr($title, 0, 80) . '“)';
}
// Typische Sätze der Standardseiten, auch wenn der Titel nichtssagend ist
if ($body !== '' && preg_match('/successfully started the nginx proxy manager|trying to access a host that isn.?t set up yet|if you see this page, the nginx web server is successfully installed|apache2 (ubuntu|debian) default page|this is the default welcome page|web server\'s default page|domain (is )?(not configured|parked)/i', $body, $m)) {
return 'Der Server antwortet mit einer Standardseite statt mit der Anwendung (Text auf der Seite: „' . mb_substr($m[0], 0, 80) . '“)';
}
return null;
}
/**
* Soll die Warnung „PHP kennt keine vertrauenswürdigen Zertifizierungsstellen“ erscheinen? Nur wenn das System es annimmt UND es auch so aussieht:
* Mindestens ein HTTPS-Ziel mit Zertifikatsprüfung scheitert an der Zertifikatsprüfung und keines wurde erfolgreich geprüft. Wird irgendeine
* HTTPS-Seite mit Prüfung erreicht, funktioniert die Prüfung, egal was die Dateisuche meint.
* @param list<array<string,mixed>> $monitors
*/
function ueberwachung_ca_warning(array $monitors, bool $systemSaysMissing): bool
{
if (!$systemSaysMissing) return false;
$bad = 0;
$good = 0;
foreach ($monitors as $m) {
if (($m['type'] ?? '') !== 'http' || !str_starts_with((string) $m['target'], 'https') || (int) ($m['verify_tls'] ?? 1) !== 1 || empty($m['last_check_at'])) continue;
if (str_starts_with((string) ($m['last_error'] ?? ''), 'Zertifikat/TLS-Fehler')) $bad++; else $good++;
}
return $bad > 0 && $good === 0;
}
@@ -0,0 +1,30 @@
CREATE TABLE IF NOT EXISTS plugin_ueberwachung_monitors (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(120) NOT NULL,
type VARCHAR(8) NOT NULL DEFAULT 'http',
target VARCHAR(500) NOT NULL,
expect_text VARCHAR(200) NOT NULL DEFAULT '',
interval_min INT NOT NULL DEFAULT 5,
timeout_sec INT NOT NULL DEFAULT 8,
cert_warn_days INT NOT NULL DEFAULT 14,
is_active TINYINT(1) NOT NULL DEFAULT 1,
state VARCHAR(8) NOT NULL DEFAULT 'unknown',
fails INT NOT NULL DEFAULT 0,
last_check_at DATETIME NULL,
last_ok_at DATETIME NULL,
last_error VARCHAR(300) NULL,
last_ms INT NULL,
cert_expires DATETIME NULL,
down_since DATETIME NULL,
ticket_id INT NULL,
cert_ticket_id INT NULL,
created_at DATETIME NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS plugin_ueberwachung_events (
id INT AUTO_INCREMENT PRIMARY KEY,
monitor_id INT NOT NULL,
kind VARCHAR(12) NOT NULL,
message VARCHAR(400) NOT NULL,
created_at DATETIME NOT NULL,
KEY idx_plugin_ueberwachung_events (monitor_id, id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
@@ -0,0 +1,30 @@
CREATE TABLE IF NOT EXISTS plugin_ueberwachung_monitors (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
type TEXT NOT NULL DEFAULT 'http',
target TEXT NOT NULL,
expect_text TEXT NOT NULL DEFAULT '',
interval_min INTEGER NOT NULL DEFAULT 5,
timeout_sec INTEGER NOT NULL DEFAULT 8,
cert_warn_days INTEGER NOT NULL DEFAULT 14,
is_active INTEGER NOT NULL DEFAULT 1,
state TEXT NOT NULL DEFAULT 'unknown',
fails INTEGER NOT NULL DEFAULT 0,
last_check_at TEXT NULL,
last_ok_at TEXT NULL,
last_error TEXT NULL,
last_ms INTEGER NULL,
cert_expires TEXT NULL,
down_since TEXT NULL,
ticket_id INTEGER NULL,
cert_ticket_id INTEGER NULL,
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS plugin_ueberwachung_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
monitor_id INTEGER NOT NULL,
kind TEXT NOT NULL,
message TEXT NOT NULL,
created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_plugin_ueberwachung_events ON plugin_ueberwachung_events (monitor_id, id)
@@ -0,0 +1 @@
ALTER TABLE plugin_ueberwachung_monitors ADD COLUMN first_fail_at DATETIME NULL
@@ -0,0 +1 @@
ALTER TABLE plugin_ueberwachung_monitors ADD COLUMN first_fail_at TEXT NULL
@@ -0,0 +1 @@
ALTER TABLE plugin_ueberwachung_monitors ADD COLUMN verify_tls TINYINT(1) NOT NULL DEFAULT 1
@@ -0,0 +1 @@
ALTER TABLE plugin_ueberwachung_monitors ADD COLUMN verify_tls INTEGER NOT NULL DEFAULT 1
@@ -0,0 +1 @@
ALTER TABLE plugin_ueberwachung_monitors ADD COLUMN last_status INT NULL, ADD COLUMN last_title VARCHAR(150) NULL
@@ -0,0 +1,2 @@
ALTER TABLE plugin_ueberwachung_monitors ADD COLUMN last_status INTEGER NULL;
ALTER TABLE plugin_ueberwachung_monitors ADD COLUMN last_title TEXT NULL
@@ -0,0 +1,182 @@
<?php
// Seite des Überwachungs-Plugins. Verfügbar: $staff, $pdo. Nur für Administratoren.
if (($staff['role'] ?? '') !== 'admin') { echo '<h1>Überwachung</h1><div class="flash error">Diese Seite ist nur für Administratoren zugänglich.</div>'; return; }
$message = null;
$error = null;
$edit = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
verify_csrf();
$action = $_POST['action'] ?? '';
if ($action === 'save') {
$id = (int) ($_POST['id'] ?? 0);
$r = ueberwachung_save($pdo, $_POST + ['is_active' => !empty($_POST['is_active']) ? 1 : 0, 'verify_tls' => !empty($_POST['verify_tls']) ? 1 : 0], $id);
if ($r['ok']) { $message = $id ? 'Gespeichert.' : 'Das Ziel wird jetzt überwacht.'; if (!$id) ueberwachung_check($pdo, $r['id']); }
else { $error = $r['error']; $edit = $_POST; }
} elseif ($action === 'self') {
$r = ueberwachung_save($pdo, ['name' => 'Diese DeskHub-Seite', 'type' => 'http', 'target' => rtrim(base_url(), '/') . '/', 'interval_min' => 5]);
if ($r['ok']) { ueberwachung_check($pdo, $r['id']); $message = 'Diese Seite wird jetzt überwacht.'; } else $error = $r['error'];
} elseif ($action === 'test_ticket') {
$tid = ueberwachung_open_ticket($pdo, 'Test: Überwachung', 'Dies ist ein Testticket der Überwachung. Es kann gelöscht oder geschlossen werden.');
if ($tid) { $tn = $pdo->query('SELECT ticket_number FROM tickets WHERE id = ' . (int) $tid)->fetchColumn(); $message = 'Testticket #' . $tn . ' wurde angelegt.'; }
else $error = 'Das Testticket konnte nicht angelegt werden: ' . (plugin_setting(UEBERWACHUNG, 'ticket_error', '') ?: 'Tickets sind ausgeschaltet.');
} elseif ($action === 'check') {
$message = ueberwachung_check($pdo, (int) ($_POST['id'] ?? 0)) ? 'Geprüft.' : null;
if ($message === null) $error = 'Ziel nicht gefunden.';
} elseif ($action === 'toggle') {
$pdo->prepare('UPDATE plugin_ueberwachung_monitors SET is_active = 1 - is_active WHERE id = ?')->execute([(int) ($_POST['id'] ?? 0)]);
$message = 'Gespeichert.';
} elseif ($action === 'delete') {
ueberwachung_delete($pdo, (int) ($_POST['id'] ?? 0));
$message = 'Das Ziel wurde gelöscht (bereits angelegte Tickets bleiben).';
} elseif ($action === 'settings') {
plugin_set_setting(UEBERWACHUNG, 'threshold', (string) max(1, min(10, (int) ($_POST['threshold'] ?? 2))));
plugin_set_setting(UEBERWACHUNG, 'department_id', (string) (int) ($_POST['department_id'] ?? 0));
plugin_set_setting(UEBERWACHUNG, 'priority_id', (string) (int) ($_POST['priority_id'] ?? 0));
foreach (['create_tickets', 'auto_resolve', 'mail'] as $k) plugin_set_setting(UEBERWACHUNG, $k, !empty($_POST[$k]) ? '1' : '0');
$mailTo = trim((string) ($_POST['alert_email'] ?? ''));
$ok = true;
foreach (preg_split('/[,;\s]+/', $mailTo, -1, PREG_SPLIT_NO_EMPTY) ?: [] as $a) if (!filter_var($a, FILTER_VALIDATE_EMAIL)) { $ok = false; $error = 'Ungültige Adresse: ' . $a; }
if ($ok) { plugin_set_setting(UEBERWACHUNG, 'alert_email', $mailTo); $message = 'Einstellungen gespeichert.'; }
}
}
if (isset($_GET['edit'])) {
$s = $pdo->prepare('SELECT * FROM plugin_ueberwachung_monitors WHERE id = ?');
$s->execute([(int) $_GET['edit']]);
$edit = $s->fetch() ?: null;
}
$cfg = ueberwachung_config();
$monitors = $pdo->query('SELECT * FROM plugin_ueberwachung_monitors ORDER BY name')->fetchAll();
$events = $pdo->query('SELECT e.*, m.name FROM plugin_ueberwachung_events e LEFT JOIN plugin_ueberwachung_monitors m ON m.id = e.monitor_id ORDER BY e.id DESC LIMIT 40')->fetchAll();
$depts = $pdo->query('SELECT id, name FROM departments ORDER BY name')->fetchAll();
$prios = $pdo->query('SELECT id, name FROM priorities ORDER BY sort_order')->fetchAll();
$types = ueberwachung_types();
$down = count(array_filter($monitors, fn($m) => $m['state'] === 'down'));
$badge = ['up' => ['In Ordnung', '#157a45', '#e6f7ee'], 'down' => ['Ausfall', '#b42318', '#fde8e8'], 'unknown' => ['Noch nicht geprüft', '#5b6b77', '#eef1f4']];
$f = fn(string $k, $d = '') => $edit[$k] ?? $d;
?>
<h1>Website- und Server-Überwachung</h1>
<?php if ($message): ?><div class="flash success"><?= e($message) ?></div><?php endif; ?>
<?php if ($error): ?><div class="flash error"><?= e($error) ?></div><?php endif; ?>
<?php if (ueberwachung_ca_warning($monitors, ueberwachung_ca_bundle_missing())): ?>
<div class="flash error" style="max-width:860px"><div><strong>Achtung:</strong> Die Zertifikatsprüfung scheitert bei allen HTTPS-Zielen, und auf diesem Server findet PHP keine Liste vertrauenswürdiger Zertifizierungsstellen (CA-Bundle). Vermutlich meldet die Prüfung deshalb bei <em>jeder</em> HTTPS-Adresse „Zertifikat ungültig“, auch wenn die Seite in Ordnung ist. Stellen Sie in der PHP-Konfiguration <code>curl.cainfo</code> und <code>openssl.cafile</code> auf eine CA-Datei (zum Beispiel <code>/etc/ssl/certs/ca-certificates.crt</code>) oder schalten Sie bei den Zielen „Zertifikat prüfen“ aus.</div></div>
<?php endif; ?>
<?php $ticketError = (string) plugin_setting(UEBERWACHUNG, 'ticket_error', ''); ?>
<?php if ($ticketError !== ''): ?>
<div class="flash error" style="max-width:860px"><div>
<strong>Hinweis zum Anlegen von Tickets:</strong> <?= e($ticketError) ?>
<form method="post" style="margin-top:6px"><?= csrf_field() ?><input type="hidden" name="action" value="test_ticket"><button class="btn secondary" type="submit">Testticket anlegen</button></form>
</div></div>
<?php endif; ?>
<div class="card" style="margin-bottom:16px">
<h3>Zustand <?= $monitors ? '' : '' ?></h3>
<?php if (!$monitors): ?>
<p class="muted">Noch nichts eingetragen. Unten ein Ziel hinzufügen oder gleich diese Seite überwachen:</p>
<form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="self"><button class="btn secondary" type="submit">Diese DeskHub-Seite überwachen</button></form>
<?php else: ?>
<p style="font-size:.95rem"><?= $down ? '<strong style="color:#b42318">' . $down . ' Ausfall' . ($down > 1 ? 'e' : '') . '</strong> · ' : '<strong style="color:#157a45">Alles in Ordnung</strong> · ' ?><?= count($monitors) ?> Ziele, geprüft vom Hintergrunddienst von DeskHub (im jeweils eingestellten Abstand).</p>
<table style="width:100%">
<thead><tr><th>Name</th><th>Ziel</th><th>Zustand</th><th>Zertifikat</th><th>Zuletzt geprüft</th><th></th></tr></thead>
<tbody>
<?php foreach ($monitors as $m): $b = $badge[$m['state']] ?? $badge['unknown']; $days = $m['cert_expires'] ? (int) floor((strtotime((string) $m['cert_expires']) - time()) / 86400) : null; ?>
<tr style="<?= $m['is_active'] ? '' : 'opacity:.55' ?>">
<td><strong><?= e($m['name']) ?></strong><div class="muted" style="font-size:.74rem"><?= e($types[$m['type']] ?? $m['type']) ?><?= $m['is_active'] ? '' : ' · pausiert' ?></div></td>
<td style="font-size:.84rem;word-break:break-all"><?= e($m['target']) ?><?php if (!empty($m['last_status']) || !empty($m['last_title'])): ?><div class="muted" style="font-size:.74rem">Antwort: <?= $m['last_status'] ? 'HTTP ' . (int) $m['last_status'] : '' ?><?= !empty($m['last_title']) ? ' · Titel „' . e(mb_strimwidth((string) $m['last_title'], 0, 60, '…')) . '“' : '' ?></div><?php endif; ?></td>
<td><span style="background:<?= $b[2] ?>;color:<?= $b[1] ?>;border-radius:20px;padding:3px 11px;font-size:.78rem;font-weight:700"><?= e($b[0]) ?></span>
<?php if ($m['state'] === 'down' && $m['last_error']): ?><div style="font-size:.74rem;color:#b42318"><?= e((string) $m['last_error']) ?></div>
<?php elseif ((int) $m['fails'] > 0): ?><div style="font-size:.74rem;color:#9a6200">Fehlschlag <?= (int) $m['fails'] ?> von <?= (int) $cfg['threshold'] ?> (Ausfall und Ticket ab Fehlschlag <?= (int) $cfg['threshold'] ?>): <?= e((string) $m['last_error']) ?></div><?php endif; ?>
<?php if ($m['is_active'] && $m['last_check_at']): $next = (int) strtotime((string) $m['last_check_at']) + ueberwachung_next_wait($m); ?><div class="muted" style="font-size:.72rem">nächste Prüfung ca. <?= e(date('H:i', max($next, time()))) ?></div><?php endif; ?></td>
<td style="font-size:.84rem"><?= $days === null ? '–' : ($days < 0 ? '<strong style="color:#b42318">abgelaufen</strong>' : ($days <= (int) $m['cert_warn_days'] ? '<strong style="color:#9a6200">' . $days . ' Tage</strong>' : $days . ' Tage')) ?></td>
<td class="muted" style="font-size:.8rem"><?= $m['last_check_at'] ? e(format_dt((string) $m['last_check_at'])) . ($m['last_ms'] !== null ? ' · ' . (int) $m['last_ms'] . ' ms' : '') : '–' ?></td>
<td style="white-space:nowrap">
<form method="post" style="display:inline"><?= csrf_field() ?><input type="hidden" name="id" value="<?= (int) $m['id'] ?>"><button class="btn secondary" name="action" value="check" type="submit" style="padding:2px 9px;font-size:.78rem">Jetzt prüfen</button>
<button class="btn secondary" name="action" value="toggle" type="submit" style="padding:2px 9px;font-size:.78rem"><?= $m['is_active'] ? 'Pausieren' : 'Fortsetzen' ?></button>
<a class="btn secondary" href="/staff/plugin.php?p=ueberwachung&amp;page=ueberwachung&amp;edit=<?= (int) $m['id'] ?>" style="padding:2px 9px;font-size:.78rem">Ändern</a>
<button class="btn danger" name="action" value="delete" type="submit" style="padding:2px 9px;font-size:.78rem" onclick="return confirm('Ziel löschen?')">Löschen</button></form>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
</div>
<?php
$lastTick = (int) plugin_setting(UEBERWACHUNG, 'last_tick', '0');
$stale = $monitors && (!$lastTick || time() - $lastTick > 900);
?>
<div class="card" style="max-width:860px;margin-bottom:16px;<?= $stale ? 'border-left:4px solid #b45309' : '' ?>">
<h3>Hintergrunddienst</h3>
<p style="font-size:.9rem">
<?php if (!$lastTick): ?><strong style="color:#b45309">Noch kein Lauf.</strong> Die Prüfungen starten, sobald DeskHub das nächste Mal aufgerufen wird.
<?php elseif ($stale): ?><strong style="color:#b45309">Letzter Lauf vor <?= e(ueberwachung_duration(time() - $lastTick)) ?>.</strong> Es hat länger niemand DeskHub aufgerufen, oder der automatische Hintergrund-Betrieb ist ausgeschaltet (Einstellungen → Cron-Jobs).
<?php else: ?><strong style="color:#157a45">✓ Läuft.</strong> Letzter Lauf: <?= e(format_dt(date('Y-m-d H:i:s', $lastTick))) ?>.<?php endif; ?>
</p>
<?php
$cliLast = (string) get_setting('cron_run_plugins_last_cli', '');
$cliAge = $cliLast !== '' ? time() - (int) strtotime($cliLast) : null;
?>
<p style="font-size:.88rem">
Echter Server-Cronjob:
<?php if ($cliAge === null): ?><strong style="color:#b45309">bisher kein Lauf</strong> <span class="muted">(Einstellungen → Cron-Jobs → „Neu installieren / aktualisieren“, mit den aktuellen DeskHub-Dateien; bei älteren Dateien siehe unten)</span>
<?php elseif ($cliAge > 900): ?><strong style="color:#b45309">letzter Lauf vor <?= e(ueberwachung_duration($cliAge)) ?></strong> <span class="muted">(<?= e(format_dt($cliLast)) ?>). Er sollte jede Minute laufen: Crontab und <code>cron/run_plugins.log</code> prüfen.</span>
<?php else: ?><strong style="color:#157a45">✓ läuft</strong> <span class="muted">(letzter Lauf <?= e(format_dt($cliLast)) ?>)</span><?php endif; ?>
</p>
<p class="muted" style="font-size:.84rem">Die Prüfungen laufen mit den Hintergrundaufgaben von DeskHub. <strong>Mit dem aktuellen DeskHub-Update</strong> gehören sie zum echten Server-Cronjob: Einstellungen → Cron-Jobs → „Neu installieren / aktualisieren“ trägt die Zeile ein (jede Minute), dann wird auch nachts ohne Besucher in dem Abstand geprüft, den Sie je Ziel einstellen (mindestens 1 Minute). Bei älteren Dateien oder ohne Server-Cronjob läuft die Prüfung nur, solange jemand die Seite oder das Backend aufruft. Dann hilft ein eigener Cronjob für dieses Plugin (zum Beispiel Plesk → Geplante Aufgaben, alle 5 Minuten):</p>
<pre style="background:var(--bg-soft,#f3f6f8);border:1px solid var(--border,#e3e9ee);border-radius:6px;padding:8px 10px;font-size:.78rem;overflow:auto;margin:0">php <?= e(str_replace('\\', '/', plugins_dir()) . '/' . UEBERWACHUNG . '/cron.php') ?></pre>
<p class="muted" style="font-size:.8rem;margin-top:8px"><strong>Wichtig:</strong> Fällt der Server aus, auf dem DeskHub selbst läuft, kann DeskHub das nicht melden. Die eigene Erreichbarkeit überwacht am besten ein Dienst auf einem anderen Server.</p>
</div>
<form method="post" class="card" style="max-width:860px;margin-bottom:16px">
<?= csrf_field() ?>
<input type="hidden" name="action" value="save">
<input type="hidden" name="id" value="<?= (int) $f('id', 0) ?>">
<h3><?= $edit && !empty($edit['id']) ? 'Ziel ändern' : 'Neues Ziel' ?></h3>
<div style="display:flex;gap:12px;flex-wrap:wrap">
<div style="flex:1;min-width:200px"><label>Name</label><input type="text" name="name" value="<?= e((string) $f('name')) ?>" placeholder="Support-Seite" required></div>
<div><label>Art</label><select name="type"><?php foreach ($types as $k => $l): ?><option value="<?= e($k) ?>" <?= $f('type', 'http') === $k ? 'selected' : '' ?>><?= e($l) ?></option><?php endforeach; ?></select></div>
</div>
<label style="margin-top:8px">Adresse bzw. Host:Port</label>
<input type="text" name="target" value="<?= e((string) $f('target')) ?>" placeholder="https://support.example.de/ oder mail.example.de:993" required>
<label style="margin-top:8px">Erwarteter Text auf der Seite (optional, nur bei Webseiten)</label>
<p class="muted" style="font-size:.78rem;margin:0 0 4px">Tipp: Mit einem Text, der nur auf der echten Seite steht (zum Beispiel der Name Ihrer Anwendung), erkennt die Überwachung auch Fälle, in denen ein Proxy oder Webserver eine andere Seite mit „200 OK“ ausliefert. Ohne Text werden bekannte Standard- und Fehlerseiten am Titel erkannt.</p>
<input type="text" name="expect_text" value="<?= e((string) $f('expect_text')) ?>" maxlength="200">
<div style="display:flex;gap:12px;flex-wrap:wrap;margin-top:8px">
<div><label>Prüfen alle (Minuten)</label><input type="number" name="interval_min" min="1" max="1440" value="<?= (int) $f('interval_min', 5) ?>" style="max-width:110px"></div>
<div><label>Zeitlimit (Sekunden)</label><input type="number" name="timeout_sec" min="2" max="30" value="<?= (int) $f('timeout_sec', 8) ?>" style="max-width:110px"></div>
<div><label>Zertifikat-Warnung (Tage vorher)</label><input type="number" name="cert_warn_days" min="1" max="90" value="<?= (int) $f('cert_warn_days', 14) ?>" style="max-width:110px"></div>
</div>
<p class="muted" style="font-size:.78rem;margin:6px 0 0">Der eingestellte Abstand gilt, sobald der Hintergrunddienst von DeskHub jede Minute läuft (aktuelle Dateien: ein Cronjob mit „Neu installieren / aktualisieren“, oder bei Seitenaufrufen). Bei älteren Dateien läuft er nur alle 5 Minuten, kürzere Werte greifen dort erst mit dem eigenen Cronjob des Plugins (Karte „Hintergrunddienst“, Zeitplan <code>* * * * *</code>).</p>
<label style="display:block;margin-top:8px;font-weight:400"><input type="checkbox" name="verify_tls" value="1" style="width:auto" <?= !$edit || !array_key_exists('verify_tls', $edit) || !empty($edit['verify_tls']) ? 'checked' : '' ?>> Zertifikat prüfen (bei selbstsignierten oder internen Zertifikaten abschalten)</label>
<label style="display:block;margin-top:8px;font-weight:400"><input type="checkbox" name="is_active" value="1" style="width:auto" <?= !$edit || !empty($edit['is_active']) ? 'checked' : '' ?>> Aktiv</label>
<div class="btn-row"><button type="submit" class="btn">Speichern</button><?php if ($edit && !empty($edit['id'])): ?> <a class="btn secondary" href="/staff/plugin.php?p=ueberwachung&amp;page=ueberwachung">Abbrechen</a><?php endif; ?></div>
</form>
<form method="post" class="card" style="max-width:860px;margin-bottom:16px">
<?= csrf_field() ?>
<input type="hidden" name="action" value="settings">
<h3>Einstellungen</h3>
<label style="display:block;font-weight:400"><input type="checkbox" name="create_tickets" value="1" style="width:auto" <?= $cfg['create_tickets'] ? 'checked' : '' ?>> Bei Ausfall und ablaufendem Zertifikat ein Ticket anlegen</label>
<label style="display:block;font-weight:400"><input type="checkbox" name="auto_resolve" value="1" style="width:auto" <?= $cfg['auto_resolve'] ? 'checked' : '' ?>> Ticket nach der Behebung automatisch auf „Gelöst“ setzen (Entwarnung)</label>
<label style="display:block;font-weight:400"><input type="checkbox" name="mail" value="1" style="width:auto" <?= $cfg['mail'] ? 'checked' : '' ?>> E-Mail bei Ausfall, Entwarnung und Zertifikat</label>
<div style="display:flex;gap:12px;flex-wrap:wrap;margin-top:8px">
<div><label>Ausfall melden nach … Fehlschlägen in Folge</label><input type="number" name="threshold" min="1" max="10" value="<?= (int) $cfg['threshold'] ?>" style="max-width:110px"></div>
<div><label>Abteilung der Tickets</label><select name="department_id"><option value="0">Standard</option><?php foreach ($depts as $d): ?><option value="<?= (int) $d['id'] ?>" <?= (int) $d['id'] === $cfg['department_id'] ? 'selected' : '' ?>><?= e($d['name']) ?></option><?php endforeach; ?></select></div>
<div><label>Priorität der Tickets</label><select name="priority_id"><option value="0">Standard</option><?php foreach ($prios as $p): ?><option value="<?= (int) $p['id'] ?>" <?= (int) $p['id'] === $cfg['priority_id'] ? 'selected' : '' ?>><?= e($p['name']) ?></option><?php endforeach; ?></select></div>
</div>
<label style="margin-top:8px">Mail an (leer = Administrator-Adresse der Installation, mehrere mit Komma)</label>
<input type="text" name="alert_email" value="<?= e((string) plugin_setting(UEBERWACHUNG, 'alert_email', '')) ?>" placeholder="<?= e((string) $cfg['alert_email']) ?>">
<div class="btn-row"><button type="submit" class="btn">Speichern</button> <button type="submit" class="btn secondary" name="action" value="test_ticket" formnovalidate>Testticket anlegen</button></div>
</form>
<div class="card">
<h3>Ereignisse</h3>
<?php if (!$events): ?><p class="muted">Noch keine Ereignisse.</p><?php else: ?>
<table style="width:100%"><thead><tr><th>Wann</th><th>Ziel</th><th>Ereignis</th></tr></thead><tbody>
<?php foreach ($events as $ev): ?>
<tr><td class="muted" style="white-space:nowrap"><?= e(format_dt((string) $ev['created_at'])) ?></td><td><?= e((string) $ev['name']) ?></td><td><?= e(['down' => 'Ausfall', 'up' => 'Entwarnung', 'cert' => 'Zertifikat', 'cert_ok' => 'Zertifikat erneuert'][$ev['kind']] ?? $ev['kind']) ?>: <?= e((string) $ev['message']) ?></td></tr>
<?php endforeach; ?>
</tbody></table>
<?php endif; ?>
</div>
+9
View File
@@ -0,0 +1,9 @@
{
"slug": "ueberwachung",
"name": "Website- und Server-Überwachung",
"version": "1.1.1",
"description": "Prüft regelmäßig Webseiten, Ports und Zertifikate. Fällt etwas aus oder läuft ein Zertifikat bald ab, legt das Plugin automatisch ein Ticket an, benachrichtigt den Administrator und gibt nach der Behebung Entwarnung (Ticket wird auf „Gelöst“ gesetzt). Nur für Administratoren.",
"author": "DeskHub",
"requires": "1.0.0",
"permissions": ["hooks.cron", "ui.menu", "db.migrations"]
}
+15
View File
@@ -0,0 +1,15 @@
<?php
// Website- und Server-Überwachung: regelmäßige Prüfung im Hintergrund.
require_once __DIR__ . '/lib.php';
ueberwachung_ensure_schema();
// „cron.minute“ (aktuelles DeskHub: jede Minute) hält den eingestellten Prüfabstand ein; „cron.run“ (alle 5 Minuten) ist der Rückfall für ältere Dateien.
// Doppelte Aufrufe schaden nicht: Es werden nur Ziele geprüft, die fällig sind.
foreach (['cron.minute', 'cron.run'] as $__hook) {
plugin_add_hook($__hook, function () {
ueberwachung_tick(get_db());
});
}
// Im Adminportal, nur für Administratoren (die Seite prüft das zusätzlich selbst)
plugin_register_menu('Überwachung', 'ueberwachung', null, 'admin');