Files
safe-paste/app/models/Paste.php

59 lines
1.6 KiB
PHP

<?php
require_once __DIR__ . '/../core/redis.php';
class Paste
{
private PDO $pdo;
public function __construct(PDO $pdo)
{
$this->pdo = $pdo;
}
public function save(
string $id,
string $encrypted_text,
string $iv,
?int $expire_time,
?string $password_hash
): bool {
if ($expire_time !== null) {
$ttl = max(1, $expire_time - time());
$redis = redisClient();
$redis->setex("paste:{$id}", $ttl, json_encode([
'encrypted_text' => $encrypted_text,
'iv' => $iv,
'password_hash' => $password_hash,
]));
return true;
}
$stmt = $this->pdo->prepare(
'INSERT INTO pastes (id, encrypted_text, iv, expire_time, password_hash)
VALUES (?, ?, ?, NULL, ?)'
);
return $stmt->execute([$id, $encrypted_text, $iv, $password_hash]);
}
public function get(string $id): array|false
{
$redis = redisClient();
$raw = $redis->get("paste:{$id}");
if ($raw !== false) {
$json = json_decode($raw, true);
return [
'encrypted_text' => $json['encrypted_text'],
'iv' => $json['iv'],
'password_hash' => $json['password_hash'],
'expire_time' => time() + $redis->ttl("paste:{$id}"),
];
}
$stmt = $this->pdo->prepare('SELECT * FROM pastes WHERE id = ? LIMIT 1');
$stmt->execute([$id]);
return $stmt->fetch();
}
}