Files
safe-paste/app/controllers/SaveController.php

61 lines
2.2 KiB
PHP

<?php
require_once __DIR__ . '/../core/security.php';
require_once __DIR__ . '/../core/logger.php';
$pdo = require __DIR__ . '/../core/db.php';
require_once __DIR__ . '/../models/Paste.php';
require_once __DIR__ . '/../models/Analytics.php';
$config = require __DIR__ . '/../config/config.php';
$logger = new Logger('save');
$analytics = new Analytics($pdo);
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
$logger->warning('Non-POST request to save endpoint', ['method' => $_SERVER['REQUEST_METHOD']]);
header('Location: /');
exit;
}
$text = trim($_POST['text'] ?? '');
$password = $_POST['password'] ?? '';
$expire = isset($_POST['expire']) ? (int)$_POST['expire'] : 0;
if ($text === '') {
$logger->warning('Empty paste submission attempt');
$analytics->record('paste_validation_failed', null, ['reason' => 'empty_text']);
jsonResponse(['success' => false, 'message' => 'Text cannot be empty.'], 422);
}
$id = generateId();
$enc = encryptText($text, $config['app']['master_key']);
$password_hash = $password !== '' ? password_hash($password, PASSWORD_DEFAULT) : null;
$expire_time = $expire > 0 ? time() + $expire : null;
$paste = new Paste($pdo);
$saved = $paste->save($id, $enc['cipher'], $enc['iv'], $expire_time, $password_hash);
if (!$saved) {
$logger->error('Failed to save paste to storage', ['id' => $id]);
$analytics->record('paste_save_failed', $id);
jsonResponse(['success' => false, 'message' => 'Failed to save paste. Please try again.'], 500);
}
$charCount = mb_strlen($text, 'UTF-8');
$logger->info('Paste created', [
'id' => $id,
'char_count' => $charCount,
'has_password' => $password_hash !== null,
'expires_in' => $expire > 0 ? "{$expire}s" : 'never',
]);
$analytics->record('paste_created', $id, [
'char_count' => $charCount,
'has_password' => $password_hash !== null,
'expire_secs' => $expire > 0 ? $expire : null,
'storage' => $expire_time !== null ? 'redis' : 'mysql',
]);
$base = rtrim($config['app']['base_url'] ?: ('http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . $_SERVER['HTTP_HOST']), '/');
$url = $base . '/view/' . $id;
jsonResponse(['success' => true, 'url' => $url]);