0) { $expiresAt = utc_after(min($expiresDays, 365) * 86400); } $stmt = db()->prepare( 'INSERT INTO invites (code_hash, note, email, created_by, created_at, expires_at) VALUES (?, ?, ?, ?, ?, ?)' ); $stmt->execute([ invite_hash($code), $note !== '' ? mb_substr($note, 0, 190, 'UTF-8') : null, $email !== '' ? mb_substr($email, 0, 190, 'UTF-8') : null, $createdBy, utc_now(), $expiresAt, ]); audit('invite.create', 'invite', (int) db()->lastInsertId(), $note, $createdBy); return $code; } function invite_find_valid(string $code): ?array { $normalized = invite_normalize($code); if ($normalized === '') { return null; } $stmt = db()->prepare( 'SELECT * FROM invites WHERE code_hash = ? AND used_by IS NULL AND used_at IS NULL AND revoked_at IS NULL LIMIT 1' ); $stmt->execute([invite_hash($normalized)]); $row = $stmt->fetch(); if (!$row) { return null; } if ($row['expires_at'] !== null && $row['expires_at'] <= utc_now()) { return null; } return $row; } function invite_consume(int $inviteId, int $userId): bool { $stmt = db()->prepare( 'UPDATE invites SET used_by = ?, used_at = ? WHERE id = ? AND used_by IS NULL AND used_at IS NULL AND revoked_at IS NULL AND (expires_at IS NULL OR expires_at > ?)' ); $stmt->execute([$userId, utc_now(), $inviteId, utc_now()]); return $stmt->rowCount() === 1; } function invite_revoke(int $inviteId): bool { $stmt = db()->prepare( 'UPDATE invites SET revoked_at = ? WHERE id = ? AND used_by IS NULL AND revoked_at IS NULL' ); $stmt->execute([utc_now(), $inviteId]); return $stmt->rowCount() === 1; } function invites_list(): array { return db()->query( "SELECT i.*, c.username AS creator_name, u.username AS used_name FROM invites i LEFT JOIN users c ON c.id = i.created_by LEFT JOIN users u ON u.id = i.used_by ORDER BY i.created_at DESC, i.id DESC LIMIT 200" )->fetchAll(); } function invite_status(array $invite): string { if ($invite['revoked_at'] !== null) { return 'widerrufen'; } if ($invite['used_at'] !== null) { return 'eingelöst'; } if ($invite['expires_at'] !== null && $invite['expires_at'] <= utc_now()) { return 'abgelaufen'; } return 'offen'; }