2023-01-22 09:47:36 +00:00
|
|
|
<?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;
|
2023-01-22 17:18:12 +00:00
|
|
|
$errmsg = false;
|
2023-01-22 09:47:36 +00:00
|
|
|
|
|
|
|
if (!empty($_POST)) {
|
|
|
|
$nick = filter_input(INPUT_POST, 'nick');
|
|
|
|
$text = filter_input(INPUT_POST, 'text');
|
|
|
|
|
2023-01-22 17:18:12 +00:00
|
|
|
$errmsg = (function() use (&$text, &$nick): string|false {
|
2023-01-22 09:47:36 +00:00
|
|
|
|
2023-01-22 17:18:12 +00:00
|
|
|
if (empty(trim($nick, ' '))) {
|
|
|
|
return 'You must choose a nickname.';
|
|
|
|
}
|
2023-01-22 12:17:50 +00:00
|
|
|
|
2023-01-22 17:18:12 +00:00
|
|
|
$nick_max_chars = 128;
|
|
|
|
if (strlen($nick) > $nick_max_chars) {
|
|
|
|
return 'Your nickname is too long.';
|
|
|
|
}
|
2023-01-22 12:17:50 +00:00
|
|
|
|
2023-01-22 17:18:12 +00:00
|
|
|
$text_max_chars = 4096;
|
|
|
|
if (strlen($text) > $text_max_chars) {
|
|
|
|
return 'Your message is too long. ' . strlen($text) . ' out of ' . $text_max_chars . ' characters.';
|
|
|
|
}
|
|
|
|
|
|
|
|
if (empty(trim($text, ' '))) {
|
|
|
|
return 'Message body cannot be empty.';
|
|
|
|
}
|
2023-01-22 09:47:36 +00:00
|
|
|
|
2023-01-22 17:18:12 +00:00
|
|
|
return false;
|
|
|
|
})();
|
|
|
|
|
|
|
|
if (!$errmsg) {
|
|
|
|
if (count(WillyChat::$messages) > 10) {
|
|
|
|
array_pop(WillyChat::$messages);
|
|
|
|
}
|
2023-01-22 09:47:36 +00:00
|
|
|
|
|
|
|
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,
|
2023-01-22 12:17:50 +00:00
|
|
|
'just_sent_message' => $just_sent_message,
|
2023-01-22 17:18:12 +00:00
|
|
|
'errmsg' => $errmsg
|
2023-01-22 09:47:36 +00:00
|
|
|
]);
|
|
|
|
});
|
|
|
|
|
|
|
|
Route::get('/willychat/messages', function() {
|
|
|
|
view('pages/willychat/messages', [
|
|
|
|
'messages' => WillyChat::$messages
|
|
|
|
]);
|
|
|
|
});
|
|
|
|
|
|
|
|
Route::get('/willychat/sync', function() {
|
|
|
|
json_response(
|
|
|
|
hash('crc32', serialize(WillyChat::$messages))
|
|
|
|
);
|
|
|
|
});
|