willy.club/app/App/Controller/ChatController.php

94 lines
2.4 KiB
PHP
Raw Normal View History

2023-02-03 11:00:13 +00:00
<?php
namespace App\Controller;
use App\Config;
ChatController::init();
abstract class ChatController
{
private static array $messages;
static function init()
{
if (!file_exists(Config::get('path_to_chat_json_file'))) {
file_put_contents(
Config::get('path_to_chat_json_file'),
json_encode([])
);
}
self::$messages = json_decode(
file_get_contents(Config::get('path_to_chat_json_file')),
true
);
}
static function index()
{
if (empty($_POST)) {
return view('pages/chat/index', [
'nick' => 'Willy',
'just_sent_message' => false,
'errmsg' => false
]);
}
$nick = filter_input(INPUT_POST, 'nick');
$text = filter_input(INPUT_POST, 'text');
$errmsg = (function() use (&$text, &$nick): string|false {
if (empty(trim($nick, ' '))) {
return 'You must choose a nickname.';
}
$nick_max_chars = 128;
if (strlen($nick) > $nick_max_chars) {
return 'Your nickname is TOO LONG! ' . strlen($nick) . ' out of ' . $nick_max_chars. ' characters.';
}
$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.';
}
return false;
})();
if (!$errmsg) {
if (count(self::$messages) > 100) {
array_pop(self::$messages);
}
array_unshift(self::$messages, [
'nick' => $nick,
'date' => time(),
'text' => $text
]);
file_put_contents(Config::get('path_to_chat_json_file'),
json_encode(
self::$messages
)
);
}
view('pages/chat/index', [
'nick' => $nick,
'just_sent_message' => true,
'errmsg' => $errmsg
]);
}
static function messages()
{
view('pages/chat/messages', ['messages' => self::$messages]);
}
static function sync()
{
json_response(hash('crc32', serialize(self::$messages)));
}
}