willy.club/routes/willychat.php
2023-01-22 13:17:50 +01:00

91 lines
2.1 KiB
PHP

<?php
use WillySoft\Http\Route;
abstract class WillyChat {
public static string $data_path;
public static array $messages;
}
Route::middleware(function() {
WillyChat::$data_path = '/dev/shm/database.json';
if (!file_exists(WillyChat::$data_path)) {
file_put_contents(
WillyChat::$data_path,
json_encode([])
);
}
WillyChat::$messages = json_decode(
file_get_contents(WillyChat::$data_path),
true
);
});
Route::match('get|post','/willychat/', function() {
$default_nick = 'Willy';
$nick = $default_nick;
$just_sent_message = false;
if (!empty($_POST)) {
$nick = filter_input(INPUT_POST, 'nick');
$text = filter_input(INPUT_POST, 'text');
if (empty(trim($nick, ' '))) {
$nick = $default_nick;
}
if (strlen($nick) > 128) {
view('pages/willychat/error', [
'error' => 'You nickname is too long.'
]);
die();
}
if (strlen($text) > 4096) {
view('pages/willychat/error', [
'error' => 'Do not send extremely long messages.'
]);
die();
}
if (count(WillyChat::$messages) > 10) {
array_pop(WillyChat::$messages);
}
if (!empty(trim($text, ' '))) {
array_unshift(WillyChat::$messages, [
'nick' => $nick,
'date' => time(),
'text' => $text
]);
file_put_contents(WillyChat::$data_path,
json_encode(
WillyChat::$messages
)
);
}
$just_sent_message = true;
}
view('pages/willychat/index', [
'nick' => $nick,
'just_sent_message' => $just_sent_message,
]);
});
Route::get('/willychat/messages', function() {
view('pages/willychat/messages', [
'messages' => WillyChat::$messages
]);
});
Route::get('/willychat/sync', function() {
json_response(
hash('crc32', serialize(WillyChat::$messages))
);
});