63 Commits

Author SHA1 Message Date
luptmoor
0f15e92d65 comment counter now refreshed for each deletion or addition of comment 2026-04-28 10:21:27 +02:00
luptmoor
942affd5e5 fix typo contribution_id 2026-04-28 10:08:49 +02:00
luptmoor
02ba53724e prepared comment counting 2026-04-28 10:04:51 +02:00
luptmoor
d0bba3d3f8 EXTENSION.md updated and completed 2026-04-28 09:20:54 +02:00
f23897018c colapsable fotos and comments section in contribution popup, comment count in popup and sidebar 2026-04-27 14:48:05 +02:00
c39667e368 photos and comments functionality for contributions, moderation page functionality pending 2026-04-25 14:30:58 +02:00
cb8994b493 unified CSS, consistent headers, standardized button colors 2026-04-25 13:37:05 +02:00
62ba9b5345 fixed html structure for news sidebar 2026-04-25 13:10:47 +02:00
360eb3744a implemented anonymous user authentification with browser identification number from cookies 2026-04-25 12:48:24 +02:00
601c13012c updated env.example 2026-04-25 12:11:31 +02:00
6200b061f2 added migration for anonymous user identification by browser ID 2026-04-24 17:47:00 +02:00
fa984e7391 author can be edited and added in news moderation page 2026-04-24 17:41:59 +02:00
125c255115 changed favicon to relative paths from database 2026-04-24 17:29:36 +02:00
04e692a6dd minor changed to text fields 2026-04-24 17:28:12 +02:00
25cf797294 added news CRUD functionality in moderation portal 2026-04-24 17:18:56 +02:00
62ae9f18b0 added date and author to news in sidebar 2026-04-24 17:08:32 +02:00
5cadc5c1b4 reverse geocoding for contributions 2026-04-24 17:00:55 +02:00
9ca215c36d added migration for reverse geocoding 2026-04-24 16:55:49 +02:00
04f96b7aba commented migration for news table 2026-04-24 16:50:27 +02:00
ffe81cdf88 migration for news table in database, news now read from database 2026-04-24 16:33:03 +02:00
c9040b2f4e reads municipality logo from database 2026-04-24 16:13:45 +02:00
9c8e641557 added privacy and imprint pages to meet german DSGVO criteria 2026-04-24 16:09:53 +02:00
076e82213d added privacy and imprint pages to meet german DSGVO criteria 2026-04-24 16:06:26 +02:00
6a721fde7c fixed point layer opacity bug, changed point layer styling 2026-04-24 15:45:27 +02:00
8179498333 bootstrap button colours 2026-04-24 15:38:18 +02:00
ec4c9fa8a9 changed edit button colour to primary 2026-04-23 15:30:41 +02:00
8d67c0c0b9 title and description above text fields for contribution edit 2026-04-23 15:27:33 +02:00
ade9ca2128 styling and fond sweetalert font override 2026-04-23 15:13:49 +02:00
2993a443a7 removed dublicate pdo call 2026-04-23 14:59:03 +02:00
luptmoor
025cd975f0 removed TODOs after successful test 2026-04-23 10:10:53 +02:00
luptmoor
0b02b435ef added municipality slug as env var 2026-04-23 10:01:18 +02:00
luptmoor
c52dbf618e added comments for slug as env var 2026-04-23 09:29:14 +02:00
luptmoor
2b1f7e3a38 SSL mode changed to disable 2026-04-23 09:29:14 +02:00
4926433c35 opens moderation portal in new tab 2026-04-22 16:02:38 +02:00
aae29618b3 added development warning in footer 2026-04-22 16:02:07 +02:00
a828a3878e fixed point opacity bug when deactivating categories in sidebar 2026-04-22 15:56:30 +02:00
f107d97b87 categories now only once defined in db.php, not longer multiple hardcoded definitions 2026-04-22 15:49:12 +02:00
7e6b55abd4 categories now only once defined in db.php, not longer multiple hardcoded definitions 2026-04-22 15:48:58 +02:00
d98d6a6713 commented db.php 2026-04-22 15:43:01 +02:00
3e73dee40b commented moderation portal and changed textblocks 2026-04-22 15:16:40 +02:00
adf863934e rebuild moderation page with filter and sorting functions, CRUD operations, map preview function and shared categories 2026-04-22 14:39:38 +02:00
27d41c0847 simplified admin and mod authentification for new moderation page 2026-04-22 14:34:03 +02:00
9d7eb25d1f get categories function for category definition in moderation page 2026-04-22 14:32:13 +02:00
f30a01615e bugfix like dislikes disappeared when reopening closed contribution popup 2026-04-22 14:16:13 +02:00
2c02a61791 refractored all var to const or let 2026-04-21 17:02:35 +02:00
a38cf999f2 adapted basemap attributions 2026-04-21 16:49:44 +02:00
78bdc22781 added layer control icons 2026-04-21 16:44:46 +02:00
f810ed520c removed circles in sidebar legend, added contribution icon in layer control 2026-04-21 16:35:35 +02:00
2b3fcb6ebf replaced category emojis with fontawesome icons 2026-04-21 16:13:56 +02:00
5fe7522f5f deactivated mouse position control and polyline measure plugin 2026-04-21 15:52:41 +02:00
f8f0d514bb added map previews in moderation portal 2026-04-21 12:33:15 +02:00
5e8b4745f1 moved header navigation items right 2026-04-21 12:33:15 +02:00
c3569d6b98 Merge pull request 'dev/patrick' (#1) from dev/patrick into main
Reviewed-on: #1
2026-04-20 16:32:31 +02:00
7dea362c89 added moderation portal with admin authentification and seperate styling 2026-04-20 16:01:10 +02:00
11a062dd84 added ende attribution in footer 2026-04-20 15:31:49 +02:00
aec6a9bfb6 commented new vote function 2026-04-20 15:21:58 +02:00
94d4308d3f added visual vote deefback without sweet alert 2026-04-20 15:19:56 +02:00
a37c1ffe01 likes and dislikes changable if citizen changes oppinion 2026-04-20 15:06:07 +02:00
8151390835 warning message portal still in development in welcome modal 2026-04-20 14:55:24 +02:00
99cf34671a changed language of geoman plugin to german 2026-04-20 14:48:16 +02:00
f9187a3e84 pinned version of sweetalert 2026-04-20 14:45:31 +02:00
94100b9371 removed sweetalert duplicate 2026-04-20 14:43:38 +02:00
84ce0de870 sweetalert font override 2026-04-20 14:40:28 +02:00
19 changed files with 3112 additions and 716 deletions

View File

@@ -4,3 +4,5 @@ POSTGRES_PORT=postgres_port
POSTGRES_DB=postgres_database POSTGRES_DB=postgres_database
POSTGRES_USER=postgres_user POSTGRES_USER=postgres_user
POSTGRES_PASSWORD= POSTGRES_PASSWORD=
ADMIN_PASSWORD=
MUNICIPALITY_SLUG=lohne

3
.gitignore vendored
View File

@@ -2,3 +2,6 @@
.vscode/ .vscode/
*.log *.log
scripts scripts
public/uploads/photos/*
!public/uploads/photos/.gitkeep

View File

@@ -1,8 +1,47 @@
## Neue Ideenkarte anlegen # Neue Ideenkarte anlegen
1. DNS record ```<name>``` A 195.59.32.237 600s
2. Nginx Weiterleitung in ```default.conf```:
## Übersicht
| Variable | Bedeutung |
|---|---|
| `<name>` | Name der Kommune (z.B. `lohne`) |
| `<ID>` | Eindeutige Port-ID für die Datenbank (z.B. `4` → Port `5434`) |
| `<branch-name>` | Git-Branch des Frontend-Repos |
---
## Schritt 1 — DNS Record anlegen
Im DNS-Panel einen neuen A-Record anlegen:
| Feld | Wert |
|---|---|
| Name | `<name>` |
| Typ | `A` |
| Ziel | `195.59.32.237` |
| TTL | `600s` |
> ⚠️ DNS muss vollständig propagiert sein, bevor Certbot in Schritt 3 ausgeführt wird.
Propagation prüfen:
```bash
dig <name>.endex-geodaten.de
``` ```
---
## Schritt 2 — Nginx `default.conf` anpassen
### 2a — Subdomain in den Port-80-Block eintragen
```nginx
server_name endex-geodaten.de www.endex-geodaten.de git.endex-geodaten.de lohne.endex-geodaten.de <name>.endex-geodaten.de localhost;
```
### 2b — Neuen HTTPS-Server-Block hinzufügen
```nginx
# WEBGIS <NAME>
server { server {
listen 443 ssl; listen 443 ssl;
server_name <name>.endex-geodaten.de; server_name <name>.endex-geodaten.de;
@@ -26,8 +65,34 @@ server {
} }
``` ```
3. Docker container für UI ---
## Schritt 3 — SSL-Zertifikat erneuern
Da kein Wildcard-Zertifikat verwendet wird, muss das Cert neu ausgestellt werden:
```bash
docker compose run --rm certbot certonly --webroot \
--webroot-path=/var/www/certbot \
-d endex-geodaten.de \
-d www.endex-geodaten.de \
-d git.endex-geodaten.de \
-d lohne.endex-geodaten.de \
-d <name>.endex-geodaten.de
``` ```
Nginx neu laden:
```bash
docker compose exec nginx nginx -s reload
```
---
## Schritt 4 — Docker Container in `docker-compose.yml` anlegen
### PHP/UI Container
```yaml
webgis-<name>-php: webgis-<name>-php:
build: php-docker/ build: php-docker/
container_name: webgis-<name>-php container_name: webgis-<name>-php
@@ -38,41 +103,81 @@ server {
- webgis-<name>-nw - webgis-<name>-nw
``` ```
und Datenbank anlegen. ### Datenbank Container
``` ```yaml
webgis-<name>db: webgis-<name>-db:
image: postgis/postgis:15-3.3 image: postgis/postgis:15-3.3
container_name: webgis-<name>-db container_name: webgis-<name>-db
restart: always restart: always
ports: ports:
- "127.0.0.1:543<ID>:5432" # inside the container always 5432 - "127.0.0.1:543<ID>:5432" # inside the container always 5432
environment: environment:
- POSTGRES_USER=${WEBGIS_DB_USER} # maybe go back to default username - POSTGRES_USER=${WEBGIS_<NAME>_DB_USER}
- POSTGRES_PASSWORD=${WEBGIS_DB_PW} # must be secure and unique - POSTGRES_PASSWORD=${WEBGIS_<NAME>_DB_PW}
- POSTGRES_DB=${WEBGIS_DB_NAME} #same as container name - POSTGRES_DB=${WEBGIS_<NAME>_DB_NAME}
volumes: volumes:
- ./webgis-<name>-data:/var/lib/postgresql/data - ./webgis-<name>-data:/var/lib/postgresql/data
networks: networks:
- webgis-<name>-nw - webgis-<name>-nw
``` ```
4. nginx Volume für neue Stadt in ```docker-compose.yml``` anlegen ### Netzwerk ergänzen
```
./webgis-<name>:/var/www/webgis-<name> Unter dem `networks:` Block am Ende der `docker-compose.yml`:
```yaml
networks:
webgis-<name>-nw:
driver: bridge
``` ```
---
5. Frontend source code nach ```webgis-<name>``` klonen ## Schritt 5 — Nginx Volume ergänzen
Beim nginx-Service in `docker-compose.yml` das neue Volume eintragen:
```yaml
volumes:
- ./webgis-<name>:/var/www/webgis-<name>
``` ```
---
## Schritt 6 — Frontend Source Code klonen
```bash
git submodule add -b <branch-name> https://git.endex-geodaten.de/lukas.uptmoor/webgis-<name>.git git submodule add -b <branch-name> https://git.endex-geodaten.de/lukas.uptmoor/webgis-<name>.git
``` ```
Jede Kommune sollte ein eigenes Repo kriegen, da Features am Anfang variieren. > Jede Kommune erhält ein eigenes Repo, da Features initial variieren können.
---
6. Mit der Datenbank verbinden über SSH-Tunnel ## Schritt 7 — Container starten
```bash
docker compose up -d webgis-<name>-php webgis-<name>-db
``` ```
Logs prüfen:
```bash
docker compose logs -f webgis-<name>-php
docker compose logs -f webgis-<name>-db
```
---
## Schritt 8 — Datenbank vorbereiten
SSH-Tunnel öffnen:
```bash
ssh -L 5433:localhost:543<ID> root@endex-geodaten.de ssh -L 5433:localhost:543<ID> root@endex-geodaten.de
``` ```
und Datenbank für Anwendung vorbereiten.
Strukturen laden:
```bash
docker exec -it webgis-<name>-db psql -U $POSTGRES_USER -d $POSTGRES_DB < migrations/001_initial_schema.sql
```

View File

@@ -0,0 +1,44 @@
-- =====================================================================
-- Migration 004: Creates News Table for Municipality Announcements
-- =====================================================================
-- ---------------------------------------------------------------------
-- Block 1: Creates Table "news"
-- ---------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS news (
news_id SERIAL PRIMARY KEY,
municipality_id INTEGER NOT NULL REFERENCES municipalities(municipality_id) ON DELETE CASCADE,
title VARCHAR(255) NOT NULL,
content TEXT NOT NULL,
author_name VARCHAR(100) NOT NULL DEFAULT 'Stadtverwaltung',
published_at TIMESTAMP NOT NULL DEFAULT NOW(),
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP NOT NULL DEFAULT NOW()
);
-- ---------------------------------------------------------------------
-- Block 2: Trigger Functions
-- ---------------------------------------------------------------------
-- Automatically Refresh updated_at on every UPDATE.
CREATE TRIGGER set_news_updated_at
BEFORE UPDATE ON news
FOR EACH ROW
EXECUTE FUNCTION set_updated_at();
-- ---------------------------------------------------------------------
-- Block 3 Indexes for fast Queries
-- ---------------------------------------------------------------------
CREATE INDEX idx_news_municipality ON news(municipality_id);
-- ---------------------------------------------------------------------
-- Block 4: Seed Data — Initial News Article
-- ---------------------------------------------------------------------
INSERT INTO news (municipality_id, title, content)
SELECT municipality_id, 'Mitmachkarte gestartet',
'Die Mitmachkarte als Bürgerbeteiligungsportal der Stadt Lohne (Oldenburg) wird nun freigeschaltet. Wir freuen uns auf Ihre Hinweise und Vorschläge!'
FROM municipalities WHERE slug = 'lohne';

View File

@@ -0,0 +1,8 @@
-- =====================================================================
-- Migration 004: Adds Address Column for Reverse Geocoding
-- =====================================================================
ALTER TABLE contributions
ADD COLUMN address VARCHAR(255) DEFAULT NULL;
COMMENT ON COLUMN contributions.address IS 'Reverse geocoded Address, stored automatically on Creation.';

View File

@@ -0,0 +1,27 @@
-- =====================================================================
-- Migration 005: Adds Browser ID for anonymous User Identification
-- =====================================================================
-- Adds browser_id Column to Contributions
ALTER TABLE contributions
ADD COLUMN browser_id VARCHAR(36) DEFAULT NULL;
-- Adds browser_id Column to Votes
-- Replaces voter_name for Identification
ALTER TABLE votes
ADD COLUMN browser_id VARCHAR(36) DEFAULT NULL;
-- Index for fast Vote Lookup by Browser
CREATE INDEX idx_votes_browser ON votes(browser_id);
-- New UNIQUE Constraint: One Vote per Browser per Contribution
-- Drops old Constraint voter_name based
ALTER TABLE votes
DROP CONSTRAINT IF EXISTS votes_unique_per_voter;
-- Creates new Constraint browser_id based
ALTER TABLE votes
ADD CONSTRAINT votes_contribution_browser_unique
UNIQUE (contribution_id, browser_id);

View File

@@ -0,0 +1,36 @@
-- =====================================================================
-- Migration 006: Comments Table and Photo Support
-- =====================================================================
-- ---------------------------------------------------------------------
-- Block 1: Creates Table "comments"
-- Stores Comments on Contributions. Comments is linked to
-- Contributions and identified by browser_id.
-- ---------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS comments (
comment_id SERIAL PRIMARY KEY,
contribution_id INTEGER NOT NULL REFERENCES contributions(contribution_id) ON DELETE CASCADE,
author_name VARCHAR(100) NOT NULL,
browser_id VARCHAR(36) DEFAULT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT NOW()
);
-- ---------------------------------------------------------------------
-- Block 2: Indexes for fast Comment Queries
-- ---------------------------------------------------------------------
CREATE INDEX idx_comments_contribution ON comments(contribution_id);
CREATE INDEX idx_comments_browser ON comments(browser_id);
-- ---------------------------------------------------------------------
-- Block 3: Adds Photo Path Column to Contributions
-- Stores relative Path to uploaded Photo File.
-- ---------------------------------------------------------------------
ALTER TABLE contributions
ADD COLUMN photo_path VARCHAR(255) DEFAULT NULL;
ADD COLUMN comment_count INTEGER NOT NULL DEFAULT 0;
COMMENT ON COLUMN contributions.photo_path IS 'Relative Path to uploaded Photo. NULL = no Photo.';

891
public/admin.php Normal file
View File

@@ -0,0 +1,891 @@
<?php
// =====================================================================
// Moderation Page
// Lists Contributions for Review. Moderators can approve, reject,
// edit and delete Contributions. Includes Map Preview and Filtering.
//
// ToDo's:
// - Comment Moderation Tab
// - News Management Tab
// - User Management Tab
// - Analytics Tab
// =====================================================================
// Reads Environment Configfile
$envFile = __DIR__ . '/../../.env';
if (file_exists($envFile)) {
$lines = file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
if (strpos(trim($line), '#') === 0) continue;
list($key, $value) = array_map('trim', explode('=', $line, 2));
putenv("$key=$value");
}
}
require_once __DIR__ . '/api/db.php';
require_once __DIR__ . '/api/auth.php';
// -----------------------------------------------------------------
// Routing: Login, Logout, or Main Page
// -----------------------------------------------------------------
$page = $_GET['page'] ?? 'main';
// Handles Login
if ($page === 'login' && $_SERVER['REQUEST_METHOD'] === 'POST') {
$password = $_POST['password'] ?? '';
if (admin_login($password)) {
header('Location: admin.php');
exit;
} else {
$login_error = 'Falsches Passwort.';
}
}
// Handles Logout
if ($page === 'logout') {
admin_logout();
header('Location: admin.php?page=login');
exit;
}
// -----------------------------------------------------------------
// Loads Municipality Configuration for Theming
// -----------------------------------------------------------------
$pdo = get_db();
$stmt = $pdo->prepare("SELECT * FROM municipalities WHERE slug = :slug");
$stmt->execute([':slug' => getenv('MUNICIPALITY_SLUG')]);
$municipality = $stmt->fetch();
// Loads News for Moderation
$stmt = $pdo->prepare("
SELECT news_id, title, content, author_name, published_at, created_at
FROM news
WHERE municipality_id = :mid
ORDER BY published_at DESC
");
$stmt->execute([':mid' => $municipality['municipality_id']]);
$news_items = $stmt->fetchAll();
// Shows Login Page if not authenticated
if ($page === 'login' || !is_admin()) {
show_login_page($municipality, $login_error ?? null);
exit;
}
// -----------------------------------------------------------------
// Loads shared Category Definitions
// -----------------------------------------------------------------
$categories = get_categories();
// -----------------------------------------------------------------
// Loads Contributions and Statistics
// -----------------------------------------------------------------
// Loads all Contributions for Municipality
$stmt = $pdo->prepare("
SELECT contribution_id, title, category, description, author_name,
geom_type, status, likes_count, dislikes_count, created_at, updated_at
FROM contributions
WHERE municipality_id = :mid
ORDER BY created_at DESC
");
$stmt->execute([':mid' => $municipality['municipality_id']]);
$all_contributions = $stmt->fetchAll();
// Counts per Status
$counts = ['pending' => 0, 'approved' => 0, 'rejected' => 0];
foreach ($all_contributions as $item) {
if (isset($counts[$item['status']])) {
$counts[$item['status']]++;
}
}
$counts['total'] = count($all_contributions);
// -----------------------------------------------------------------
// Renders Main Page
// -----------------------------------------------------------------
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Moderation — <?= htmlspecialchars($municipality['name']) ?></title>
<link rel="icon" href="<?= htmlspecialchars($municipality['logo_path'] ?? 'assets/icon-municipality.png') ?>" type="image/png">
<!-- Loads CSS Dependencies -->
<!-- Font Awesome for Icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<!-- Leaflet -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.min.css">
<!-- Application Styles -->
<link rel="stylesheet" href="styles.css">
<!-- Loads JavaScript Dependencies -->
<!-- SweetAlert2 -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.14.0/dist/sweetalert2.all.min.js"></script>
<!-- Loads Municipality Theme from Database -->
<style>:root { --color-primary: <?= htmlspecialchars($municipality['primary_color']) ?>; }</style>
</head>
<body>
<!-- ============================================================= -->
<!-- Header -->
<!-- ============================================================= -->
<div class="page-header">
<div class="page-header-inner">
<h1><i class="fa-solid fa-shield-halved"></i> Moderationsportal <?= htmlspecialchars($municipality['name']) ?></h1>
<div class="page-header-nav">
<a href="index.php"><i class="fa-solid fa-map"></i> Bürgerportal</a>
<a href="admin.php?page=logout"><i class="fa-solid fa-right-from-bracket"></i> Abmelden</a>
</div>
</div>
</div>
<div class="page-container">
<!-- ========================================================= -->
<!-- Page Navigation Tabs -->
<!-- ========================================================= -->
<div class="page-tabs">
<button class="page-tab active" onclick="showPageTab('contributions')">
<i class="fa-solid fa-list-check"></i> Beiträge
</button>
<button class="page-tab" onclick="showPageTab('news')">
<i class="fa-solid fa-newspaper"></i> Neuigkeiten
</button>
<button class="page-tab" onclick="showPageTab('stats')">
<i class="fa-solid fa-chart-bar"></i> Statistik
</button>
<button class="page-tab" onclick="showPageTab('users')">
<i class="fa-solid fa-users"></i> Benutzer
</button>
</div>
<!-- ========================================================= -->
<!-- Contributions Tab -->
<!-- ========================================================= -->
<div id="tab-contributions" class="page-tab-content">
<!-- Statistics Cards -->
<div class="stats-grid">
<div class="stat-card">
<div class="stat-number"><?= $counts['total'] ?></div>
<div class="stat-label">Alle</div>
</div>
<div class="stat-card">
<div class="stat-number"><?= $counts['pending'] ?></div>
<div class="stat-label">Ausstehend</div>
</div>
<div class="stat-card">
<div class="stat-number"><?= $counts['approved'] ?></div>
<div class="stat-label">Akzeptiert</div>
</div>
<div class="stat-card">
<div class="stat-number"><?= $counts['rejected'] ?></div>
<div class="stat-label">Abgelehnt</div>
</div>
</div>
<!-- Status Filter Tabs -->
<div class="filter-tabs">
<button class="filter-tab active" onclick="filterByStatus('all', this)">
Alle <span class="tab-count"><?= $counts['total'] ?></span>
</button>
<button class="filter-tab" onclick="filterByStatus('pending', this)">
Ausstehend <span class="tab-count"><?= $counts['pending'] ?></span>
</button>
<button class="filter-tab" onclick="filterByStatus('approved', this)">
Akzeptiert <span class="tab-count"><?= $counts['approved'] ?></span>
</button>
<button class="filter-tab" onclick="filterByStatus('rejected', this)">
Abgelehnt <span class="tab-count"><?= $counts['rejected'] ?></span>
</button>
</div>
<!-- Sort Controls -->
<div class="sort-controls">
<span id="visible-count"><?= $counts['total'] ?> Beiträge</span>
<select onchange="sortContributions(this.value)">
<option value="date-desc">Neueste zuerst</option>
<option value="date-asc">Älteste zuerst</option>
<option value="category">Nach Kategorie</option>
</select>
</div>
<!-- Contribution List -->
<div id="contributions-container">
<?php if (empty($all_contributions)): ?>
<div class="empty-state">
<i class="fa-solid fa-inbox" style="font-size:2rem;margin-bottom:8px;display:block;"></i>
Noch keine Beiträge vorhanden.
</div>
<?php else: ?>
<?php foreach ($all_contributions as $item):
$cat = $categories[$item['category']] ?? ['label' => $item['category'], 'faIcon' => 'fa-question', 'color' => '#999'];
$status_label = ['pending' => 'Ausstehend', 'approved' => 'Akzeptiert', 'rejected' => 'Abgelehnt'];
?>
<div class="contribution-row"
data-status="<?= $item['status'] ?>"
data-category="<?= htmlspecialchars($item['category']) ?>"
data-date="<?= $item['created_at'] ?>"
data-id="<?= $item['contribution_id'] ?>">
<!-- Collapsed Header: Title + Status -->
<div class="contribution-row-header" onclick="toggleRow(this.parentElement)">
<div class="contribution-row-summary">
<span class="title"><?= htmlspecialchars($item['title']) ?></span>
<span class="badge badge-category">
<i class="fa-solid <?= $cat['faIcon'] ?>"></i>
<?= $cat['label'] ?>
</span>
<span class="badge badge-<?= $item['status'] ?>"><?= $status_label[$item['status']] ?? $item['status'] ?></span>
</div>
<i class="fa-solid fa-chevron-down collapse-icon"></i>
</div>
<!-- Expanded Detail -->
<div class="contribution-row-detail">
<div class="detail-layout">
<!-- Map Preview -->
<div class="detail-map" id="map-<?= $item['contribution_id'] ?>"
data-contribution-id="<?= $item['contribution_id'] ?>">
</div>
<!-- Content -->
<div class="detail-content">
<?php if ($item['description']): ?>
<div class="description"><?= htmlspecialchars($item['description']) ?></div>
<?php else: ?>
<div class="description empty">Keine Beschreibung vorhanden.</div>
<?php endif; ?>
<div class="detail-meta">
<span><i class="fa-solid fa-user"></i> <?= htmlspecialchars($item['author_name']) ?></span>
<span><i class="fa-solid fa-calendar"></i> <?= date('d.m.Y, H:i', strtotime($item['created_at'])) ?> Uhr</span>
<span>
<i class="fa-solid fa-thumbs-up"></i> <?= $item['likes_count'] ?>
&middot;
<i class="fa-solid fa-thumbs-down"></i> <?= $item['dislikes_count'] ?>
</span>
</div>
</div>
</div>
<!-- Action Buttons -->
<div class="action-buttons">
<?php if ($item['status'] !== 'approved'): ?>
<button class="btn btn-approve" onclick="changeStatus(<?= $item['contribution_id'] ?>, 'approved')">
<i class="fa-solid fa-check"></i> Akzeptieren
</button>
<?php endif; ?>
<?php if ($item['status'] !== 'rejected'): ?>
<button class="btn btn-reject" onclick="changeStatus(<?= $item['contribution_id'] ?>, 'rejected')">
<i class="fa-solid fa-xmark"></i> Ablehnen
</button>
<?php endif; ?>
<?php if ($item['status'] !== 'pending'): ?>
<button class="btn btn-reset" onclick="changeStatus(..., 'pending')">
<i class="fa-solid fa-rotate-left"></i> Zurücksetzen
</button>
<?php endif; ?>
<button class="btn btn-edit" onclick="editContribution(<?= $item['contribution_id'] ?>, '<?= htmlspecialchars(addslashes($item['title']), ENT_QUOTES) ?>', '<?= htmlspecialchars(addslashes($item['description'] ?? ''), ENT_QUOTES) ?>')">
<i class="fa-solid fa-pen"></i> Bearbeiten
</button>
<button class="btn btn-delete" onclick="deleteContribution(<?= $item['contribution_id'] ?>)">
<i class="fa-solid fa-trash"></i> Löschen
</button>
<a class="btn btn-map" href="index.php" target="_blank">
<i class="fa-solid fa-map-location-dot"></i> Karte
</a>
</div>
</div>
</div>
<?php endforeach; ?>
<?php endif; ?>
</div>
</div>
<!-- ========================================================= -->
<!-- News Article Tab -->
<!-- ========================================================= -->
<div id="tab-news" class="page-tab-content" style="display:none;">
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;">
<h2 style="margin:0;border:none;padding:0;"><i class="fa-solid fa-newspaper"></i> Neuigkeiten</h2>
<button class="btn btn-approve" onclick="createNews()">
<i class="fa-solid fa-plus"></i> Nachricht hinzufügen
</button>
</div>
<?php if (empty($news_items)): ?>
<div class="empty-state">
<i class="fa-solid fa-newspaper" style="font-size:2rem;margin-bottom:8px;display:block;"></i>
Noch keine Neuigkeiten veröffentlicht.
</div>
<?php else: ?>
<?php foreach ($news_items as $news): ?>
<div class="contribution-row" data-id="<?= $news['news_id'] ?>">
<div class="contribution-row-header" onclick="toggleRow(this.parentElement)">
<div class="contribution-row-summary">
<span class="title"><?= htmlspecialchars($news['title']) ?></span>
<span style="font-size:0.8rem;color:#999;">
<?= date('d.m.Y', strtotime($news['published_at'])) ?>
· <?= htmlspecialchars($news['author_name']) ?>
</span>
</div>
<i class="fa-solid fa-chevron-down collapse-icon"></i>
</div>
<div class="contribution-row-detail">
<div style="padding:12px 0;font-size:0.9rem;line-height:1.6;color:#5a5a7a;">
<?= nl2br(htmlspecialchars($news['content'])) ?>
</div>
<div class="action-buttons">
<button class="btn btn-edit" onclick="editNews(<?= $news['news_id'] ?>, '<?= htmlspecialchars(addslashes($news['title']), ENT_QUOTES) ?>', '<?= htmlspecialchars(addslashes($news['content']), ENT_QUOTES) ?>', '<?= htmlspecialchars(addslashes($news['author_name']), ENT_QUOTES) ?>')">
<i class="fa-solid fa-pen"></i> Bearbeiten
</button>
<button class="btn btn-delete" onclick="deleteNews(<?= $news['news_id'] ?>)">
<i class="fa-solid fa-trash"></i> Löschen
</button>
</div>
</div>
</div>
<?php endforeach; ?>
<?php endif; ?>
</div>
<!-- ========================================================= -->
<!-- Placeholder Tabs for future Features -->
<!-- ========================================================= -->
<div id="tab-stats" class="page-tab-content" style="display:none;">
<div class="placeholder-content">
<i class="fa-solid fa-chart-bar"></i>
<p>Statistiken und Analysen - geplant in zukünftiger Version.</p>
</div>
</div>
<div id="tab-users" class="page-tab-content" style="display:none;">
<div class="placeholder-content">
<i class="fa-solid fa-users"></i>
<p>Benutzerverwaltung - geplant in zukünftiger Version.</p>
</div>
</div>
</div>
<!-- ============================================================= -->
<!-- JavaScript: Leaflet, Interactions, API Calls -->
<!-- ============================================================= -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.min.js"></script>
<script>
// Municipality Configuration for Map Previews
const MUNICIPALITY_CENTER = [<?= $municipality['center_lat'] ?>, <?= $municipality['center_lng'] ?>];
const MUNICIPALITY_ID = <?= $municipality['municipality_id'] ?>;
const API_URL = 'api/contributions.php';
const PRIMARY_COLOR = '<?= htmlspecialchars($municipality['primary_color']) ?>';
// Current Status Filter
let currentFilter = 'all';
// =============================================================
// Page Tab Navigation
// =============================================================
function showPageTab(tabName) {
// Hides all Tab Contents
document.querySelectorAll('.page-tab-content').forEach(function (el) {
el.style.display = 'none';
});
// Deactivates all Tab Buttons
document.querySelectorAll('.page-tab').forEach(function (el) {
el.classList.remove('active');
});
// Shows selected Tab and activates Button
document.getElementById('tab-' + tabName).style.display = 'block';
event.currentTarget.classList.add('active');
}
// =============================================================
// Collapsible Rows
// =============================================================
function toggleRow(row) {
const wasOpen = row.classList.contains('open');
// Closes all open Rows
document.querySelectorAll('.contribution-row.open').forEach(function (el) {
el.classList.remove('open');
});
// Toggles clicked Row
if (!wasOpen) {
row.classList.add('open');
// Loads Map Preview if not already loaded
const mapDiv = row.querySelector('.detail-map');
if (mapDiv && !mapDiv.dataset.loaded) {
loadMapPreview(mapDiv);
}
}
}
// =============================================================
// Map Preview (Leaflet Mini Map per Contribution)
// =============================================================
function loadMapPreview(mapDiv) {
const contributionId = mapDiv.dataset.contributionId;
// Fetches all Contributions to find the Geometry
const formData = new FormData();
formData.append('action', 'read');
formData.append('municipality_id', MUNICIPALITY_ID);
formData.append('status', 'all');
fetch(API_URL, { method: 'POST', body: formData })
.then(function (r) { return r.json(); })
.then(function (data) {
if (!data.features) return;
// Finds specific Contribution
const feature = data.features.find(function (f) {
return f.properties.contribution_id == contributionId;
});
if (!feature) {
mapDiv.innerHTML = '<div style="padding:20px;color:#999;text-align:center;font-size:0.8rem;">Geometrie nicht gefunden.</div>';
return;
}
// Creates Leaflet Mini Map
const miniMap = L.map(mapDiv, {
zoomControl: false,
attributionControl: false,
dragging: true,
scrollWheelZoom: false
});
L.tileLayer('https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png', {
maxZoom: 20
}).addTo(miniMap);
// Adds Geometry to Mini Map
const geojsonLayer = L.geoJSON(feature, {
style: { color: PRIMARY_COLOR, weight: 3, fillOpacity: 0.2 },
pointToLayer: function (f, latlng) {
return L.circleMarker(latlng, {
radius: 8, color: '#ffffff', weight: 2,
fillColor: PRIMARY_COLOR, fillOpacity: 0.9
});
}
}).addTo(miniMap);
// Fits Map to Geometry Bounds
const bounds = geojsonLayer.getBounds();
if (bounds.isValid()) {
miniMap.fitBounds(bounds, { padding: [25, 25], maxZoom: 17 });
} else {
miniMap.setView(MUNICIPALITY_CENTER, 15);
}
mapDiv.dataset.loaded = 'true';
})
.catch(function () {
mapDiv.innerHTML = '<div style="padding:20px;color:#999;text-align:center;font-size:0.8rem;">Karte nicht verfügbar.</div>';
});
}
// =============================================================
// Status Filter
// =============================================================
function filterByStatus(status, tabButton) {
currentFilter = status;
// Updates active Tab
document.querySelectorAll('.filter-tab').forEach(function (el) {
el.classList.remove('active');
});
tabButton.classList.add('active');
// Shows/Hides Contribution Rows
let visibleCount = 0;
document.querySelectorAll('.contribution-row').forEach(function (row) {
if (status === 'all' || row.dataset.status === status) {
row.style.display = '';
visibleCount++;
} else {
row.style.display = 'none';
}
});
// Updates Count Display
document.getElementById('visible-count').textContent = visibleCount + ' Beiträge';
}
// =============================================================
// Sort Contributions
// =============================================================
function sortContributions(sortBy) {
const container = document.getElementById('contributions-container');
const rows = Array.from(container.querySelectorAll('.contribution-row'));
rows.sort(function (a, b) {
if (sortBy === 'date-desc') {
return new Date(b.dataset.date) - new Date(a.dataset.date);
} else if (sortBy === 'date-asc') {
return new Date(a.dataset.date) - new Date(b.dataset.date);
} else if (sortBy === 'category') {
return a.dataset.category.localeCompare(b.dataset.category);
}
return 0;
});
// Reappends sorted Rows
rows.forEach(function (row) {
container.appendChild(row);
});
}
// =============================================================
// API Helper
// =============================================================
function apiCall(data) {
const formData = new FormData();
for (const key in data) {
formData.append(key, data[key]);
}
return fetch(API_URL, { method: 'POST', body: formData })
.then(function (r) { return r.json(); });
}
// =============================================================
// Change Contribution Status
// =============================================================
function changeStatus(contributionId, newStatus) {
const labels = { approved: 'freigeben', rejected: 'ablehnen', pending: 'zurücksetzen' };
Swal.fire({
title: 'Beitrag ' + labels[newStatus] + '?',
showCancelButton: true,
confirmButtonText: 'Ja',
cancelButtonText: 'Abbrechen',
confirmButtonColor: PRIMARY_COLOR
}).then(function (result) {
if (!result.isConfirmed) return;
apiCall({
action: 'update',
contribution_id: contributionId,
status: newStatus
}).then(function (response) {
if (response.error) {
Swal.fire('Fehler', response.error, 'error');
return;
}
// Reloads Page to reflect Changes
location.reload();
});
});
}
// =============================================================
// Edit Contribution (Title and Description)
// =============================================================
function editContribution(contributionId, currentTitle, currentDescription) {
Swal.fire({
title: 'Beitrag bearbeiten',
html:
'<div style="text-align:left;">' +
'<div style="margin-bottom:12px;">' +
'<label style="display:block;font-weight:600;font-size:1.15rem;margin-bottom:4px;">Titel</label>' +
'<input id="swal-title" class="swal2-input" style="margin:0;width:100%;" value="' + currentTitle + '">' +
'</div>' +
'<div>' +
'<label style="display:block;font-weight:600;font-size:1.15rem;margin-bottom:4px;">Beschreibung</label>' +
'<textarea id="swal-description" class="swal2-textarea" style="margin:0;width:100%;">' + currentDescription + '</textarea>' +
'</div>' +
'</div>',
showCancelButton: true,
confirmButtonText: 'Speichern',
cancelButtonText: 'Abbrechen',
confirmButtonColor: PRIMARY_COLOR,
preConfirm: function () {
return {
title: document.getElementById('swal-title').value.trim(),
description: document.getElementById('swal-description').value.trim()
};
}
}).then(function (result) {
if (!result.isConfirmed) return;
apiCall({
action: 'update',
contribution_id: contributionId,
title: result.value.title,
description: result.value.description
}).then(function (response) {
if (response.error) {
Swal.fire('Fehler', response.error, 'error');
return;
}
Swal.fire('Gespeichert!', 'Beitrag wurde aktualisiert.', 'success')
.then(function () { location.reload(); });
});
});
}
// =============================================================
// Delete Contribution
// =============================================================
function deleteContribution(contributionId) {
Swal.fire({
title: 'Beitrag löschen?',
text: 'Diese Aktion kann nicht rückgängig gemacht werden.',
icon: 'warning',
showCancelButton: true,
confirmButtonText: 'Beitrag löschen',
cancelButtonText: 'Abbrechen',
confirmButtonColor: '#c62828'
}).then(function (result) {
if (!result.isConfirmed) return;
apiCall({
action: 'delete',
contribution_id: contributionId
}).then(function (response) {
if (response.error) {
Swal.fire('Fehler', response.error, 'error');
return;
}
Swal.fire('Gelöscht!', 'Beitrag wurde gelöscht.', 'success')
.then(function () { location.reload(); });
});
});
}
// =============================================================
// Create News Article
// =============================================================
function createNews() {
Swal.fire({
title: 'Neuigkeit hinzufügen',
html:
'<div style="text-align:left;">' +
'<div style="margin-bottom:12px;">' +
'<label style="display:block;font-weight:600;font-size:1.15rem;margin-bottom:4px;">Titel</label>' +
'<input id="swal-news-title" class="swal2-input" style="margin:0;width:100%;" placeholder="Titel der Neuigkeit">' +
'</div>' +
'<div style="margin-bottom:12px;">' +
'<label style="display:block;font-weight:600;font-size:1.15rem;margin-bottom:4px;">Inhalt</label>' +
'<textarea id="swal-news-content" class="swal2-textarea" style="margin:0;width:100%;" placeholder="Neuigkeit verfassen..."></textarea>' +
'</div>' +
'<div>' +
'<label style="display:block;font-weight:600;font-size:1.15rem;margin-bottom:4px;">Autor</label>' +
'<input id="swal-news-author" class="swal2-input" style="margin:0;width:100%;" value="Stadtverwaltung">' +
'</div>' +
'</div>',
showCancelButton: true,
confirmButtonText: 'Veröffentlichen',
cancelButtonText: 'Abbrechen',
confirmButtonColor: PRIMARY_COLOR,
preConfirm: function () {
const title = document.getElementById('swal-news-title').value.trim();
const content = document.getElementById('swal-news-content').value.trim();
const author = document.getElementById('swal-news-author').value.trim() || 'Stadtverwaltung';
if (!title || !content) {
Swal.showValidationMessage('Titel und Inhalt sind Pflichtfelder.');
return false;
}
return { title: title, content: content, author_name: author };
}
}).then(function (result) {
if (!result.isConfirmed) return;
const formData = new FormData();
formData.append('action', 'create_news');
formData.append('municipality_id', MUNICIPALITY_ID);
formData.append('title', result.value.title);
formData.append('content', result.value.content);
formData.append('author_name', result.value.author_name);
fetch(API_URL, { method: 'POST', body: formData })
.then(function (r) { return r.json(); })
.then(function (response) {
if (response.error) {
Swal.fire('Fehler', response.error, 'error');
return;
}
Swal.fire('Veröffentlicht!', 'Neuigkeit wurde veröffentlicht.', 'success')
.then(function () { location.reload(); });
});
});
}
// =============================================================
// Edit News Article
// =============================================================
function editNews(newsId, currentTitle, currentContent, currentAuthor) {
Swal.fire({
title: 'Neuigkeit bearbeiten',
html:
'<div style="text-align:left;">' +
'<div style="margin-bottom:12px;">' +
'<label style="display:block;font-weight:600;font-size:1.15rem;margin-bottom:4px;">Titel</label>' +
'<input id="swal-news-title" class="swal2-input" style="margin:0;width:100%;" value="' + currentTitle + '">' +
'</div>' +
'<div style="margin-bottom:12px;">' +
'<label style="display:block;font-weight:600;font-size:1.15rem;margin-bottom:4px;">Inhalt</label>' +
'<textarea id="swal-news-content" class="swal2-textarea" style="margin:0;width:100%;">' + currentContent + '</textarea>' +
'</div>' +
'<div>' +
'<label style="display:block;font-weight:600;font-size:1.15rem;margin-bottom:4px;">Autor</label>' +
'<input id="swal-news-author" class="swal2-input" style="margin:0;width:100%;" value="' + currentAuthor + '">' +
'</div>' +
'</div>',
showCancelButton: true,
confirmButtonText: 'Speichern',
cancelButtonText: 'Abbrechen',
confirmButtonColor: PRIMARY_COLOR,
preConfirm: function () {
return {
title: document.getElementById('swal-news-title').value.trim(),
content: document.getElementById('swal-news-content').value.trim(),
author_name: document.getElementById('swal-news-author').value.trim() || 'Stadtverwaltung'
};
}
}).then(function (result) {
if (!result.isConfirmed) return;
const formData = new FormData();
formData.append('action', 'update_news');
formData.append('news_id', newsId);
formData.append('title', result.value.title);
formData.append('content', result.value.content);
formData.append('author_name', result.value.author_name);
fetch(API_URL, { method: 'POST', body: formData })
.then(function (r) { return r.json(); })
.then(function (response) {
if (response.error) {
Swal.fire('Fehler', response.error, 'error');
return;
}
Swal.fire('Gespeichert!', 'Neuigkeit wurde aktualisiert.', 'success')
.then(function () { location.reload(); });
});
});
}
// =============================================================
// Create News Article
// =============================================================
function deleteNews(newsId) {
Swal.fire({
title: 'Neuigkeit löschen?',
text: 'Diese Aktion kann nicht rückgängig gemacht werden.',
icon: 'warning',
showCancelButton: true,
confirmButtonText: 'Löschen',
cancelButtonText: 'Abbrechen',
confirmButtonColor: '#c62828'
}).then(function (result) {
if (!result.isConfirmed) return;
const formData = new FormData();
formData.append('action', 'delete_news');
formData.append('news_id', newsId);
fetch(API_URL, { method: 'POST', body: formData })
.then(function (r) { return r.json(); })
.then(function (response) {
if (response.error) {
Swal.fire('Fehler', response.error, 'error');
return;
}
Swal.fire('Gelöscht!', 'Neuigkeit wurde gelöscht.', 'success')
.then(function () { location.reload(); });
});
});
}
</script>
</body>
</html>
<?php
// -----------------------------------------------------------------
// Login Page
// -----------------------------------------------------------------
function show_login_page($municipality, $error = null) {
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Moderation - Anmeldung</title>
<link rel="icon" href="<?= htmlspecialchars($municipality['logo_path'] ?? 'assets/icon-municipality.png') ?>" type="image/png"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<link rel="stylesheet" href="styles.css">
<style>:root { --color-primary: <?= htmlspecialchars($municipality['primary_color']) ?>; }</style>
</head>
<body>
<div class="login-wrapper">
<div class="login-box">
<h1><i class="fa-solid fa-shield-halved"></i> Moderationsportal</h1>
<p>Bitte geben Sie das Moderationspasswort ein.</p>
<?php if ($error): ?>
<div class="login-error"><i class="fa-solid fa-triangle-exclamation"></i> <?= htmlspecialchars($error) ?></div>
<?php endif; ?>
<form method="POST" action="admin.php?page=login">
<input type="password" name="password" placeholder="Passwort" autofocus>
<button type="submit"><i class="fa-solid fa-right-to-bracket"></i> Anmelden</button>
</form>
<div class="back-link"><i class="fa fa-arrow-left"></i></i> <a href="index.php">Zurück zum Bürgerportal</a></div>
</div>
</div>
</body>
</html>
<?php
}
?>

28
public/api/auth.php Normal file
View File

@@ -0,0 +1,28 @@
<?php
// =====================================================================
// Admin Authentication Helper
// Provides simple Password-based Session Authentication for the
// Moderation Page. Reads Password from .env File.
// ToDo: Replace with full User Authentication in Phase 3-3.
// =====================================================================
// Checks if current Session is authenticated as Admin
function is_admin() {
return isset($_SESSION['is_admin']) && $_SESSION['is_admin'] === true;
}
// Authenticates with Password, returns true on Success
function admin_login($password) {
$correct = getenv('ADMIN_PASSWORD');
if ($correct && $password === $correct) {
$_SESSION['is_admin'] = true;
return true;
}
return false;
}
// Logs out Admin Session
function admin_logout() {
$_SESSION['is_admin'] = false;
session_destroy();
}

View File

@@ -38,13 +38,31 @@ switch ($action) {
case 'vote': case 'vote':
handle_vote($input); handle_vote($input);
break; break;
case 'create_news':
handle_create_news($input);
break;
case 'update_news':
handle_update_news($input);
break;
case 'delete_news':
handle_delete_news($input);
break;
case 'read_comments':
handle_read_comments($input);
break;
case 'create_comment':
handle_create_comment($input);
break;
case 'delete_comment':
handle_delete_comment($input);
break;
default: default:
error_response('Unknown Action. Supported Actions are read, create, update, delete, vote.'); error_response('Unknown Action. Supported Actions are read, create, update, delete, vote.');
} }
// ===================================================================== // =====================================================================
// Action Handlers // Action Handlers for Contributions
// ===================================================================== // =====================================================================
@@ -67,9 +85,16 @@ function handle_read($input) {
// Builds SQL Query with Placeholders for prepared Statement // Builds SQL Query with Placeholders for prepared Statement
$sql = "SELECT *, ST_AsGeoJSON(geom) AS geojson $sql = "SELECT *, ST_AsGeoJSON(geom) AS geojson
FROM contributions FROM contributions
WHERE municipality_id = :mid AND status = 'approved'"; WHERE municipality_id = :mid";
$params = [':mid' => $municipality_id]; $params = [':mid' => $municipality_id];
// Optional: Filters by Status (Default: only approved)
$status = $input['status'] ?? 'approved';
if ($status !== 'all') {
$sql .= " AND status = :status";
$params[':status'] = $status;
}
// Optional: Filters by Category // Optional: Filters by Category
if (!empty($input['category'])) { if (!empty($input['category'])) {
$sql .= " AND category = :cat"; $sql .= " AND category = :cat";
@@ -110,6 +135,23 @@ function handle_read($input) {
'features' => $features 'features' => $features
]; ];
// Includes User's Votes for persistent Vote Display
// Returns which Contributions the current Browser has voted on
$browser_id = $input['browser_id'] ?? '';
if ($browser_id !== '') {
$stmt = $pdo->prepare("
SELECT contribution_id, vote_type
FROM votes
WHERE browser_id = :bid
");
$stmt->execute([':bid' => $browser_id]);
$user_votes = [];
foreach ($stmt->fetchAll() as $v) {
$user_votes[$v['contribution_id']] = $v['vote_type'];
}
$featureCollection['user_votes'] = $user_votes;
}
json_response($featureCollection); json_response($featureCollection);
} }
@@ -119,6 +161,11 @@ function handle_read($input) {
// Required: municipality_id, geom, geom_type, category, title, author_name // Required: municipality_id, geom, geom_type, category, title, author_name
// Optional: description // Optional: description
// --------------------------------------------------------------------- // ---------------------------------------------------------------------
// ---------------------------------------------------------------------
// CREATE: Inserts new Contributions with optional Photo Upload
// Required: municipality_id, geom, geom_type, category, title, author_name
// Optional: description, browser_id, photo (File Upload)
// ---------------------------------------------------------------------
function handle_create($input) { function handle_create($input) {
$pdo = get_db(); $pdo = get_db();
@@ -142,14 +189,23 @@ function handle_create($input) {
error_response('Invalid GeoJSON in Geometry Field.'); error_response('Invalid GeoJSON in Geometry Field.');
} }
// Handles Photo Upload
$photo_path = null;
if (isset($_FILES['photo']) && $_FILES['photo']['error'] === UPLOAD_ERR_OK) {
$photo_path = handle_photo_upload($_FILES['photo']);
if (!$photo_path) {
error_response('Photo Upload failed. JPG, PNG, GIF and WebP up to 5 MB are allowed.');
}
}
// Prepared SQL Statement // Prepared SQL Statement
try { try {
$stmt = $pdo->prepare(" $stmt = $pdo->prepare("
INSERT INTO contributions INSERT INTO contributions
(municipality_id, geom, geom_type, category, title, description, author_name) (municipality_id, geom, geom_type, category, title, description, author_name, browser_id, photo_path)
VALUES VALUES
(:mid, ST_SetSRID(ST_GeomFromGeoJSON(:geom), 4326), :geom_type, (:mid, ST_SetSRID(ST_GeomFromGeoJSON(:geom), 4326), :geom_type,
:category, :title, :description, :author_name) :category, :title, :description, :author_name, :browser_id, :photo_path)
"); ");
$stmt->execute([ $stmt->execute([
@@ -159,7 +215,9 @@ function handle_create($input) {
':category' => $input['category'], ':category' => $input['category'],
':title' => $input['title'], ':title' => $input['title'],
':description' => $input['description'] ?? '', ':description' => $input['description'] ?? '',
':author_name' => $input['author_name'] ':author_name' => $input['author_name'],
':browser_id' => $input['browser_id'] ?? null,
':photo_path' => $photo_path
]); ]);
json_response([ json_response([
@@ -198,7 +256,7 @@ function handle_update($input) {
} }
// Builds dynamic SQL Query to only update sent Fields // Builds dynamic SQL Query to only update sent Fields
$updatable_fields = ['category', 'title', 'description', 'status']; $updatable_fields = ['category', 'title', 'description', 'status', 'address'];
$set_clauses = []; $set_clauses = [];
$params = [':id' => $contribution_id]; $params = [':id' => $contribution_id];
@@ -303,24 +361,320 @@ function handle_vote($input) {
// Prepared SQL Statement // Prepared SQL Statement
try { try {
$stmt = $pdo->prepare(" // Checks if Voter already voted on this Contribution
INSERT INTO votes (contribution_id, voter_name, vote_type) $browser_id = $input['browser_id'] ?? '';
VALUES (:cid, :voter, :vtype) if (empty($browser_id)) {
"); error_response('Browser ID required for Voting.');
}
$stmt = $pdo->prepare("
SELECT vote_id, vote_type FROM votes
WHERE contribution_id = :cid AND browser_id = :bid
");
$stmt->execute([':cid' => $input['contribution_id'], ':bid' => $browser_id]);
$existing = $stmt->fetch();
if ($existing) {
if ($existing['vote_type'] === $input['vote_type']) {
// Same Vote Type — Removes Vote
$stmt = $pdo->prepare("DELETE FROM votes WHERE vote_id = :vid");
$stmt->execute([':vid' => $existing['vote_id']]);
json_response(['message' => 'Vote removed.', 'action' => 'removed']);
} else {
// Different Vote Type — Switches Vote
$stmt = $pdo->prepare("DELETE FROM votes WHERE vote_id = :vid");
$stmt->execute([':vid' => $existing['vote_id']]);
$stmt = $pdo->prepare("
INSERT INTO votes (contribution_id, voter_name, vote_type, browser_id)
VALUES (:cid, :voter, :vtype, :bid)
");
$stmt->execute([ $stmt->execute([
':cid' => $input['contribution_id'], ':cid' => $input['contribution_id'],
':voter' => $input['voter_name'], ':voter' => $input['voter_name'],
':vtype' => $input['vote_type'] ':vtype' => $input['vote_type'],
':bid' => $browser_id
]); ]);
json_response(['message' => 'Vote changed.', 'action' => 'changed'], 200);
json_response(['message' => 'Vote recorded successfully.'], 201); }
} else {
// No existing Vote — Inserts Vote
$stmt = $pdo->prepare("
INSERT INTO votes (contribution_id, voter_name, vote_type, browser_id)
VALUES (:cid, :voter, :vtype, :bid)
");
$stmt->execute([
':cid' => $input['contribution_id'],
':voter' => $input['voter_name'],
':vtype' => $input['vote_type'],
':bid' => $browser_id
]);
json_response(['message' => 'Vote recorded.', 'action' => 'created'], 201);
}
} catch (PDOException $e) {
error_response('Database Error: ' . $e->getMessage(), 500);
}
}
// =====================================================================
// Action Handlers for News
// =====================================================================
// ---------------------------------------------------------------------
// CREATE NEWS: Inserts new News Entry
// Required: municipality_id, title, content
// ---------------------------------------------------------------------
function handle_create_news($input) {
$pdo = get_db();
$missing = validate_required($input, ['municipality_id', 'title', 'content']);
if (!empty($missing)) {
error_response('Missing Fields: ' . implode(', ', $missing));
}
try {
$stmt = $pdo->prepare("
INSERT INTO news (municipality_id, title, content, author_name)
VALUES (:mid, :title, :content, :author)
");
$stmt->execute([
':mid' => $input['municipality_id'],
':title' => $input['title'],
':content' => $input['content'],
':author' => $input['author_name'] ?? 'Stadtverwaltung'
]);
json_response(['message' => 'News created successfully.', 'news_id' => (int) $pdo->lastInsertId()], 201);
} catch (PDOException $e) {
error_response('Database Error: ' . $e->getMessage(), 500);
}
}
// ---------------------------------------------------------------------
// UPDATE NEWS: Updates existing News Entry
// Required: news_id
// Optional: title, content
// ---------------------------------------------------------------------
function handle_update_news($input) {
$pdo = get_db();
$missing = validate_required($input, ['news_id']);
if (!empty($missing)) {
error_response('Missing Fields: ' . implode(', ', $missing));
}
$set = [];
$params = [':id' => $input['news_id']];
foreach (['title', 'content', 'author_name'] as $field) {
if (isset($input[$field]) && $input[$field] !== '') {
$set[] = "$field = :$field";
$params[":$field"] = $input[$field];
}
}
if (empty($set)) {
error_response('No Fields to update.');
}
try {
$stmt = $pdo->prepare("UPDATE news SET " . implode(', ', $set) . " WHERE news_id = :id");
$stmt->execute($params);
json_response(['message' => 'News updated successfully.']);
} catch (PDOException $e) {
error_response('Database Error: ' . $e->getMessage(), 500);
}
}
// ---------------------------------------------------------------------
// DELETE NEWS: Deletes existing News Entry
// Required: news_id
// ---------------------------------------------------------------------
function handle_delete_news($input) {
$pdo = get_db();
$missing = validate_required($input, ['news_id']);
if (!empty($missing)) {
error_response('Missing Fields: ' . implode(', ', $missing));
}
try {
$stmt = $pdo->prepare("DELETE FROM news WHERE news_id = :id");
$stmt->execute([':id' => $input['news_id']]);
json_response(['message' => 'News deleted successfully.']);
} catch (PDOException $e) {
error_response('Database Error: ' . $e->getMessage(), 500);
}
}
// =====================================================================
// Action Handlers for Photos
// =====================================================================
// ---------------------------------------------------------------------
// PHOTO UPLOAD: Validates and Saves uploaded Photo Files
// Returns relative Path on Success, null on Failure.
// Allowed: JPG, PNG, GIF, WebP. with maximum Size of 5 MB.
// ---------------------------------------------------------------------
function handle_photo_upload($file) {
// Validates File Size
$max_size = 5 * 1024 * 1024;
if ($file['size'] > $max_size) {
return null;
}
// Validates MIME Type
$allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $file['tmp_name']);
finfo_close($finfo);
if (!in_array($mime, $allowed_types)) {
return null;
}
// Generates unique Filename
$ext = [
'image/jpeg' => 'jpg',
'image/png' => 'png',
'image/gif' => 'gif',
'image/webp' => 'webp'
][$mime];
$filename = uniqid('photo_', true) . '.' . $ext;
$upload_dir = __DIR__ . '/../uploads/photos/';
$target_path = $upload_dir . $filename;
// Creates Upload Directory
if (!is_dir($upload_dir)) {
mkdir($upload_dir, 0755, true);
}
// Moves uploaded File
if (move_uploaded_file($file['tmp_name'], $target_path)) {
return 'uploads/photos/' . $filename;
}
return null;
}
// =====================================================================
// Action Handlers for Comments
// =====================================================================
// ---------------------------------------------------------------------
// READ COMMENTS: Loads Comments for a Contribution
// Returns Comments sorted by Date (newest first)
// Required: contribution_id
// ---------------------------------------------------------------------
function handle_read_comments($input) {
$pdo = get_db();
$missing = validate_required($input, ['contribution_id']);
if (!empty($missing)) {
error_response('Missing Fields: ' . implode(', ', $missing));
}
try {
$stmt = $pdo->prepare("
SELECT comment_id, contribution_id, author_name, browser_id, content, created_at
FROM comments
WHERE contribution_id = :cid
ORDER BY created_at ASC
");
$stmt->execute([':cid' => $input['contribution_id']]);
$comments = $stmt->fetchAll();
json_response(['comments' => $comments, 'count' => count($comments)]);
} catch (PDOException $e) {
error_response('Database Error: ' . $e->getMessage(), 500);
}
}
// ---------------------------------------------------------------------
// CREATE COMMENT: Adds Comments to Contributions
// Required: contribution_id, author_name, content
// Optional: browser_id
// ---------------------------------------------------------------------
function handle_create_comment($input) {
$pdo = get_db();
$missing = validate_required($input, ['contribution_id', 'author_name', 'content']);
if (!empty($missing)) {
error_response('Missing Fields: ' . implode(', ', $missing));
}
// Validates Content Length
if (strlen($input['content']) > 1000) {
error_response('Comment too long. Maximum 1000 Characters.');
}
// Checks if Contribution exists
$stmt = $pdo->prepare("SELECT contribution_id FROM contributions WHERE contribution_id = :id");
$stmt->execute([':id' => $input['contribution_id']]);
if (!$stmt->fetch()) {
error_response('Contribution not found.', 404);
}
try {
$stmt = $pdo->prepare("
INSERT INTO comments (contribution_id, author_name, browser_id, content)
VALUES (:cid, :author, :bid, :content)
");
$stmt->execute([
':cid' => $input['contribution_id'],
':author' => $input['author_name'],
':bid' => $input['browser_id'] ?? null,
':content' => $input['content']
]);
$stmt2 = $pdo->prepare("
UPDATE contributions
SET comment_count = comment_count + 1
WHERE contribution_id = :cid;
");
$stmt2->execute([':cid' => $input['contribution_id']]);
json_response([
'message' => 'Comment created successfully.',
'comment_id' => (int) $pdo->lastInsertId()
], 201);
} catch (PDOException $e) {
error_response('Database Error: ' . $e->getMessage(), 500);
}
}
// ---------------------------------------------------------------------
// DELETE COMMENT: Removes a Comment
// Required: comment_id
// ---------------------------------------------------------------------
function handle_delete_comment($input) {
$pdo = get_db();
$missing = validate_required($input, ['comment_id']);
if (!empty($missing)) {
error_response('Missing Fields: ' . implode(', ', $missing));
}
try {
$stmt = $pdo->prepare("DELETE FROM comments WHERE comment_id = :id");
$stmt->execute([':id' => $input['comment_id']]);
$stmt2 = $pdo->prepare("
UPDATE contributions
SET comment_count = comment_count - 1
WHERE contribution_id = :cid;
");
$stmt2->execute([':cid' => $input['contribution_id']]);
json_response(['message' => 'Comment deleted successfully.']);
} catch (PDOException $e) { } catch (PDOException $e) {
// UNIQUE Constraint Violation - Voter already voted on this Contribution
if ($e->getCode() == '23505') {
error_response('You have already voted on this Contribution.', 409);
}
error_response('Database Error: ' . $e->getMessage(), 500); error_response('Database Error: ' . $e->getMessage(), 500);
} }
} }

View File

@@ -1,8 +1,8 @@
<?php <?php
// ===================================================================== // =====================================================================
// Database Helper // Database Helper Functions
// Provides PDO Connection to Database and shared miscellaneous // Provides PDO Connection, JSON Response Helpers, Category Definitions
// Functions for all API Endpoints. // and shared miscellaneous Functions for all API Endpoints.
// ===================================================================== // =====================================================================
require_once __DIR__ . '/init.php'; require_once __DIR__ . '/init.php';
@@ -92,3 +92,22 @@ function get_db() {
return $pdo; return $pdo;
} }
// ---------------------------------------------------------------------
// Category Definitions
// Returns associative Array of Category Keys to Labels, Icons,
// and Colors. Shared between Citizen Participation Portal and
// Moderation Page.
// ToDo: Move to Database Table.
// ---------------------------------------------------------------------
function get_categories() {
return [
'consumption' => ['label' => 'Geschäfte', 'faIcon' => 'fa-cart-shopping', 'color' => '#C00000'],
'building' => ['label' => 'Bauen', 'faIcon' => 'fa-building', 'color' => '#E65100'],
'energy' => ['label' => 'Energie', 'faIcon' => 'fa-bolt', 'color' => '#FFC000'],
'environment' => ['label' => 'Umwelt', 'faIcon' => 'fa-seedling', 'color' => '#92D050'],
'mobility' => ['label' => 'Mobilität', 'faIcon' => 'fa-bus', 'color' => '#0070C0'],
'industry' => ['label' => 'Industrie', 'faIcon' => 'fa-industry', 'color' => '#7030A0'],
'other' => ['label' => 'Sonstiges', 'faIcon' => 'fa-thumbtack', 'color' => '#7F7F7F'],
];
}

View File

@@ -28,24 +28,16 @@ session_start();
// Initializes Database Connection // Initializes Database Connection
try { try {
$opt = [ $dsn = "pgsql:host=$host;dbname=$db;port=$port";
$pdo = new PDO($dsn, $user, $pass, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false PDO::ATTR_EMULATE_PREPARES => false
]; ]);
$dsn = "pgsql:host=$host;dbname=$db;port=$port";
$pdo = new PDO($dsn, $user, $pass, $opt);
$pdo = new PDO($dsn, $user, $pass, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
// Creates Error Message // Creates Error Message
} catch(PDOException $e) { } catch (PDOException $e) {
echo "Error: ".$e->getMessage(); echo "Error: " . $e->getMessage();
} }
?> ?>

39
public/imprint.php Normal file
View File

@@ -0,0 +1,39 @@
<?php
require_once __DIR__ . '/api/db.php';
$pdo = get_db();
$stmt = $pdo->prepare("SELECT * FROM municipalities WHERE slug = :slug");
$stmt->execute([':slug' => getenv('MUNICIPALITY_SLUG')]);
$municipality = $stmt->fetch();
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Impressum — <?= htmlspecialchars($municipality['name']) ?></title>
<link rel="icon" href="<?= htmlspecialchars($municipality['logo_path'] ?? 'assets/icon-municipality.png') ?>" type="image/png">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<link rel="stylesheet" href="styles.css">
<style>:root { --color-primary: <?= htmlspecialchars($municipality['primary_color']) ?>; }</style>
</head>
<body>
<div class="page-header">
<div class="page-header-inner">
<h1><i class="fa-solid fa-scale-balanced"></i> Impressum</h1>
<div class="page-header-nav">
<a href="index.php"><i class="fa-solid fa-arrow-left"></i> Zurück zur Karte</a>
</div>
</div>
</div>
<div class="page-container">
<div class="page-content-box">
<div class="dev-notice">
<i class="fa-solid fa-triangle-exclamation"></i>
Dieses Portal befindet sich in der Entwicklung und wurde nicht offiziell beauftragt. Das Impressum wird mit der offiziellen Inbetriebnahme hier hinzugefügt.
</div>
<h2>Impressum</h2>
<p>Das Impressum wird hier hinzugefügt, sobald das Portal in den Produktivbetrieb geht.</p>
</div>
</div>
</body>
</html>

View File

@@ -6,6 +6,7 @@
// ===================================================================== // =====================================================================
require_once __DIR__ . '/api/db.php'; require_once __DIR__ . '/api/db.php';
require_once __DIR__ . '/api/auth.php';
// ----------------------------------------------------------------- // -----------------------------------------------------------------
// Loads Municipality Configuration // Loads Municipality Configuration
@@ -14,7 +15,7 @@ require_once __DIR__ . '/api/db.php';
// ----------------------------------------------------------------- // -----------------------------------------------------------------
$pdo = get_db(); $pdo = get_db();
$stmt = $pdo->prepare("SELECT * FROM municipalities WHERE slug = :slug"); $stmt = $pdo->prepare("SELECT * FROM municipalities WHERE slug = :slug");
$stmt->execute([':slug' => 'lohne']); $stmt->execute([':slug' => getenv('MUNICIPALITY_SLUG')]);
$municipality = $stmt->fetch(); $municipality = $stmt->fetch();
if (!$municipality) { if (!$municipality) {
@@ -23,6 +24,11 @@ if (!$municipality) {
exit; exit;
} }
// Loads News for Sidebar
$stmt = $pdo->prepare("SELECT * FROM news WHERE municipality_id = :mid ORDER BY published_at DESC LIMIT 10");
$stmt->execute([':mid' => $municipality['municipality_id']]);
$news_items = $stmt->fetchAll();
?> ?>
<!DOCTYPE html> <!DOCTYPE html>
<html lang="de"> <html lang="de">
@@ -30,7 +36,7 @@ if (!$municipality) {
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bürgerbeteiligungsportal <?= htmlspecialchars($municipality['name']) ?></title> <title>Bürgerbeteiligungsportal <?= htmlspecialchars($municipality['name']) ?></title>
<link rel="icon" href="assets/icon-municipality.png" type="image/png"> <link rel="icon" href="<?= htmlspecialchars($municipality['logo_path'] ?? 'assets/icon-municipality.png') ?>" type="image/png">
<meta name="description" content="Bürgerbeteiligungsportal. Hinweise und Vorschläge auf der Karte eintragen."> <meta name="description" content="Bürgerbeteiligungsportal. Hinweise und Vorschläge auf der Karte eintragen.">
@@ -54,12 +60,9 @@ if (!$municipality) {
<link rel="stylesheet" href="https://unpkg.com/leaflet-control-geocoder@2.4.0/dist/Control.Geocoder.css"> <link rel="stylesheet" href="https://unpkg.com/leaflet-control-geocoder@2.4.0/dist/Control.Geocoder.css">
<!-- Leaflet Polyline Measurement Tool --> <!-- Leaflet Polyline Measurement Tool -->
<link rel="stylesheet" href="https://ppete2.github.io/Leaflet.PolylineMeasure/Leaflet.PolylineMeasure.css"> <!-- <link rel="stylesheet" href="https://ppete2.github.io/Leaflet.PolylineMeasure/Leaflet.PolylineMeasure.css"> -->
<!-- SweetAlert2 for Confirmation Dialogs --> <!-- Font Awesome for Icons -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
<!-- Font Awesome 6 for Icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<!-- Application Styles --> <!-- Application Styles -->
@@ -76,15 +79,17 @@ if (!$municipality) {
</style> </style>
</head> </head>
<body> <body class="portal-page">
<!-- ============================================================= --> <!-- ============================================================= -->
<!-- Header --> <!-- Header -->
<!-- ============================================================= --> <!-- ============================================================= -->
<header id="app-header"> <header id="app-header">
<div class="header-left"> <div class="header-left">
<img src="assets/logo-municipality.png" alt="<?= htmlspecialchars($municipality['name']) ?>" class="header-logo" onerror="this.style.display='none'"> <?php if (!empty($municipality['logo_path'])): ?>
<h1 class="header-title">Bürgerbeteiligung <?= htmlspecialchars($municipality['name']) ?></h1> <img src="<?= htmlspecialchars($municipality['logo_path']) ?>" alt="<?= htmlspecialchars($municipality['name']) ?>" class="header-logo" onerror="this.style.display='none'">
<?php endif; ?>
<h1 class="header-title">Mitmachkarte <?= htmlspecialchars($municipality['name']) ?></h1>
</div> </div>
<nav class="header-nav"> <nav class="header-nav">
@@ -92,14 +97,17 @@ if (!$municipality) {
<i class="fa-solid fa-circle-info"></i> <i class="fa-solid fa-circle-info"></i>
<span class="nav-label">Informationen</span> <span class="nav-label">Informationen</span>
</button> </button>
<button class="nav-btn" onclick="showPrivacyModal()"> <a href="privacy.php" class="nav-btn" target="_blank">
<i class="fa-solid fa-shield-halved"></i> <i class="fa-solid fa-shield-halved"></i>
<span class="nav-label">Datenschutz</span> <span class="nav-label">Datenschutz</span>
</button> </a>
<button class="nav-btn" onclick="showImprintModal()"> <a href="imprint.php" class="nav-btn" target="_blank">
<i class="fa-solid fa-scale-balanced"></i> <i class="fa-solid fa-scale-balanced"></i>
<span class="nav-label">Impressum</span> <span class="nav-label">Impressum</span>
</button> </a>
<a href="admin.php" class="nav-btn nav-btn-admin" title="Moderationsbereich" target="_blank">
<i class="fa-solid fa-lock"></i>
</a>
</nav> </nav>
<!-- Mobile Hamburger Menu --> <!-- Mobile Hamburger Menu -->
@@ -196,12 +204,31 @@ if (!$municipality) {
<span class="leaflet-sidebar-close"><i class="fa-solid fa-xmark"></i></span> <span class="leaflet-sidebar-close"><i class="fa-solid fa-xmark"></i></span>
</h2> </h2>
<div class="sidebar-body"> <div class="sidebar-body">
<div class="news-item"> <!-- News Search -->
<span class="news-date">April 2026</span> <div class="list-search">
<h3>Portal gestartet</h3> <input type="text" id="news-search-input" placeholder="Neuigkeiten durchsuchen..." class="form-input" oninput="filterNews()">
<p>Das Bürgerbeteiligungsportal für <?= htmlspecialchars($municipality['name']) ?> ist online. Wir freuen uns auf Ihre Hinweise und Vorschläge!</p> </div>
<!-- News Items Container -->
<div id="news-list">
<?php if (empty($news_items)): ?>
<p style="text-align:center;color:#999;padding:20px;">Noch keine Neuigkeiten veröffentlicht.</p>
<?php else: ?>
<?php foreach ($news_items as $news): ?>
<div class="news-item"
data-title="<?= htmlspecialchars(strtolower($news['title'])) ?>"
data-content="<?= htmlspecialchars(strtolower($news['content'])) ?>"
data-author="<?= htmlspecialchars(strtolower($news['author_name'])) ?>">
<h3><?= htmlspecialchars($news['title']) ?></h3>
<p><?= nl2br(htmlspecialchars($news['content'])) ?></p>
<span class="news-date">
<?= htmlspecialchars($news['author_name']) ?>
· <?= date('d.m.Y', strtotime($news['published_at'])) ?>
</span>
</div>
<?php endforeach; ?>
<?php endif; ?>
</div> </div>
<!-- News Items can be added or loaded from Database here -->
</div> </div>
</div> </div>
@@ -218,9 +245,11 @@ if (!$municipality) {
<!-- Footer --> <!-- Footer -->
<!-- ============================================================= --> <!-- ============================================================= -->
<footer id="app-footer"> <footer id="app-footer">
<span class="dev-warning">
<i class="fa-solid fa-triangle-exclamation"></i> Pilotprojekt - nicht offiziell von der Stadt Lohne (Oldenburg) beauftragt
</span>
<div class="footer-content"> <div class="footer-content">
<img src="assets/logo-company.png" alt="Company Logo" class="footer-logo" onerror="this.style.display='none'"> <span class="footer-text">© <a href="https://endex-geodaten.de" target="_blank" style="color:inherit;">endex GmbH</a></span>
<span class="footer-text"> Bürgerbeteiligungsportal <?= htmlspecialchars($municipality['name']) ?> </span>
</div> </div>
</footer> </footer>
@@ -237,8 +266,10 @@ if (!$municipality) {
<li>Hinweise und Verbesserungsvorschläge für die Stadtverwaltung hinzufügen</li> <li>Hinweise und Verbesserungsvorschläge für die Stadtverwaltung hinzufügen</li>
<li>Bestehende Beiträge der Bürgerschaft betrachten und bewerten</li> <li>Bestehende Beiträge der Bürgerschaft betrachten und bewerten</li>
</ul> </ul>
<p>Zum Hinzufügen von Beiträgen geben Sie bitte zunächst Ihren Namen ein.</p> <p style="background:#fff3cd;padding:10px;border-radius:6px;border:1px solid #ffc107;font-size:0.85rem;color:#856404;">
<div class="modal-actions"> <i class="fa-solid fa-triangle-exclamation"></i> <strong>Hinweis:</strong> Dieses Bürgerbeteiligungsportal befindet sich noch in der Entwicklung und wurde nicht offiziell beauftragt.
</p>
<p>Zum Hinzufügen von Beiträgen geben Sie bitte zunächst Ihren Namen ein.</p> <div class="modal-actions">
<button class="btn btn-primary" onclick="closeWelcomeAndShowLogin()">Loslegen</button> <button class="btn btn-primary" onclick="closeWelcomeAndShowLogin()">Loslegen</button>
</div> </div>
</div> </div>
@@ -290,6 +321,15 @@ if (!$municipality) {
<textarea id="create-description" class="form-input" rows="4" placeholder="Detaillierte Beschreibung (optional)"></textarea> <textarea id="create-description" class="form-input" rows="4" placeholder="Detaillierte Beschreibung (optional)"></textarea>
</div> </div>
<!-- Photo Upload -->
<div class="form-group">
<label for="create-photo"></i> Foto</label>
<input type="file" id="create-photo" class="form-input" accept="image/jpeg,image/png,image/gif,image/webp">
<div id="photo-preview" style="margin-top:8px;display:none;">
<img id="photo-preview-img" style="max-width:100%;max-height:200px;border-radius:6px;border:1px solid var(--color-border);">
</div>
</div>
<input type="hidden" id="create-geom"> <input type="hidden" id="create-geom">
<input type="hidden" id="create-geom-type"> <input type="hidden" id="create-geom-type">
@@ -321,17 +361,17 @@ if (!$municipality) {
<script src="https://unpkg.com/leaflet-control-geocoder@2.4.0/dist/Control.Geocoder.min.js"></script> <script src="https://unpkg.com/leaflet-control-geocoder@2.4.0/dist/Control.Geocoder.min.js"></script>
<!-- Leaflet PolylineMeasure --> <!-- Leaflet PolylineMeasure -->
<script src="https://ppete2.github.io/Leaflet.PolylineMeasure/Leaflet.PolylineMeasure.js"></script> <!-- <script src="https://ppete2.github.io/Leaflet.PolylineMeasure/Leaflet.PolylineMeasure.js"></script> -->
<!-- SweetAlert2 --> <!-- SweetAlert2 -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.14.0/dist/sweetalert2.all.min.js"></script>
<!-- ============================================================= --> <!-- ============================================================= -->
<!-- Municipality Configuration (passed to JavaScript) --> <!-- Municipality Configuration passed to JavaScript -->
<!-- ============================================================= --> <!-- ============================================================= -->
<script> <script>
// Municipality Configuration from Database — used by app.js // Municipality Configuration from Database — used by app.js
var MUNICIPALITY = { const MUNICIPALITY = {
id: <?= $municipality['municipality_id'] ?>, id: <?= $municipality['municipality_id'] ?>,
name: "<?= htmlspecialchars($municipality['name'], ENT_QUOTES) ?>", name: "<?= htmlspecialchars($municipality['name'], ENT_QUOTES) ?>",
slug: "<?= htmlspecialchars($municipality['slug'], ENT_QUOTES) ?>", slug: "<?= htmlspecialchars($municipality['slug'], ENT_QUOTES) ?>",
@@ -339,6 +379,12 @@ if (!$municipality) {
zoom: <?= $municipality['default_zoom'] ?>, zoom: <?= $municipality['default_zoom'] ?>,
primaryColor: "<?= htmlspecialchars($municipality['primary_color'], ENT_QUOTES) ?>" primaryColor: "<?= htmlspecialchars($municipality['primary_color'], ENT_QUOTES) ?>"
}; };
// Category Definitions from Database
const CATEGORIES = <?= json_encode(get_categories(), JSON_UNESCAPED_UNICODE) ?>;
// Admin Status from PHP Session
const IS_ADMIN = <?= (function_exists('is_admin') && is_admin()) ? 'true' : 'false' ?>;
</script> </script>
<!-- Application Logic --> <!-- Application Logic -->

View File

@@ -14,31 +14,37 @@
// ===================================================================== // =====================================================================
// API Endpoint as relative Path // API Endpoint as relative Path
var API_URL = 'api/contributions.php'; const API_URL = 'api/contributions.php';
// Current User Name, set via Login Modal, stored in sessionStorage // Username set via Login Modal stored in sessionStorage
var currentUser = sessionStorage.getItem('webgis_user') || ''; let currentUser = sessionStorage.getItem('webgis_user') || '';
// Browser Identification Number for anonymous User Identification stored as Cookie
let browserId = getBrowserId();
function getBrowserId() {
let id = document.cookie.replace(/(?:(?:^|.*;\s*)webgis_browser_id\s*=\s*([^;]*).*$)|^.*$/, '$1');
if (!id) {
id = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
const r = Math.random() * 16 | 0;
return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
// Cookie Expiration in one Year
document.cookie = 'webgis_browser_id=' + id + ';path=/;max-age=31536000;SameSite=Lax';
}
return id;
}
// Category Definitions with Labels, Icons, and Colors
var CATEGORIES = {
mobility: { label: 'Mobilität', icon: '🚲', color: '#1565C0', faIcon: 'fa-bicycle' },
building: { label: 'Bauen', icon: '🏗️', color: '#E65100', faIcon: 'fa-helmet-safety' },
energy: { label: 'Energie', icon: '⚡', color: '#F9A825', faIcon: 'fa-bolt' },
environment: { label: 'Umwelt', icon: '🌳', color: '#2E7D32', faIcon: 'fa-tree' },
industry: { label: 'Industrie', icon: '🏭', color: '#6A1B9A', faIcon: 'fa-industry' },
consumption: { label: 'Konsum', icon: '🛒', color: '#AD1457', faIcon: 'fa-cart-shopping' },
other: { label: 'Sonstiges', icon: '📌', color: '#546E7A', faIcon: 'fa-map-pin' }
};
// Application State // Application State
var map; // Leaflet Map Instance let map; // Leaflet Map Instance
var sidebar; // Sidebar Instance let sidebar; // Sidebar Instance
var contributionsLayer; // GeoJSON Layer holding all Contributions let contributionsLayer; // GeoJSON Layer holding all Contributions
var contributionsData = []; // Raw Contribution Data Array let contributionsData = []; // Raw Contribution Data Array
var activeFilters = Object.keys(CATEGORIES); // Active Category Filters let activeFilters = Object.keys(CATEGORIES); // Active Category Filters
var drawnGeometry = null; // Temporary Storage for Geometry drawn with Geoman let drawnGeometry = null; // Temporary Storage for Geometry drawn with Geoman
var drawnGeomType = null; // Temporary Storage for Geometry Type let drawnGeomType = null; // Temporary Storage for Geometry Type
let userVotes = {}; // Tracks User Votes
// ===================================================================== // =====================================================================
// Block 2: Map Initialization // Block 2: Map Initialization
@@ -63,17 +69,17 @@ map = L.map('map', {
// ===================================================================== // =====================================================================
// Basemap Tile Layers // Basemap Tile Layers
var basemapOSM = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { const basemapOSM = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>', attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
maxZoom: 20 maxZoom: 20
}); });
var basemapCartoDB = L.tileLayer('https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png', { const basemapCartoDB = L.tileLayer('https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png', {
attribution: '© <a href="https://carto.com/">CARTO</a>', attribution: '© <a href="https://carto.com/">Carto</a>',
maxZoom: 20 maxZoom: 20
}); });
var basemapSatellite = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', { const basemapSatellite = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
attribution: '© <a href="https://www.esri.com/">Esri</a>', attribution: '© <a href="https://www.esri.com/">Esri</a>',
maxZoom: 20 maxZoom: 20
}); });
@@ -82,15 +88,15 @@ var basemapSatellite = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/
basemapCartoDB.addTo(map); basemapCartoDB.addTo(map);
// Layer Control // Layer Control
var basemaps = { const basemaps = {
'OpenStreetMap': basemapOSM, '<i class="fa-solid fa-map" style="color:#404040;"></i> Hintergrundkarte (farbe)': basemapOSM,
'CartoDB (hell)': basemapCartoDB, '<i class="fa-solid fa-map" style="color:#404040;"></i> Hintergrundkarte (grau)': basemapCartoDB,
'Satellit (Esri)': basemapSatellite, '<i class="fa-solid fa-satellite" style="color:#404040;"></i> Satellitenbild': basemapSatellite,
}; };
var overlays = {}; // Populated later with Contribution Layers const overlays = {}; // Populated later with Contribution Layers
var layerControl = L.control.layers(basemaps, overlays, { const layerControl = L.control.layers(basemaps, overlays, {
position: 'topright', position: 'topright',
collapsed: true collapsed: true
}).addTo(map); }).addTo(map);
@@ -135,39 +141,39 @@ L.Control.geocoder({
}).addTo(map); }).addTo(map);
// Polyline Measure Tool // Polyline Measure Tool
L.control.polylineMeasure({ // L.control.polylineMeasure({
position: 'topright', // position: 'topright',
unit: 'metres', // unit: 'metres',
showBearings: false, // showBearings: false,
clearMeasurementsOnStop: false, // clearMeasurementsOnStop: false,
showClearControl: true // showClearControl: true
}).addTo(map); // }).addTo(map);
// Mouse Position Display // Mouse Position Display
var MousePositionControl = L.Control.extend({ // const MousePositionControl = L.Control.extend({
options: { position: 'bottomright' }, // options: { position: 'bottomright' },
onAdd: function () { // onAdd: function () {
var container = L.DomUtil.create('div', 'mouse-position-display'); // const container = L.DomUtil.create('div', 'mouse-position-display');
container.innerHTML = 'Lat: , Lng: '; // container.innerHTML = 'Lat: , Lng: ';
map.on('mousemove', function (e) { // map.on('mousemove', function (e) {
container.innerHTML = 'Lat: ' + e.latlng.lat.toFixed(5) + ', Lng: ' + e.latlng.lng.toFixed(5); // container.innerHTML = 'Lat: ' + e.latlng.lat.toFixed(5) + ', Lng: ' + e.latlng.lng.toFixed(5);
}); // });
return container; // return container;
} // }
}); // });
new MousePositionControl().addTo(map); // new MousePositionControl().addTo(map);
// GPS Location Button // GPS Location Button
var GpsControl = L.Control.extend({ const GpsControl = L.Control.extend({
options: { position: 'topright' }, options: { position: 'topright' },
onAdd: function () { onAdd: function () {
var container = L.DomUtil.create('div', 'leaflet-bar leaflet-control'); const container = L.DomUtil.create('div', 'leaflet-bar leaflet-control');
var button = L.DomUtil.create('a', 'gps-control-button', container); const button = L.DomUtil.create('a', 'gps-control-button', container);
button.href = '#'; button.href = '#';
button.title = 'Mein Standort'; button.title = 'Mein Standort';
button.innerHTML = '<i class="fa-solid fa-location-crosshairs"></i>'; button.innerHTML = '<i class="fa-solid fa-location-crosshairs"></i>';
@@ -184,7 +190,7 @@ var GpsControl = L.Control.extend({
new GpsControl().addTo(map); new GpsControl().addTo(map);
// GPS Location Found Handler // GPS Location Found Handler
var gpsMarker = null; let gpsMarker = null;
map.on('locationfound', function (e) { map.on('locationfound', function (e) {
if (gpsMarker) { if (gpsMarker) {
@@ -236,9 +242,11 @@ map.pm.addControls({
rotateMode: false rotateMode: false
}); });
map.pm.setLang('de');
// Captures drawn Geometry and opens the Create Modal // Captures drawn Geometry and opens the Create Modal
map.on('pm:create', function (e) { map.on('pm:create', function (e) {
var geojson = e.layer.toGeoJSON().geometry; const geojson = e.layer.toGeoJSON().geometry;
// Determines drawn Geometry Type and normalizes to simple Types // Determines drawn Geometry Type and normalizes to simple Types
if (e.shape === 'Marker') { if (e.shape === 'Marker') {
@@ -278,8 +286,8 @@ map.on('pm:create', function (e) {
// Generic API Call Function // Generic API Call Function
function apiCall(data, callback) { function apiCall(data, callback) {
var formData = new FormData(); const formData = new FormData();
for (var key in data) { for (const key in data) {
formData.append(key, data[key]); formData.append(key, data[key]);
} }
@@ -299,9 +307,15 @@ function apiCall(data, callback) {
}); });
} }
// Loads all Contributions from API and displays Contributions on Map // Loads all Contributions from API and displays Contributions on Map
function loadContributions() { function loadContributions() {
apiCall({ action: 'read', municipality_id: MUNICIPALITY.id }, function (data) { const readParams = { action: 'read', municipality_id: MUNICIPALITY.id };
// Sends Browser ID for persistent Vote Display
readParams.browser_id = browserId;
apiCall(readParams, function (data) {
if (data.error) { if (data.error) {
console.error('Load Error:', data.error); console.error('Load Error:', data.error);
return; return;
@@ -309,6 +323,14 @@ function loadContributions() {
contributionsData = data.features || []; contributionsData = data.features || [];
// Restores Vote Highlights from API Response
if (data.user_votes) {
userVotes = {};
for (const key in data.user_votes) {
userVotes[key] = data.user_votes[key];
}
}
// Removes existing Layer if present // Removes existing Layer if present
if (contributionsLayer) { if (contributionsLayer) {
map.removeLayer(contributionsLayer); map.removeLayer(contributionsLayer);
@@ -322,8 +344,7 @@ function loadContributions() {
onEachFeature: bindFeaturePopup onEachFeature: bindFeaturePopup
}).addTo(map); }).addTo(map);
layerControl.addOverlay(contributionsLayer, 'Beiträge'); layerControl.addOverlay(contributionsLayer, '<i class="fa-solid fa-map-pin" style="color:#C00000;"></i> Beiträge');
// Update Sidebar List and Statistics // Update Sidebar List and Statistics
updateContributionsList(); updateContributionsList();
updateStatistics(); updateStatistics();
@@ -337,20 +358,21 @@ function loadContributions() {
// Style for Point Features (CircleMarkers) // Style for Point Features (CircleMarkers)
function stylePoint(feature, latlng) { function stylePoint(feature, latlng) {
var cat = CATEGORIES[feature.properties.category] || CATEGORIES.other; const cat = CATEGORIES[feature.properties.category] || CATEGORIES.other;
return L.circleMarker(latlng, { return L.circleMarker(latlng, {
radius: 8, radius: 8,
color: '#ffffff', color: cat.color,
weight: 2, weight: 3,
fillColor: cat.color, fillColor: cat.color,
fillOpacity: 0.9 fillOpacity: 0.25,
opacity: 0.8
}); });
} }
// Style for Line and Polygon Features // Style for Line and Polygon Features
function styleLinePolygon(feature) { function styleLinePolygon(feature) {
var cat = CATEGORIES[feature.properties.category] || CATEGORIES.other; const cat = CATEGORIES[feature.properties.category] || CATEGORIES.other;
return { return {
color: cat.color, color: cat.color,
@@ -366,45 +388,99 @@ function styleLinePolygon(feature) {
// Block 9: Feature Popups for Read, Edit, Delete and Vote // Block 9: Feature Popups for Read, Edit, Delete and Vote
// ===================================================================== // =====================================================================
function bindFeaturePopup(feature, layer) { // Builds Popup HTML for Features called every Time the Popup opens
var props = feature.properties; function buildPopupHtml(feature) {
var cat = CATEGORIES[props.category] || CATEGORIES.other; const props = feature.properties;
const cat = CATEGORIES[props.category] || CATEGORIES.other;
// Formats Date // Formats Date
var date = new Date(props.created_at); const date = new Date(props.created_at);
var dateStr = date.toLocaleDateString('de-DE', { const dateStr = date.toLocaleDateString('de-DE', {
day: '2-digit', month: '2-digit', year: 'numeric' day: '2-digit', month: '2-digit', year: 'numeric'
}); });
// Builds Popup on Click let html = '' +
var html = '' +
'<div class="popup-detail">' + '<div class="popup-detail">' +
'<span class="popup-detail-category">' + cat.icon + ' ' + cat.label + '</span>' + '<span class="popup-detail-category">' + categoryIcon(cat) + ' ' + cat.label + '</span>' +
'<div class="popup-detail-title">' + escapeHtml(props.title) + '</div>' + '<div class="popup-detail-title">' + escapeHtml(props.title) + '</div>' +
(props.description ? '<div class="popup-detail-description">' + escapeHtml(props.description) + '</div>' : '') + (props.description ? '<div class="popup-detail-description">' + escapeHtml(props.description) + '</div>' : '');
'<div class="popup-detail-meta">' +
// Photo Toggle Button including hidden Photo
if (props.photo_path) {
html += '<div class="popup-photo-container" id="photo-container-' + props.contribution_id + '" style="display:none;">' +
'<img src="' + escapeHtml(props.photo_path) + '" alt="Foto" class="popup-photo-img" onclick="window.open(\'' + escapeHtml(props.photo_path) + '\', \'_blank\')">' +
'</div>' +
'<div class="popup-photo-toggle">' +
'<button class="popup-photo-btn" onclick="togglePhoto(' + props.contribution_id + ')">' +
'<i class="fa-solid fa-camera"></i> <span id="photo-label-' + props.contribution_id + '">Foto anzeigen</span>' +
'</button>' +
'</div>';
}
// Meta Information
html += '<div class="popup-detail-meta">' +
'<i class="fa-solid fa-user"></i> ' + escapeHtml(props.author_name) + '<i class="fa-solid fa-user"></i> ' + escapeHtml(props.author_name) +
' &middot; <i class="fa-solid fa-calendar"></i> ' + dateStr + ' &middot; <i class="fa-solid fa-calendar"></i> ' + dateStr +
'</div>' +
'<div class="popup-detail-votes">' +
'<button class="popup-vote-btn" onclick="voteContribution(' + props.contribution_id + ', \'like\')" title="Gefällt mir">' +
'<i class="fa-solid fa-thumbs-up"></i> <span id="likes-' + props.contribution_id + '">' + props.likes_count + '</span>' +
'</button>' +
'<button class="popup-vote-btn" onclick="voteContribution(' + props.contribution_id + ', \'dislike\')" title="Gefällt mir nicht">' +
'<i class="fa-solid fa-thumbs-down"></i> <span id="dislikes-' + props.contribution_id + '">' + props.dislikes_count + '</span>' +
'</button>' +
'</div>' +
(currentUser === props.author_name ?
'<div class="popup-detail-actions">' +
'<button class="btn btn-primary" onclick="editContribution(' + props.contribution_id + ')"><i class="fa-solid fa-pen"></i> Bearbeiten</button>' +
'<button class="btn btn-danger" onclick="deleteContribution(' + props.contribution_id + ')"><i class="fa-solid fa-trash"></i> Löschen</button>' +
'</div>' : '') +
'</div>'; '</div>';
layer.bindPopup(html, { maxWidth: 320, minWidth: 240 }); // Vote Buttons
html += '<div class="popup-detail-votes">' +
'<button class="popup-vote-btn' + (userVotes[props.contribution_id] === 'like' ? ' liked' : '') + '" id="vote-like-' + props.contribution_id + '" onclick="voteContribution(' + props.contribution_id + ', \'like\')" title="Gefällt mir">' +
'<i class="fa-solid fa-thumbs-up"></i> <span id="likes-' + props.contribution_id + '">' + props.likes_count + '</span>' +
'</button>' +
'<button class="popup-vote-btn' + (userVotes[props.contribution_id] === 'dislike' ? ' disliked' : '') + '" id="vote-dislike-' + props.contribution_id + '" onclick="voteContribution(' + props.contribution_id + ', \'dislike\')" title="Gefällt mir nicht">' +
'<i class="fa-solid fa-thumbs-down"></i> <span id="dislikes-' + props.contribution_id + '">' + props.dislikes_count + '</span>' +
'</button>' +
'</div>';
// Builds Tooltip on Hover // Edit and Delete Buttons for Author or Admin
layer.bindTooltip(cat.icon + ' ' + escapeHtml(props.title), { if (props.browser_id === browserId || (typeof IS_ADMIN !== 'undefined' && IS_ADMIN)) {
html += '<div class="popup-detail-actions">' +
'<button class="btn btn-primary" onclick="editContribution(' + props.contribution_id + ')"><i class="fa-solid fa-pen"></i> Bearbeiten</button>' +
'<button class="btn btn-danger" onclick="deleteContribution(' + props.contribution_id + ')"><i class="fa-solid fa-trash"></i> Löschen</button>' +
'</div>';
}
// Collapsible Comments Section
const commentCount = props.comment_count || 0;
html += '<div class="popup-comments">' +
'<div class="popup-comments-header" onclick="toggleComments(' + props.contribution_id + ')">' +
'<i class="fa-solid fa-comments"></i> Kommentare (' + commentCount + ')' +
' <i class="fa-solid fa-chevron-down popup-comments-toggle" id="comments-toggle-' + props.contribution_id + '"></i>' +
'</div>' +
'<div id="comments-section-' + props.contribution_id + '" style="display:none;">' +
'<div id="comments-list-' + props.contribution_id + '" class="popup-comments-list"></div>';
// Comment Input for logged-in Users
if (currentUser) {
html += '<div class="popup-comment-form">' +
'<input type="text" id="comment-input-' + props.contribution_id + '" class="popup-comment-input" placeholder="Kommentar schreiben..." maxlength="1000">' +
'<button class="popup-comment-submit" onclick="submitComment(' + props.contribution_id + ')" title="Senden">' +
'<i class="fa-solid fa-paper-plane"></i>' +
'</button>' +
'</div>';
}
html += '</div></div></div>';
return html;
}
// Binds Popup and Tooltip to Feature Layer
function bindFeaturePopup(feature, layer) {
const cat = CATEGORIES[feature.properties.category] || CATEGORIES.other;
// Dynamic Popup — rebuilt every Time the Popup opens
layer.bindPopup(function () { return buildPopupHtml(feature); }, { maxWidth: 320, minWidth: 240 });
// Loads Comments when Popup opens
layer.on('popupopen', function () {
loadComments(feature.properties.contribution_id);
});
// Tooltip on Hover
layer.bindTooltip(categoryIcon(cat) + ' ' + escapeHtml(feature.properties.title), {
direction: 'top', direction: 'top',
offset: [0, -10] offset: [0, -10]
}); });
@@ -417,13 +493,14 @@ function bindFeaturePopup(feature, layer) {
// CREATE: Submits new Contributions from Modal // CREATE: Submits new Contributions from Modal
function submitCreate() { function submitCreate() {
var category = document.getElementById('create-category').value; const category = document.getElementById('create-category').value;
var title = document.getElementById('create-title').value.trim(); const title = document.getElementById('create-title').value.trim();
var description = document.getElementById('create-description').value.trim(); const description = document.getElementById('create-description').value.trim();
var geom = document.getElementById('create-geom').value; const geom = document.getElementById('create-geom').value;
var geomType = document.getElementById('create-geom-type').value; const geomType = document.getElementById('create-geom-type').value;
const photoInput = document.getElementById('create-photo');
// Validates // Validates required Fields
if (!category) { if (!category) {
Swal.fire('Kategorie fehlt', 'Bitte wählen Sie eine Kategorie aus.', 'warning'); Swal.fire('Kategorie fehlt', 'Bitte wählen Sie eine Kategorie aus.', 'warning');
return; return;
@@ -437,24 +514,47 @@ function submitCreate() {
return; return;
} }
apiCall({ // Builds FormData manually to include Photo File
action: 'create', const formData = new FormData();
municipality_id: MUNICIPALITY.id, formData.append('action', 'create');
category: category, formData.append('municipality_id', MUNICIPALITY.id);
title: title, formData.append('category', category);
description: description, formData.append('title', title);
geom: geom, formData.append('description', description);
geom_type: geomType, formData.append('geom', geom);
author_name: currentUser formData.append('geom_type', geomType);
}, function (response) { formData.append('author_name', currentUser);
formData.append('browser_id', browserId);
// Appends Photo File if selected
if (photoInput.files.length > 0) {
formData.append('photo', photoInput.files[0]);
}
// Sends directly via fetch not through apiCall, because of File Upload
fetch(API_URL, { method: 'POST', body: formData })
.then(function (response) { return response.json(); })
.then(function (response) {
if (response.error) { if (response.error) {
Swal.fire('Fehler', response.error, 'error'); Swal.fire('Fehler', response.error, 'error');
return; return;
} }
// Triggers Reverse Geocoding in Background
if (response.contribution_id && drawnGeometry) {
const coords = drawnGeomType === 'point' ? drawnGeometry.coordinates :
drawnGeomType === 'line' ? drawnGeometry.coordinates[0] :
drawnGeometry.coordinates[0][0];
reverseGeocode(response.contribution_id, coords[1], coords[0]);
}
Swal.fire('Eingereicht!', 'Ihr Beitrag wurde erfolgreich eingereicht und wird nach Prüfung durch das Moderationsteam veröffentlicht.', 'success'); Swal.fire('Eingereicht!', 'Ihr Beitrag wurde erfolgreich eingereicht und wird nach Prüfung durch das Moderationsteam veröffentlicht.', 'success');
closeCreateModal(); closeCreateModal();
loadContributions(); loadContributions();
})
.catch(function (error) {
console.error('Upload Error:', error);
Swal.fire('Verbindungsfehler', 'Verbindung zum Server fehlgeschlagen.', 'error');
}); });
} }
@@ -470,6 +570,9 @@ function closeCreateModal() {
document.getElementById('create-description').value = ''; document.getElementById('create-description').value = '';
document.getElementById('create-geom').value = ''; document.getElementById('create-geom').value = '';
document.getElementById('create-geom-type').value = ''; document.getElementById('create-geom-type').value = '';
// Resets Photo Upload
document.getElementById('create-photo').value = '';
document.getElementById('photo-preview').style.display = 'none';
drawnGeometry = null; drawnGeometry = null;
drawnGeomType = null; drawnGeomType = null;
} }
@@ -477,22 +580,26 @@ function closeCreateModal() {
// UPDATE: Edits existing Contributions // UPDATE: Edits existing Contributions
function editContribution(contributionId) { function editContribution(contributionId) {
// Finds Contribution in local Data // Finds Contribution in local Data
var contribution = contributionsData.find(function (f) { const contribution = contributionsData.find(function (f) {
return f.properties.contribution_id === contributionId; return f.properties.contribution_id === contributionId;
}); });
if (!contribution) return; if (!contribution) return;
var props = contribution.properties; const props = contribution.properties;
Swal.fire({ Swal.fire({
title: 'Beitrag bearbeiten', title: 'Beitrag bearbeiten',
html: html:
'<div style="text-align:left;">' + '<div style="text-align:left;">' +
'<label style="font-weight:600;font-size:0.85rem;">Titel</label>' + '<div style="margin-bottom:12px;">' +
'<input id="swal-title" class="swal2-input" value="' + escapeHtml(props.title) + '">' + '<label style="display:block;font-weight:600;font-size:1.15rem;margin-bottom:4px;">Titel</label>' +
'<label style="font-weight:600;font-size:0.85rem;">Beschreibung</label>' + '<input id="swal-title" class="swal2-input" style="margin:0;width:100%;" value="' + escapeHtml(props.title) + '">' +
'<textarea id="swal-description" class="swal2-textarea">' + escapeHtml(props.description || '') + '</textarea>' + '</div>' +
'<div>' +
'<label style="display:block;font-weight:600;font-size:1.15rem;margin-bottom:4px;">Beschreibung</label>' +
'<textarea id="swal-description" class="swal2-textarea" style="margin:0;width:100%;">' + escapeHtml(props.description || '') + '</textarea>' +
'</div>' +
'</div>', '</div>',
showCancelButton: true, showCancelButton: true,
confirmButtonText: 'Speichern', confirmButtonText: 'Speichern',
@@ -554,7 +661,6 @@ function deleteContribution(contributionId) {
// VOTE: Like or Dislike existing Contributions // VOTE: Like or Dislike existing Contributions
function voteContribution(contributionId, voteType) { function voteContribution(contributionId, voteType) {
if (!currentUser) { if (!currentUser) {
Swal.fire('Bitte anmelden', 'Sie sollten sich anmelden, um abzustimmen.', 'info');
showLoginModal(); showLoginModal();
return; return;
} }
@@ -563,15 +669,68 @@ function voteContribution(contributionId, voteType) {
action: 'vote', action: 'vote',
contribution_id: contributionId, contribution_id: contributionId,
voter_name: currentUser, voter_name: currentUser,
vote_type: voteType vote_type: voteType,
browser_id: browserId
}, function (response) { }, function (response) {
if (response.error) { if (response.error) {
Swal.fire('Hinweis', response.error, 'info');
return; return;
} }
// Updates Vote Counts in the Popup without reloading everything // Updates local Vote State
loadContributions(); const likeBtn = document.getElementById('vote-like-' + contributionId);
const dislikeBtn = document.getElementById('vote-dislike-' + contributionId);
const likesSpan = document.getElementById('likes-' + contributionId);
const dislikesSpan = document.getElementById('dislikes-' + contributionId);
// Finds Feature in Contributions to update Properties
const feature = contributionsData.find(function (f) {
return f.properties.contribution_id === contributionId;
});
if (response.action === 'created') {
userVotes[contributionId] = voteType;
if (voteType === 'like') {
likeBtn.classList.add('liked');
likesSpan.textContent = parseInt(likesSpan.textContent) + 1;
if (feature) feature.properties.likes_count++;
} else {
dislikeBtn.classList.add('disliked');
dislikesSpan.textContent = parseInt(dislikesSpan.textContent) + 1;
if (feature) feature.properties.dislikes_count++;
}
} else if (response.action === 'removed') {
delete userVotes[contributionId];
if (voteType === 'like') {
likeBtn.classList.remove('liked');
likesSpan.textContent = Math.max(0, parseInt(likesSpan.textContent) - 1);
if (feature) feature.properties.likes_count = Math.max(0, feature.properties.likes_count - 1);
} else {
dislikeBtn.classList.remove('disliked');
dislikesSpan.textContent = Math.max(0, parseInt(dislikesSpan.textContent) - 1);
if (feature) feature.properties.dislikes_count = Math.max(0, feature.properties.dislikes_count - 1);
}
} else if (response.action === 'changed') {
userVotes[contributionId] = voteType;
if (voteType === 'like') {
likeBtn.classList.add('liked');
dislikeBtn.classList.remove('disliked');
likesSpan.textContent = parseInt(likesSpan.textContent) + 1;
dislikesSpan.textContent = Math.max(0, parseInt(dislikesSpan.textContent) - 1);
if (feature) {
feature.properties.likes_count++;
feature.properties.dislikes_count = Math.max(0, feature.properties.dislikes_count - 1);
}
} else {
dislikeBtn.classList.add('disliked');
likeBtn.classList.remove('liked');
dislikesSpan.textContent = parseInt(dislikesSpan.textContent) + 1;
likesSpan.textContent = Math.max(0, parseInt(likesSpan.textContent) - 1);
if (feature) {
feature.properties.dislikes_count++;
feature.properties.likes_count = Math.max(0, feature.properties.likes_count - 1);
}
}
}
}); });
} }
@@ -581,16 +740,16 @@ function voteContribution(contributionId, voteType) {
// ===================================================================== // =====================================================================
function updateContributionsList() { function updateContributionsList() {
var container = document.getElementById('contributions-list'); const container = document.getElementById('contributions-list');
var searchInput = document.getElementById('list-search-input'); const searchInput = document.getElementById('list-search-input');
var searchTerm = searchInput ? searchInput.value.toLowerCase() : ''; const searchTerm = searchInput ? searchInput.value.toLowerCase() : '';
// Filters by Categories and Search Term // Filters by Categories and Search Term
var filtered = contributionsData.filter(function (f) { const filtered = contributionsData.filter(function (f) {
var props = f.properties; const props = f.properties;
var matchesCategory = activeFilters.indexOf(props.category) !== -1; const matchesCategory = activeFilters.indexOf(props.category) !== -1;
var cat = CATEGORIES[props.category] || CATEGORIES.other; const cat = CATEGORIES[props.category] || CATEGORIES.other;
var matchesSearch = !searchTerm || const matchesSearch = !searchTerm ||
props.title.toLowerCase().indexOf(searchTerm) !== -1 || props.title.toLowerCase().indexOf(searchTerm) !== -1 ||
(props.description && props.description.toLowerCase().indexOf(searchTerm) !== -1) || (props.description && props.description.toLowerCase().indexOf(searchTerm) !== -1) ||
props.author_name.toLowerCase().indexOf(searchTerm) !== -1 || props.author_name.toLowerCase().indexOf(searchTerm) !== -1 ||
@@ -609,16 +768,16 @@ function updateContributionsList() {
return; return;
} }
var html = ''; let html = '';
filtered.forEach(function (f) { filtered.forEach(function (f) {
var props = f.properties; const props = f.properties;
var cat = CATEGORIES[props.category] || CATEGORIES.other; const cat = CATEGORIES[props.category] || CATEGORIES.other;
var date = new Date(props.created_at).toLocaleDateString('de-DE'); const date = new Date(props.created_at).toLocaleDateString('de-DE');
html += '' + html += '' +
'<div class="contribution-card" onclick="flyToContribution(' + props.contribution_id + ')">' + '<div class="contribution-card" onclick="flyToContribution(' + props.contribution_id + ')">' +
'<div class="contribution-card-header">' + '<div class="contribution-card-header">' +
'<span class="contribution-card-category">' + cat.icon + ' ' + cat.label + '</span>' + '<span class="contribution-card-category">' + categoryIcon(cat) + ' ' + cat.label + '</span>' +
'</div>' + '</div>' +
'<div class="contribution-card-title">' + escapeHtml(props.title) + '</div>' + '<div class="contribution-card-title">' + escapeHtml(props.title) + '</div>' +
'<div class="contribution-card-meta">' + '<div class="contribution-card-meta">' +
@@ -626,6 +785,7 @@ function updateContributionsList() {
'<span class="contribution-card-votes">' + '<span class="contribution-card-votes">' +
'<span title="Likes"><i class="fa-solid fa-thumbs-up"></i> ' + props.likes_count + '</span>' + '<span title="Likes"><i class="fa-solid fa-thumbs-up"></i> ' + props.likes_count + '</span>' +
'<span title="Dislikes"><i class="fa-solid fa-thumbs-down"></i> ' + props.dislikes_count + '</span>' + '<span title="Dislikes"><i class="fa-solid fa-thumbs-down"></i> ' + props.dislikes_count + '</span>' +
'<span title="Kommentare"><i class="fa-solid fa-comment"></i> ' + (props.comment_count || 0) + '</span>' +
'</span>' + '</span>' +
'</div>' + '</div>' +
'</div>'; '</div>';
@@ -670,18 +830,17 @@ document.getElementById('list-search-input').addEventListener('input', function
// Builds Category Filter Checkboxes // Builds Category Filter Checkboxes
function buildCategoryFilter() { function buildCategoryFilter() {
var container = document.getElementById('category-filter'); const container = document.getElementById('category-filter');
var html = ''; let html = '';
for (var key in CATEGORIES) { for (const key in CATEGORIES) {
var cat = CATEGORIES[key]; const cat = CATEGORIES[key];
var checked = activeFilters.indexOf(key) !== -1 ? 'checked' : ''; const checked = activeFilters.indexOf(key) !== -1 ? 'checked' : '';
html += '' + html += '' +
'<label style="display:flex;align-items:center;gap:8px;margin-bottom:6px;cursor:pointer;">' + '<label style="display:flex;align-items:center;gap:8px;margin-bottom:6px;cursor:pointer;">' +
'<input type="checkbox" value="' + key + '" ' + checked + ' onchange="toggleCategoryFilter(this)">' + '<input type="checkbox" value="' + key + '" ' + checked + ' onchange="toggleCategoryFilter(this)">' +
'<span style="display:inline-block;width:12px;height:12px;border-radius:50%;background:' + cat.color + ';"></span>' + '<span>' + categoryIcon(cat) + ' ' + cat.label + '</span>' +
'<span>' + cat.icon + ' ' + cat.label + '</span>' +
'</label>'; '</label>';
} }
@@ -690,7 +849,7 @@ function buildCategoryFilter() {
// Toggles a Category Filter on or off // Toggles a Category Filter on or off
function toggleCategoryFilter(checkbox) { function toggleCategoryFilter(checkbox) {
var category = checkbox.value; const category = checkbox.value;
if (checkbox.checked) { if (checkbox.checked) {
if (activeFilters.indexOf(category) === -1) { if (activeFilters.indexOf(category) === -1) {
@@ -704,9 +863,16 @@ function toggleCategoryFilter(checkbox) {
if (contributionsLayer) { if (contributionsLayer) {
contributionsLayer.eachLayer(function (layer) { contributionsLayer.eachLayer(function (layer) {
if (layer.feature) { if (layer.feature) {
var cat = layer.feature.properties.category; const cat = layer.feature.properties.category;
if (activeFilters.indexOf(cat) !== -1) { if (activeFilters.indexOf(cat) !== -1) {
layer.setStyle({ opacity: 1, fillOpacity: layer.feature.geometry.type === 'Point' ? 0.9 : 0.25 }); const catDef = CATEGORIES[cat] || CATEGORIES.other;
layer.setStyle({
color: catDef.color,
weight: 3,
opacity: 0.8,
fillColor: catDef.color,
fillOpacity: 0.25
});
if (layer.setRadius) layer.setRadius(8); if (layer.setRadius) layer.setRadius(8);
layer.options.interactive = true; layer.options.interactive = true;
} else { } else {
@@ -726,24 +892,24 @@ function toggleCategoryFilter(checkbox) {
// Updates Statistics in Home Tab // Updates Statistics in Home Tab
function updateStatistics() { function updateStatistics() {
var container = document.getElementById('stats-container'); const container = document.getElementById('stats-container');
var total = contributionsData.length; const total = contributionsData.length;
// Counts per Category // Counts per Category
var counts = {}; const counts = {};
contributionsData.forEach(function (f) { contributionsData.forEach(function (f) {
var cat = f.properties.category; const cat = f.properties.category;
counts[cat] = (counts[cat] || 0) + 1; counts[cat] = (counts[cat] || 0) + 1;
}); });
var html = '<p style="font-size:0.9rem;"><strong>' + total + '</strong> Beiträge insgesamt</p>'; let html = '<p style="font-size:0.9rem;"><strong>' + total + '</strong> Beiträge insgesamt</p>';
for (var key in CATEGORIES) { for (const key in CATEGORIES) {
var cat = CATEGORIES[key]; const cat = CATEGORIES[key];
var count = counts[key] || 0; const count = counts[key] || 0;
if (count > 0) { if (count > 0) {
html += '<div style="display:flex;align-items:center;gap:8px;margin:4px 0;font-size:0.85rem;">' + html += '<div style="display:flex;align-items:center;gap:8px;margin:4px 0;font-size:0.85rem;">' +
'<span style="display:inline-block;width:10px;height:10px;border-radius:50%;background:' + cat.color + ';"></span>' + categoryIcon(cat) + ' ' +
cat.label + ': ' + count + cat.label + ': ' + count +
'</div>'; '</div>';
} }
@@ -759,7 +925,7 @@ function updateStatistics() {
// Welcome Modal shows on new Visits // Welcome Modal shows on new Visits
function checkWelcomeModal() { function checkWelcomeModal() {
var hasVisited = localStorage.getItem('webgis_welcomed'); const hasVisited = localStorage.getItem('webgis_welcomed');
if (!hasVisited) { if (!hasVisited) {
document.getElementById('welcome-modal').style.display = 'flex'; document.getElementById('welcome-modal').style.display = 'flex';
} }
@@ -779,7 +945,7 @@ function showLoginModal() {
} }
function submitLogin() { function submitLogin() {
var name = document.getElementById('user-name-input').value.trim(); const name = document.getElementById('user-name-input').value.trim();
if (!name) { if (!name) {
Swal.fire('Name eingeben', 'Bitte geben Sie Ihren Namen ein.', 'warning'); Swal.fire('Name eingeben', 'Bitte geben Sie Ihren Namen ein.', 'warning');
return; return;
@@ -813,44 +979,20 @@ function showInfoModal() {
}); });
} }
// Privacy Modal
function showPrivacyModal() {
Swal.fire({
title: 'Datenschutz',
html: '<p style="text-align:left;line-height:1.6;">Das Bürgerbeteiligungsportal speichert die von Ihnen ' +
'hinterlegten Daten zur Durchführung der Bürgerbeteiligung.</p>' +
'<p style="text-align:left;line-height:1.6;">Ihre Daten werden nicht an Dritte weitergegeben. ' +
'Details entnehmen Sie bitte der vollständigen Datenschutzerklärung von ' +
MUNICIPALITY.name + '.</p>',
confirmButtonColor: MUNICIPALITY.primaryColor
});
}
// Imprint Modal
function showImprintModal() {
Swal.fire({
title: 'Impressum',
html: '<p style="text-align:left;line-height:1.6;">Stadt ' + MUNICIPALITY.name + '</p>' +
'<p style="text-align:left;line-height:1.6;color:#777;">Die vollständigen Angaben ' +
'werden hier hinzugefügt, sobald das Portal in den Produktivbetrieb geht.</p>',
confirmButtonColor: MUNICIPALITY.primaryColor
});
}
// ===================================================================== // =====================================================================
// Block 14: Mobile Navigation // Block 14: Mobile Navigation
// ===================================================================== // =====================================================================
function toggleMobileNav() { function toggleMobileNav() {
var nav = document.querySelector('.header-nav'); const nav = document.querySelector('.header-nav');
nav.classList.toggle('open'); nav.classList.toggle('open');
} }
// Closes Mobile Nav when clicking outside // Closes Mobile Nav when clicking outside
document.addEventListener('click', function (e) { document.addEventListener('click', function (e) {
var nav = document.querySelector('.header-nav'); const nav = document.querySelector('.header-nav');
var toggle = document.querySelector('.header-menu-toggle'); const toggle = document.querySelector('.header-menu-toggle');
if (nav.classList.contains('open') && !nav.contains(e.target) && !toggle.contains(e.target)) { if (nav.classList.contains('open') && !nav.contains(e.target) && !toggle.contains(e.target)) {
nav.classList.remove('open'); nav.classList.remove('open');
@@ -874,11 +1016,176 @@ document.addEventListener('keydown', function (e) {
// Escapes HTML to prevent Cross-Site Scripting (XSS) in Popups and Lists // Escapes HTML to prevent Cross-Site Scripting (XSS) in Popups and Lists
function escapeHtml(text) { function escapeHtml(text) {
if (!text) return ''; if (!text) return '';
var div = document.createElement('div'); const div = document.createElement('div');
div.appendChild(document.createTextNode(text)); div.appendChild(document.createTextNode(text));
return div.innerHTML; return div.innerHTML;
} }
// Returns a colored Font Awesome Icon HTML String for a Category
function categoryIcon(cat) {
return '<i class="fa-solid ' + cat.faIcon + '" style="color:' + cat.color + ';"></i>';
}
// Reverse Geocodes Coordinates and saves Address to Contribution via API
function reverseGeocode(contributionId, lat, lng) {
fetch('https://nominatim.openstreetmap.org/reverse?format=json&lat=' + lat + '&lon=' + lng + '&zoom=18&addressdetails=1', {
headers: { 'Accept-Language': 'de' }
})
.then(function (r) { return r.json(); })
.then(function (data) {
if (data.display_name) {
const addr = data.address || {};
const parts = [];
if (addr.road) parts.push(addr.road + (addr.house_number ? ' ' + addr.house_number : ''));
if (addr.city || addr.town || addr.village) parts.push(addr.city || addr.town || addr.village);
const shortAddress = parts.length > 0 ? parts.join(', ') : data.display_name.split(',').slice(0, 2).join(',');
// Saves Address to Database via API
apiCall({
action: 'update',
contribution_id: contributionId,
address: shortAddress
}, function () {});
}
})
.catch(function () {});
}
// Filters News Items in Sidebar by Search Term
function filterNews() {
const searchTerm = document.getElementById('news-search-input').value.toLowerCase();
const newsItems = document.querySelectorAll('#news-list .news-item');
newsItems.forEach(function (item) {
const title = item.dataset.title || '';
const content = item.dataset.content || '';
const author = item.dataset.author || '';
// Shows Item if Search Term matches Title, Content or Author
if (!searchTerm || title.indexOf(searchTerm) !== -1 || content.indexOf(searchTerm) !== -1 || author.indexOf(searchTerm) !== -1) {
item.style.display = '';
} else {
item.style.display = 'none';
}
});
}
// Loads and Displays Comments forContributions in Popups
function loadComments(contributionId) {
apiCall({
action: 'read_comments',
contribution_id: contributionId
}, function (response) {
const listContainer = document.getElementById('comments-list-' + contributionId);
const countSpan = document.getElementById('comment-count-' + contributionId);
if (!listContainer) return;
if (response.error || !response.comments || response.comments.length === 0) {
listContainer.innerHTML = '<div class="popup-comment-empty">Noch keine Kommentare.</div>';
if (countSpan) countSpan.textContent = '(0)';
return;
}
if (countSpan) countSpan.textContent = '(' + response.count + ')';
let html = '';
response.comments.forEach(function (comment) {
const commentDate = new Date(comment.created_at).toLocaleDateString('de-DE');
const canDelete = comment.browser_id === browserId || (typeof IS_ADMIN !== 'undefined' && IS_ADMIN);
html += '<div class="popup-comment">' +
'<div class="popup-comment-meta">' +
'<strong>' + escapeHtml(comment.author_name) + '</strong>' +
' · ' + commentDate +
(canDelete ? ' · <a href="#" onclick="deleteComment(' + comment.comment_id + ', ' + contributionId + ');return false;" class="popup-comment-delete"><i class="fa-solid fa-trash"></i></a>' : '') +
'</div>' +
'<div class="popup-comment-text">' + escapeHtml(comment.content) + '</div>' +
'</div>';
});
listContainer.innerHTML = html;
const count = response.comments.length;
const header = document.querySelector('#comments-toggle-' + contributionId)?.closest('.popup-comments-header');
if (header) {
header.innerHTML = '<i class="fa-solid fa-comments"></i> Kommentare (' + count + ')' +
' <i class="fa-solid fa-chevron-down popup-comments-toggle" id="comments-toggle-' + contributionId + '"></i>';
}
});
}
// Submits a new Comment on a Contribution
function submitComment(contributionId) {
const input = document.getElementById('comment-input-' + contributionId);
const content = input ? input.value.trim() : '';
if (!content) return;
apiCall({
action: 'create_comment',
contribution_id: contributionId,
author_name: currentUser,
browser_id: browserId,
content: content
}, function (response) {
if (response.error) {
Swal.fire('Fehler', response.error, 'error');
return;
}
// Clears Input and reloads Comments
if (input) input.value = '';
loadComments(contributionId);
});
}
// Deletes a Comment
function deleteComment(commentId, contributionId) {
apiCall({
action: 'delete_comment',
comment_id: commentId
}, function (response) {
if (response.error) return;
// Reloads Comments after Deletion
loadComments(contributionId);
});
}
// Toggles Photo Visibility in Popup
function togglePhoto(contributionId) {
const container = document.getElementById('photo-container-' + contributionId);
const label = document.getElementById('photo-label-' + contributionId);
if (!container) return;
if (container.style.display === 'none') {
container.style.display = 'block';
label.textContent = 'Foto verbergen';
} else {
container.style.display = 'none';
label.textContent = 'Foto anzeigen';
}
}
// Toggles Comments Section Visibility in Popup
function toggleComments(contributionId) {
const section = document.getElementById('comments-section-' + contributionId);
const toggle = document.getElementById('comments-toggle-' + contributionId);
if (!section) return;
if (section.style.display === 'none') {
section.style.display = 'block';
toggle.classList.remove('fa-chevron-down');
toggle.classList.add('fa-chevron-up');
// Loads Comments
loadComments(contributionId);
} else {
section.style.display = 'none';
toggle.classList.remove('fa-chevron-up');
toggle.classList.add('fa-chevron-down');
}
}
// ===================================================================== // =====================================================================
// Block 16: Application Startup // Block 16: Application Startup
@@ -886,16 +1193,18 @@ function escapeHtml(text) {
// Populates Category Dropdown in Create Modal from Categories Object // Populates Category Dropdown in Create Modal from Categories Object
function buildCategoryDropdown() { function buildCategoryDropdown() {
var select = document.getElementById('create-category'); const select = document.getElementById('create-category');
for (var key in CATEGORIES) { for (const key in CATEGORIES) {
var cat = CATEGORIES[key]; const cat = CATEGORIES[key];
var option = document.createElement('option'); const option = document.createElement('option');
option.value = key; option.value = key;
option.textContent = cat.icon + ' ' + cat.label; option.textContent = cat.label;
option.dataset.icon = cat.faIcon;
select.appendChild(option); select.appendChild(option);
} }
} }
// Populates Category Dropdown // Populates Category Dropdown
buildCategoryDropdown(); buildCategoryDropdown();
@@ -907,3 +1216,21 @@ loadContributions();
// Shows Welcome Modal on first Visit // Shows Welcome Modal on first Visit
checkWelcomeModal(); checkWelcomeModal();
// Photo Preview in Create Modal
document.getElementById('create-photo').addEventListener('change', function () {
const preview = document.getElementById('photo-preview');
const previewImg = document.getElementById('photo-preview-img');
if (this.files && this.files[0]) {
const reader = new FileReader();
reader.onload = function (e) {
previewImg.src = e.target.result;
preview.style.display = 'block';
};
reader.readAsDataURL(this.files[0]);
} else {
preview.style.display = 'none';
}
});

39
public/privacy.php Normal file
View File

@@ -0,0 +1,39 @@
<?php
require_once __DIR__ . '/api/db.php';
$pdo = get_db();
$stmt = $pdo->prepare("SELECT * FROM municipalities WHERE slug = :slug");
$stmt->execute([':slug' => getenv('MUNICIPALITY_SLUG')]);
$municipality = $stmt->fetch();
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Datenschutz — <?= htmlspecialchars($municipality['name']) ?></title>
<link rel="icon" href="<?= htmlspecialchars($municipality['logo_path'] ?? 'assets/icon-municipality.png') ?>" type="image/png">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<link rel="stylesheet" href="styles.css">
<style>:root { --color-primary: <?= htmlspecialchars($municipality['primary_color']) ?>; }</style>
</head>
<body>
<div class="page-header">
<div class="page-header-inner">
<h1><i class="fa-solid fa-lock"></i> Datenschutz</h1>
<div class="page-header-nav">
<a href="index.php"><i class="fa-solid fa-arrow-left"></i> Zurück zur Karte</a>
</div>
</div>
</div>
<div class="page-container">
<div class="page-content-box">
<div class="dev-notice">
<i class="fa-solid fa-triangle-exclamation"></i>
Dieses Portal befindet sich in der Entwicklung und wurde nicht offiziell beauftragt. Die Datenschutzerklärung wird mit der offiziellen Inbetriebnahme hier hinzugefügt.
</div>
<h2>Datenschutz</h2>
<p>Die Datenschutzerklärung wird hier hinzugefügt, sobald das Portal in den Produktivbetrieb geht.</p>
</div>
</div>
</body>
</html>

File diff suppressed because it is too large Load Diff

7
public/uploads/.htaccess Normal file
View File

@@ -0,0 +1,7 @@
# Prevents PHP in Upload Directory
php_flag engine off
# Allows Image Files
<FilesMatch "\.(?i:jpg|jpeg|png|gif|webp)$">
Require all granted
</FilesMatch>

View File