<?php

/*
ET-Chat Copyright by SEDesign | ET-Chat v3.x.x Lizenz: CCPL | Autor: Evgeni Tcherkasski (info@s-e-d.de)
ET-Chat_T-FISH-MOD Weiterentwicklungen, Optimierungen und Ergänzungen am Code sind das geistige Eigentum von Tommy (Thomas Kuhn) und Harlekin (Bernd Witte).

Die darauf folgende Optimierungen und Ergänzungen am Code sind das Geistige Eigentum von Powermen (Christian K.) 
PHP 8/9 Ready, XML Parser, PDO Prepared Statements Get Set sicherheit usw.
*/

class MessageInserter extends EtChatConfig
{
    private $dbObj;
    public $status = null;

    public function __construct($dbObj, $raum_array)
    {
        parent::__construct();
        $this->dbObj = $dbObj;

        /* ===== PHP 8 Absicherung ===== */

        $_POST["roomchange"] = $_POST["roomchange"] ?? "";
        $_POST["message"] = $_POST["message"] ?? "";
        $_POST["room"] = $_POST["room"] ?? 0;
        $_POST["privat"] = $_POST["privat"] ?? 0;
        $_POST["color"] = $_POST["color"] ?? "";
        $_POST["bold"] = $_POST["bold"] ?? "";
        $_POST["italic"] = $_POST["italic"] ?? "";

        $_SESSION["etchat_" . $this->_prefix . "spam"] =
            $_SESSION["etchat_" . $this->_prefix . "spam"] ?? [];

        $_SESSION["etchat_" . $this->_prefix . "spam_warn"] =
            $_SESSION["etchat_" . $this->_prefix . "spam_warn"] ?? 0;

        $_SESSION["etchat_" . $this->_prefix . "chek_user_ajax_getted_data"] =
            $_SESSION[
                "etchat_" . $this->_prefix . "chek_user_ajax_getted_data"
            ] ?? [];

        $_SERVER["REMOTE_ADDR"] = $_SERVER["REMOTE_ADDR"] ?? "";

        /* =============================== */

        if (
            isset($_POST["roomchange"]) &&
            $_POST["roomchange"] == "true" &&
            !empty($raum_array[0][3])
        ) {
            $room_message_insert = str_replace(
                "\r\n",
                "<br />",
                $raum_array[0][3]
            );
            $room_message_insert = str_replace(
                "\n",
                "<br />",
                $room_message_insert
            );
            new SysMessage(
                $this->dbObj,
                "<br /><div style=\"margin: 4px;\">" .
                    $room_message_insert .
                    "<div>",
                (int) $_POST["room"],
                $_SESSION["etchat_" . $this->_prefix . "user_id"]
            );
        }

        if (isset($_POST["sysmess"])) {
            if ($this->spamTester()) {
                $this->status = "spam";
                return false;
            }

            if (
                !in_array(
                    $_POST["message"],
                    $_SESSION[
                        "etchat_" .
                            $this->_prefix .
                            "chek_user_ajax_getted_data"
                    ]
                )
            ) {
                return false;
            }

            if ($_POST["roomchange"] == "true") {
                $raum_name = $this->dbObj->sqlGet(
                    "SELECT etchat_roomname FROM {$this->_prefix}etchat_rooms where etchat_id_room =" .
                        (int) $_POST["room"]
                );

                if (!is_array($raum_name)) {
                    $raum_name = [];
                }

                $_POST["message"] = $_POST["message"] . " " . $raum_name[0][0];
            }

            $_POST["message"] = htmlspecialchars(
                $_POST["message"],
                ENT_QUOTES,
                "UTF-8"
            );
            $_POST["message"] =
                "<b>" .
                $_SESSION["etchat_" . $this->_prefix . "username"] .
                "</b> " .
                $_POST["message"];

            if (
                $_POST["roomchange"] == "true" &&
                $_SESSION["etchat_" . $this->_prefix . "userstatus"] ==
                    "status_invisible"
            ) {
                $_POST["privat"] =
                    $_SESSION["etchat_" . $this->_prefix . "user_id"];
            } else {
                if ($_POST["privat"] > 0) {
                    $_POST["privat"] =
                        $_SESSION["etchat_" . $this->_prefix . "user_id"];
                }
            }

            new SysMessage(
                $this->dbObj,
                $_POST["message"],
                (int) $_POST["room"],
                (int) $_POST["privat"]
            );
        } else {
            if ($this->spamTester()) {
                $this->status = "spam";
                return false;
            }

            $this->messageTransformer();

            $_POST["color"] = substr($_POST["color"], 0, 7);
            $_POST["bold"] = substr($_POST["bold"], 0, 6);
            $_POST["italic"] = substr($_POST["italic"], 0, 6);

            $style =
                "color:" .
                htmlentities($_POST["color"], ENT_QUOTES, "UTF-8") .
                ";font-weight:" .
                htmlentities($_POST["bold"], ENT_QUOTES, "UTF-8") .
                ";font-style:" .
                htmlentities($_POST["italic"], ENT_QUOTES, "UTF-8") .
                ";";

            // Prüfen, ob es sich um einen Bot-/Systembefehl handelt
            if (
                preg_match(
                    "/^\\.(hallo|bye|time|version|chatregeln|reg)/i",
                    $_POST["message"]
                )
            ) {
                // Diese Befehle werden später behandelt
            } else {
                // Normale Nachricht speichern
                $this->dbObj->sqlSet(
                    "INSERT INTO {$this->_prefix}etchat_messages (
					etchat_user_fid, etchat_text, etchat_text_css, etchat_timestamp, etchat_fid_room, etchat_privat, etchat_user_ip
				) VALUES (
					'" .
                        $_SESSION["etchat_" . $this->_prefix . "user_id"] .
                        "',
					'" .
                        $_POST["message"] .
                        "',
					'" .
                        $style .
                        "',
					" .
                        date("U") .
                        ",
					" .
                        (int) $_POST["room"] .
                        ",
					" .
                        (int) $_POST["privat"] .
                        ",
					'" .
                        $_SERVER["REMOTE_ADDR"] .
                        "'
				)"
                );
            }

            // ---- CHATBOT START ------------------------------------------------------

            // Prüfen, ob der Bot aktiviert ist
            $botEnabled =
                (int) ($_SESSION["etchat_" . $this->_prefix . "etchat_bot"] ??
                    0);

            if ($botEnabled) {
                $messageText = strtolower($_POST["message"]);

                // Wenn Nachricht "bot", "chatbot" oder "mc-bot" enthält
                if (
                    preg_match(
                        "/\b(bot|chatbot|caht-bot|ChatBot)\b/i",
                        $messageText
                    )
                ) {
                    // JSON-Datei laden
                    $jsonFile = dirname(__DIR__, 1) . "/cache/bot_answers.json";

                    if (file_exists($jsonFile)) {
                        $botAnswers = json_decode(
                            file_get_contents($jsonFile),
                            true
                        );

                        // Falls JSON nicht geladen werden kann
                        if (!is_array($botAnswers) || empty($botAnswers)) {
                            $botAnswers = [
                                "Ich bin kaputt… bitte mein JSON reparieren!",
                            ];
                        }
                    } else {
                        // JSON fehlt => Notfallantwort
                        $botAnswers = ["JSON-Datei wurde nicht gefunden!"];
                    }

                    // Antwort auswählen
                    $reply = $botAnswers[array_rand($botAnswers)];

                    $safeReply = $this->dbObj->escape($reply);
                    $botStyle =
                        "color:var(--Botfarbe);font-weight:normal;font-style:italic;";

                    // Kleine Denkpause
                    usleep(rand(100000, 500000)); // Mikrosekunden

                    // In DB schreiben
                    $this->dbObj->sqlSet(
                        "INSERT INTO {$this->_prefix}etchat_messages
             (etchat_user_fid, etchat_text, etchat_text_css, etchat_timestamp, etchat_fid_room, etchat_privat)
             VALUES (
                 -1,
                 '{$safeReply}',
                 '{$botStyle}',
                 " .
                            time() .
                            ",
                 " .
                            (int) $_POST["room"] .
                            ",
                 0
             )",
                        false
                    );
                }
            }

            // ---- CHATBOT ENDE ------------------------------------------------------

            // BOT -------------------------------------------
            // (Deine bestehenden .hallo / .bye / .time usw. bleiben unverändert)

            // Prüfen, ob Nachricht mit .hallo oder .bye beginnt
            $cmd = "";
            if (substr($_POST["message"], 0, 6) == ".hallo") {
                $cmd = "hallo";
            } elseif (substr($_POST["message"], 0, 4) == ".bye") {
                $cmd = "bye";
            }

            if ($cmd !== "") {
                // passender Datei-Name wählen
                $file_map = [
                    "hallo" => "./cache/anreden.txt",
                    "bye" => "./cache/verabschieden.txt",
                ];
                $txt_file = __DIR__ . "/" . $file_map[$cmd];

                // Datei laden oder Fallback setzen
                if (file_exists($txt_file)) {
                    $lines = file(
                        $txt_file,
                        FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES
                    );
                    $texte = array_map("trim", $lines);
                } else {
                    $texte =
                        $cmd === "hallo"
                            ? ["Hallo", "Hi", "Servus", "Grüß dich"]
                            : ["Tschüss", "Ciao", "Mach’s gut", "Bis bald"];
                }

                // aktueller Benutzer
                $aktueller_user =
                    $_SESSION["etchat_" . $this->_prefix . "username"] ?? "";
                $aktueller_user_norm = mb_strtolower(
                    trim($aktueller_user),
                    "UTF-8"
                );

                // Alle Online-User abrufen
                $rows = $this->dbObj->sqlGet(
                    "SELECT etchat_user_online_user_name
         FROM " .
                        $this->_prefix .
                        "etchat_useronline"
                );

                if (!is_array($rows)) {
                    $rows = [];
                }

                $teile = [];
                foreach ($rows as $row) {
                    $user = trim($row[0]);
                    if (
                        mb_strtolower($user, "UTF-8") === $aktueller_user_norm
                    ) {
                        continue;
                    }

                    $text = $texte[array_rand($texte)];
                    $user_html = htmlspecialchars($user, ENT_QUOTES, "UTF-8");

                    // Stil
                    $teile[] = "$text <span style=\"font-weight:bold; background-color:#ffff0052; padding:2px; border-radius:3px;\">$user_html</span>";
                }

                if (!empty($teile)) {
                    if ($cmd === "hallo") {
                        $schluss =
                            count($teile) === 1
                                ? "! Schön, dass du online bist."
                                : "! Schön, dass ihr online seid.";
                    } else {
                        // .bye
                        $schluss =
                            count($teile) === 1
                                ? "! Mach’s gut."
                                : "! Schön, mit euch gechattet zu haben.";
                    }

                    $nachricht = implode(", ", $teile) . $schluss;
                    $nachricht_safe_sql = $this->dbObj->escape($nachricht);

                    $this->dbObj->sqlSet(
                        "INSERT INTO " .
                            $this->_prefix .
                            "etchat_messages
             (etchat_user_fid, etchat_text, etchat_text_css, etchat_timestamp, etchat_fid_room, etchat_privat)
             VALUES
             ('" .
                            $_SESSION["etchat_" . $this->_prefix . "user_id"] .
                            "',
              '" .
                            $nachricht_safe_sql .
                            "',
              'color:#" .
                            $_SESSION["etchat_" . $this->_prefix . "syscolor"] .
                            ";font-weight:normal;font-style:normal;',
              " .
                            time() .
                            ",
              " .
                            (int) $_POST["room"] .
                            ",
              0)",
                        false
                    );
                }
            }
            if (substr($_POST["message"], 0, 5) == ".time") {
                $this->dbObj->sqlSet(
                    "INSERT INTO {$this->_prefix}etchat_messages ( etchat_user_fid , etchat_text, etchat_text_css, etchat_timestamp, etchat_fid_room, etchat_privat)
					VALUES ( 1, '" .
                        date("d.m.Y - H:i") .
                        "', 'color:#" .
                        $_SESSION["etchat_" . $this->_prefix . "syscolor"] .
                        ";font-weight:normal;font-style:normal;', " .
                        date("U") .
                        ", " .
                        (int) $_POST["room"] .
                        ", 0)",
                    false
                );
            }
            if (substr($_POST["message"], 0, 8) == ".version") {
                $this->dbObj->sqlSet(
                    "INSERT INTO {$this->_prefix}etchat_messages ( etchat_user_fid , etchat_text, etchat_text_css, etchat_timestamp, etchat_fid_room, etchat_privat)
					VALUES ( 1, 'ET-Chat v3.0.7 r3 / M.C.v.1.9.6.3', 'color:#" .
                        $_SESSION["etchat_" . $this->_prefix . "syscolor"] .
                        ";font-weight:normal;font-style:normal;', " .
                        date("U") .
                        ", " .
                        (int) $_POST["room"] .
                        ", 0)",
                    false
                );
            }
            $role = $_SESSION["etchat_" . $this->_prefix . "user_priv"] ?? "";
            $allowedRoles = ["admin", "mod", "co_admin", "grafik", "chatwache"];

            if (
                substr($_POST["message"], 0, 11) == ".chatregeln" &&
                in_array($role, $allowedRoles)
            ) {
                $this->dbObj->sqlSet(
                    "INSERT INTO {$this->_prefix}etchat_messages ( etchat_user_fid , etchat_text, etchat_text_css, etchat_timestamp, etchat_fid_room, etchat_privat)
                    VALUES ( 1, '<center> Regeln<br><iframe src=\"?Text&id=4\" width=\"70%\"</iframe></center>', 'color:#" .
                        $_SESSION["etchat_" . $this->_prefix . "syscolor"] .
                        ";font-weight:normal;font-style:normal;', " .
                        date("U") .
                        ", " .
                        (int) $_POST["room"] .
                        ", 0)",
                    false
                );
            }
            if (
                substr($_POST["message"], 0, 4) == ".reg" &&
                in_array($role, $allowedRoles)
            ) {
                $this->dbObj->sqlSet(
                    "INSERT INTO {$this->_prefix}etchat_messages ( etchat_user_fid , etchat_text, etchat_text_css, etchat_timestamp, etchat_fid_room, etchat_privat)
                    VALUES ( 1, '<center> Registrieren (Name durch Passwort sch&uuml;tzen)<br><iframe src=\"?Text&id=3\" width=\"70%\"</iframe></center>', 'color:#" .
                        $_SESSION["etchat_" . $this->_prefix . "syscolor"] .
                        ";font-weight:normal;font-style:normal;', " .
                        date("U") .
                        ", " .
                        (int) $_POST["room"] .
                        ", 0)",
                    false
                );
            }
        }
    }

    private function messageTransformer()
    {
        $_POST["message"] = substr($_POST["message"], 0, 1000);
        if (strlen($_POST["message"]) > 999) {
            $_POST["message"] .= "...";
        }

        $woerter_array = explode(" ", $_POST["message"]);
        foreach ($woerter_array as $wort) {
            if (
                strlen($wort) > 50 &&
                substr($wort, 0, 7) != "http://" &&
                substr($wort, 0, 8) != "https://" &&
                substr($wort, 0, 6) != "ftp://" &&
                stripos($wort, "]http://") === false &&
                stripos($wort, "]https://") === false
            ) {
                $new_wort = wordwrap($wort, 50, " ", 1);
                $_POST["message"] = str_replace(
                    $wort,
                    $new_wort,
                    $_POST["message"]
                );
            }
        }
        $_POST["message"] = htmlspecialchars(
            str_replace("\\", "\\\\", $_POST["message"]),
            ENT_QUOTES,
            "UTF-8"
        );
    }

    private function spamTester()
    {
        $_SESSION["etchat_" . $this->_prefix . "spam"][] = time();
        if (count($_SESSION["etchat_" . $this->_prefix . "spam"]) > 200) {
            unset($_SESSION["etchat_" . $this->_prefix . "spam"]);
            $_SESSION["etchat_" . $this->_prefix . "spam"] = [];
        }
        $role = $_SESSION["etchat_" . $this->_prefix . "user_priv"] ?? null;
        $excludedRoles = ["admin", "mod", "chatwache", "co_admin"];

        if (
            count($_SESSION["etchat_" . $this->_prefix . "spam"]) > 3 &&
            !in_array($role, $excludedRoles, true)
        ) {
            $spamCount = count($_SESSION["etchat_" . $this->_prefix . "spam"]);
            $spam_interval =
                $_SESSION["etchat_" . $this->_prefix . "spam"][$spamCount - 1] -
                $_SESSION["etchat_" . $this->_prefix . "spam"][$spamCount - 4];
            if ($spam_interval < 6) {
                $langObj = new LangXml();
                $lang = $langObj->getLang()->reloader_php[0];
                new SysMessage(
                    $this->dbObj,
                    $lang->spam[0]->tagData,
                    (int) $_POST["room"],
                    (int) $_SESSION["etchat_" . $this->_prefix . "user_id"]
                );
                $_SESSION["etchat_" . $this->_prefix . "spam_warn"]++;
                if ($_SESSION["etchat_" . $this->_prefix . "spam_warn"] > 2) {
                    $blObj = new Blacklist($this->dbObj);
                    $blObj->insertUser(
                        $_SESSION["etchat_" . $this->_prefix . "user_id"],
                        300
                    );
                    $blObj->userInBlacklist();
                    $blObj->allowedToAndSetCookie();
                    $blObj->killUserSession();
                    return true;
                } else {
                    return false;
                }
            }
        }
        return false;
    }
}
?>
