aboutsummaryrefslogtreecommitdiffstats
path: root/src/app/Controllers/EditorController.php
blob: c7dd9fcbb795aa5a83764e23ae648f2507cc39da (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
<?php

declare(strict_types=1);
// Editor: webcam/upload image capture, overlay selection, and server-side
// GD compositing to create posts.

namespace App\Controllers;

use App\Csrf;
use App\Flash;
use App\Models\Post;

class EditorController
{
    private Post $post;

    public function __construct()
    {
        $this->post = new Post();
    }

    public function show(): void
    {
        if (!isset($_SESSION['user_id'])) {
            header('Location: /login');
            return;
        }

        $overlaysDir = \dirname(__DIR__, 2) . '/public/assets/overlays';
        $overlayFiles = glob($overlaysDir . '/*.png');
        // Map filesystem paths to URL paths the browser can load
        $overlays = array_map(static fn($path) => '/assets/overlays/' . basename($path), $overlayFiles);

        $userPosts = $this->post->findByUserId($_SESSION['user_id']);

        $content = __DIR__ . '/../Views/editor/index.php';
        include __DIR__ . '/../Views/layouts/main.php';
    }

    public function store(): void
    {
        header('Content-Type: application/json');

        if (!isset($_SESSION['user_id'])) {
            http_response_code(401);
            echo json_encode(['error' => 'Not authenticated.']);
            return;
        }

        $input = json_decode(file_get_contents('php://input'), true);
        if (!$input) {
            http_response_code(400);
            echo json_encode(['error' => 'Invalid request.']);
            return;
        }

        if (!Csrf::validate($input['csrf_token'] ?? '')) {
            http_response_code(403);
            echo json_encode(['error' => 'Invalid CSRF token.']);
            return;
        }

        $imageData = $input['image_data'] ?? '';
        $overlayName = $input['overlay'] ?? '';
        $overlayScale = (float) ($input['overlay_scale'] ?? 1.0);

        // Validate overlay exists — use basename() to prevent path traversal
        $overlaysDir = \dirname(__DIR__, 2) . '/public/assets/overlays';
        $overlayPath = $overlaysDir . '/' . basename($overlayName);
        if (!file_exists($overlayPath) || !str_ends_with($overlayPath, '.png')) {
            http_response_code(400);
            echo json_encode(['error' => 'Invalid overlay.']);
            return;
        }

        $overlayScale = max(0.1, min(2.0, $overlayScale));

        // Strip the data URL prefix (e.g. "data:image/jpeg;base64,") to get raw base64
        $base64 = preg_replace('#^data:image/\w+;base64,#', '', $imageData);
        $decoded = base64_decode($base64, true);
        if ($decoded === false) {
            http_response_code(400);
            echo json_encode(['error' => 'Invalid image data.']);
            return;
        }

        $base = @imagecreatefromstring($decoded);
        if ($base === false) {
            http_response_code(400);
            echo json_encode(['error' => 'Could not process image.']);
            return;
        }

        $outputPath = $this->composite($base, $overlayPath, $overlayScale);


        if ($outputPath === null) {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to save image.']);
            return;
        }

        // Store relative path from the web root so it works as a URL
        $relativePath = 'uploads/posts/' . basename($outputPath);
        $this->post->create($_SESSION['user_id'], $relativePath);

        echo json_encode(['success' => true, 'redirect' => '/editor']);
    }

    public function destroy(string $id): void
    {
        if (!isset($_SESSION['user_id'])) {
            header('Location: /login');
            return;
        }

        if (!Csrf::validate($_POST['csrf_token'] ?? '')) {
            Flash::set('error', 'Invalid CSRF token.');
            header('Location: /editor');
            return;
        }

        $post = $this->post->findById((int) $id);

        // Only the post owner can delete it
        if (!$post || $post['user_id'] !== $_SESSION['user_id']) {
            Flash::set('error', 'Post not found.');
            header('Location: /editor');
            return;
        }

        // Delete the image file from disk
        $filePath = \dirname(__DIR__, 2) . '/' . $post['image_path'];
        if (file_exists($filePath)) {
            unlink($filePath);
        }

        $this->post->delete((int) $id);
        Flash::set('success', 'Post deleted.');
        header('Location: /editor');
    }

    /**
     * Composite the base image with an overlay using GD.
     * Returns the saved file path, or null on failure.
     */
    private function composite(\GdImage $base, string $overlayPath, float $scale): ?string
    {
        $canvasSize = 640;

        // Create a square canvas and fill with white
        $canvas = imagecreatetruecolor($canvasSize, $canvasSize);
        $white = imagecolorallocate($canvas, 255, 255, 255);
        imagefill($canvas, 0, 0, $white);

        // Resize base image to cover the 640x640 canvas (center-crop)
        $srcW = imagesx($base);
        $srcH = imagesy($base);
        // Pick the largest square that fits inside the source image
        $cropSize = min($srcW, $srcH);
        $srcX = (int) (($srcW - $cropSize) / 2);
        $srcY = (int) (($srcH - $cropSize) / 2);
        imagecopyresampled($canvas, $base, 0, 0, $srcX, $srcY, $canvasSize, $canvasSize, $cropSize, $cropSize);

        // Load the overlay PNG with alpha transparency
        $overlay = imagecreatefrompng($overlayPath);
        // Enable alpha blending so transparent overlay pixels don't overwrite the base
        imagealphablending($canvas, true);

        $overlayW = imagesx($overlay);
        $overlayH = imagesy($overlay);
        $scaledW = (int) ($overlayW * $scale);
        $scaledH = (int) ($overlayH * $scale);
        // Center the overlay on the canvas
        $destX = (int) (($canvasSize - $scaledW) / 2);
        $destY = (int) (($canvasSize - $scaledH) / 2);

        imagecopyresampled($canvas, $overlay, $destX, $destY, 0, 0, $scaledW, $scaledH, $overlayW, $overlayH);


        // Save as JPEG
        $uploadsDir = \dirname(__DIR__, 2) . '/uploads/posts';

        $filename = $_SESSION['user_id'] . '_' . time() . '_' . bin2hex(random_bytes(4)) . '.jpg';
        $path = $uploadsDir . '/' . $filename;

        $ok = imagejpeg($canvas, $path, 85);


        return $ok ? $path : null;
    }
}