Tutorial: Quizbot in den Chat einbauen

Tutorial Übersicht Tutorial Übersicht  >>  ET-Chat ET-Chat

Quizbot in den Chat einbauen NEU
Von: Harlekin am: 13.12.2025 - 22:55 Gelesen 36 x gelesen Tutorial drucken

Werbung:
ALL INKL



Ich habe es endlich fertig bekommen einen einfachen Quizbot in den Chat ein zu bauen.
Sicherlich gibt es elegantere Methoden mit Datenbank, Adminbereich, automatischer Zählung der richtigen Antworten und so weiter, aber mir reicht diese Version erstmal.

Ich habe selber derzeit um die 300 Fragen so drin, die ich aber nicht alle hier mit im Code habe. Aber das solltet ihr selber ohne weiteres erweitern können.

Anleitung:
Eine Quizfrage wird gestartet mit !quiz
Es erscheint die Frage im Chat.
Sollte die nächsten 30 Sekunden keiner die richtige Antwort schreiben, kommt ein Tip.
Sollte dann wieder die nächsten 30 Sekunden keiner die richtige Antwort schreiben, kommt ein zweiter Tip.
Und nach weiteren 30 Sekunden ohne richtige Antwort wird die richtige Antwort in den Chat geschrieben.
Danach kann dann eine weitere Frage gestartet werden.

Eine Quizfrage wird gestoppt mit !stop
Danach kann dann eine weitere Frage gestartet werden.

1. erstellt im Root Verzeichnis von eurem ET-Chat ein Verzeichnis cache

2. gebt dem Verzeichnis cache die Rechte 777

3. erstellt eine Datei quiz_status.json mit folgendem Inhalt:
Code Alles auswählen
{
    "aktiv": false,
    "frage": "",
    "tipp1": "",
    "tipp2": "",
    "antwort": "",
    "start": 0,
    "raum": 0,
    "starter_id": 0,
    "starter_name": "",
    "tipp1_sent": false,
    "tipp2_sent": false,
    "gewonnen": false,
    "gewinner_id": 0,
    "gewinner_name": "",
    "gewinner_antwort": "",
    "erkannt_um": 0
}


4. ladet die Datei in euer Verzeichnis cache

5. gebt der Datei die Rechte 666

6. class/ReloaderMessages.class.php bearbeiten
WICHTIG: Erst die Datei 1x sichern!
wer eine unverbastelte ReloaderMessages.class.php hat kann den vorhanden Code mit dem folgenden Code komplett austauschen.
Wer nicht, muss die Dateien vergleichen.

Code Alles auswählen
<?php
/**
 * Class ReloaderMessages, the AJAX Request for getting and setting new messges,  pull session and more,
 *
 * LICENSE: CREATIVE COMMONS PUBLIC LICENSE  "Namensnennung — Nicht-kommerziell 2.0"
 *
 * @copyright  2010 <SEDesign />
 * @license    http://creativecommons.org/licenses/by-nc/2.0/de/
 * @version    $3.0.7$
 * @link       http://www.sedesign.de/de_produkte_chat-v3.html
 * @since      File available since Alpha 2.0
 */
 
class ReloaderMessages extends DbConectionMaker
{

   /**
   * Constructor
   *
   * @uses ConnectDB::sqlGet()   
   * @uses Blacklist object creation
   * @uses Blacklist::userInBlacklist() checks if in the Blacklist
   * @uses Blacklist::allowedToAndSetCookie()
   * @uses Blacklist::killUserSession()
   * @uses MessageInserter object creation
   * @uses MessageInserter::$status break if status is "spam"
   * @return void
   */
   public function __construct (){
      
      // call parent Constructor from class DbConectionMaker
      parent::__construct();

      session_start();

      header('Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0');
      header('content-type: application/json; charset=utf-8');

      // Checks if the user is in the kick list
      if ($this->checkKicklist()) { $this->errorOutput("kick"); return false; }
      
      // create new Blacklist Object
      $blackListObj = new Blacklist($this->dbObj);
      
      // Is the curent user IP in zhe Blacklist or has the user browser an actual "black cookie"?
      if ($blackListObj->userInBlacklist()){
         if ($blackListObj->allowedToAndSetCookie()){
            $blackListObj->killUserSession();
            $this->errorOutput("blacklist");
            return false;
         }
      }
      
      // Get room array
      $raum_array = $this->getRoomArray();
      // it kannt happen, but if somebody tries to fool the JavaScript in chat.js ;-)
      if (!is_array($raum_array)) return false;
      
      // all needed Userdata for current user
      $user_array=$this->dbObj->sqlGet("SELECT etchat_user_id, etchat_username, etchat_userprivilegien, etchat_usersex FROM {$this->_prefix}etchat_user where etchat_user_id = ".$_SESSION['etchat_'.$this->_prefix.'user_id']);

      // Update etchat_useronline if the session exists or create a new dataset in the table
      $this->refreshUserSession($user_array, $raum_array, $blackListObj->user_param_all);
      
      if (empty($_POST['privat'])) $_POST['privat']=0;
      
      // ===== QUIZBOT INTEGRATION =====
      $this->handleQuizBot();
      // ===============================
      
      // Make message
      if (isset($_POST['message']) && !empty($_POST['message']) && trim($_POST['message'])!="/window:" && !empty($_SESSION['etchat_'.$this->_prefix.'user_id'])){
         
         // create new MessageInserter Object
         $inserterObj = new MessageInserter($this->dbObj, $raum_array);
         
         // if $inserterObj->status="spam" then the user is now inserted in Blacklist and just send "spam" message to the JacaScript at AJAX
         if (!empty($inserterObj->status)) {
            $this->errorOutput($inserterObj->status);
            return false;
         }
      }
      
      // selects all needed Messages to display and make a JSON output from it
      $this->makeJsonOutput($this->selectMessagesForTheUser());
   }
   
   /**
   * QUIZBOT HANDLER - Wird NACH der Initialisierung ausgeführt
   *
   * @return void
   */
   private function handleQuizBot() {
      // Prüfe ob DB-Objekt existiert
      if (!isset($this->dbObj) || !is_object($this->dbObj)) {
         return;
      }
      
      // Prüfe ob Session existiert
      if (!isset($_SESSION) || session_id() == '') {
         return;
      }
      
      // Pfad zur Quiz-Status Datei (global für alle Benutzer)
      $quizFile = __DIR__ . '/../cache/quiz_status.json';
      // Verzeichnis erstellen falls nicht existiert
      $cacheDir = dirname($quizFile);
      if (!file_exists($cacheDir)) {
         mkdir($cacheDir, 0755, true);
      }
      
      // Quiz-Status aus Datei lesen oder initialisieren
      if (file_exists($quizFile)) {
         $q = json_decode(file_get_contents($quizFile), true);
         // Sicherstellen, dass alle Felder existieren
         if (!isset($q['tipp2_sent'])) {
            $q['tipp2_sent'] = false;
         }
         
         if (!isset($q['tipp1_sent'])) {
            $q['tipp1_sent'] = false;
         }
         
         if (!isset($q['starter_id'])) {
            $q['starter_id'] = 0;
         }
         
         if (!isset($q['starter_name'])) {
            $q['starter_name'] = '';
         }
         
         if (!isset($q['gewinner_id'])) {
            $q['gewinner_id'] = 0;
         }
         
         if (!isset($q['gewinner_name'])) {
            $q['gewinner_name'] = '';
         }
         
         if (!isset($q['gewinner_antwort'])) {
            $q['gewinner_antwort'] = '';
         }
         
         if (!isset($q['erkannt_um'])) {
            $q['erkannt_um'] = 0;
         }
      } else {
         $q = [
            'aktiv' => false,
            'frage' => '',
            'tipp1' => '',
            'tipp2' => '',
            'antwort' => '',
            'start' => 0,
            'raum' => 0,
            'starter_id' => 0,
            'starter_name' => '',
            'tipp1_sent' => false,
            'tipp2_sent' => false,
            'gewonnen' => false,
            'gewinner_id' => 0,
            'gewinner_name' => '',
            'gewinner_antwort' => '',
            'erkannt_um' => 0
         ];
         file_put_contents($quizFile, json_encode($q));
      }
      
      // 1. TIMER prüfen (nur wenn Quiz aktiv und Raum gesetzt)
      if ($q['aktiv'] && isset($_POST['room']) && $q['raum'] == (int)$_POST['room'] && !$q['gewonnen']) {
         $zeit = time() - $q['start'];
         if ($zeit >= 90) {// 90 Sekunden - Zeit abgelaufen
            $antwort_safe = addslashes(ucwords($q['antwort']));
            $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,'Die Zeit ist abgelaufen! Die Antwort war: <b>{$antwort_safe}</b>','color:#e67e22;font-weight:bold;',".time().",".$q['raum'].",0)");
            
            $q['aktiv'] = false;
            $q['gewonnen'] = true;
            file_put_contents($quizFile, json_encode($q));
         } elseif ($zeit >= 60 && !$q['tipp2_sent']) {// 60 Sekunden - Tipp 2
            $tipp2_safe = addslashes($q['tipp2']);
            $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,'<b>Tipp 2:</b> {$tipp2_safe}','color:#e67e22;',".time().",".$q['raum'].",0)");
            
            $q['tipp2_sent'] = true;
            file_put_contents($quizFile, json_encode($q));
         } elseif ($zeit >= 30 && !$q['tipp1_sent']) {// 30 Sekunden - Tipp 1
            $tipp1_safe = addslashes($q['tipp1']);
            $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,'<b>Tipp 1:</b> {$tipp1_safe}','color:#e67e22;',".time().",".$q['raum'].",0)");
            
            $q['tipp1_sent'] = true;
            file_put_contents($quizFile, json_encode($q));
         }
      }
      
      // 2. NACHRICHTEN verarbeiten (nur wenn eine Nachricht gesendet wurde und User-ID existiert)
      if (isset($_POST['message']) && !empty($_POST['message']) && isset($_SESSION['etchat_'.$this->_prefix.'user_id'])) {
         $message = trim($_POST['message']);
         // Flag ob QuizBot die Nachricht verarbeitet hat
         $quizbot_verarbeitet = false;
         
         // Quiz Befehl
         if (stripos($message, '!quiz') === 0) {
            $userPriv = $_SESSION['etchat_'.$this->_prefix.'user_priv'] ?? '';
            if (in_array($userPriv, ['admin','mod'])) {
               $quizbot_verarbeitet = true;
               if ($q['aktiv'] && !$q['gewonnen']) {
                  // Bot-Fehlermeldung
                  $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,'Es läuft bereits eine Quizfrage!','color:#e67e22;font-weight:bold;',".time().",".(int)($_POST['room']??0).",0)");
               } else {
                  // Fragen-Datenbank
                  $fragen = [
                     "\"Hauptstadt\" von Europa?|||B _ _ _ _ _ _ _|||B _ _ s _ _ _ l|||Brüssel",
                     "Wer soll das gesagt haben? (Vor- und Nachname!)! \"Hier stehe ich nun, ich kann nicht anders\"|||M _ _ _ _ _  L _ _ _ _ _|||M a _ t _ _  L _ t _ _ r|||Martin Luther",
                     "Ich übergebe ihnen hier mal eine Xerographie....häh? Was übergibt er?|||K _ _ _ _|||K _ p _ e|||Kopie",
                     "\"Mein kleiner grüner Kaktus steht draussen am Balkon\"... Welche Gruppe machte u.a. damit Furore?|||C _ _ _ D _ _ _  H _ _ _ _ _ _ _ _ _|||C _ _ _ d _ _ n  H _ _ m o _ _ _ _ s|||Comedian Harmonists",
                     "\"Mutterland\" von Sony?|||J _ _ _ _|||J _ _ _ n|||Japan",
                     "\"Totengräber\" der UDSSR? (Vor- und Nachname!)|||M _  _ _ _ _  G _ _ _ _ _ _ _ _ _ _|||M _ c h _ _ _  G _ _ b _ t _ _ _ o w|||Michail Gorbatschow",
                     "1937 in Duisburg geboren, 1949 in die DDR abgewandert - immer auf Achse, am Tatort und ein Liebling. (Vor- und Nachname!)|||M _ _ _ _ _ _  K _ _ _|||M _ _ f _ _ d  K _ _g|||Manfred Krug",
                     "Bösewichter? (Damit wird kleinen Kindern oft das Zähneputzen erklärt)|||K _ _ _ _ _  und  B _ _ _ _ _|||K _ r _ _ s  und  B _ k t _ s|||Karius und Baktus",
                     "Abdeckung eines Loches in einer Wand, aus welcher man mit Hilfe von metallischen Strippen einer Gerätschaft Energie zuführen kann?|||S _ _ _ _ _ _ _ _|||S t _ _ _ d _ _ e|||Steckdose",
                     "Abkürzung für Strafgesetzbuch?|||S _ _ _|||S _ _ b|||StGb",
                     "Abnehmbares, nicht faltbares Autodach?|||H _ _ _ _ _ _|||H _ r d _ _ p|||Hardtop",
                     "Alte Druckeinheit?|||A _ _ _|||A _ _ e|||Atue",
                     "Alte japanische Kaiserstadt?|||K _ _ _ _|||K y _ _ o|||Kyoto",
                     "Amerikanischer Schwarzenführer (*1929, +1968)?|||M _ _ _ _ _  L _ _ _ _ _  K _ _ _|||M _ _ t _ _  L _ t h _ r  K _ _ g|||Martin Luther King",
                     "Wo Wera und Fulda sich küssen entspringt die ...?|||W _ _ _ _|||W _ _ _ r|||Weser",
                     "An welchem Fluss liegt das Land Liechtenstein?|||R _ _ _ _|||R _ _ _ n|||Rhein",
                     "An welchem Fluss liegt Heidelberg?|||N _ _ _ _ _|||N _ _ k _ r|||Neckar",
                     "An welchem Meer liegt Scheveningen?|||N _ _ _ _ _ _|||N _ _ d _ _ e|||Nordsee",
                     "An welchem Wochentag wurde JFK erschossen?|||F _ _ _ _ _ _|||F _ _ _ _ _ g|||Freitag",
                     "An welchen See grenzen drei europäische Staaten?|||B _ _ _ _ _ _ _|||B _ d _ n _ _ e|||Bodensee",
                     "Anderer Name für Karotten?|||M _ _ _ _ _|||M _ h r _ n|||Möhren",
                     "Anderes Wort für \"dafür\"?|||p _ _|||p _ o|||pro",
                     "Anderes Wort für \"dagegen\"?|||k _ _ _ _ _|||k _ _ t _ a|||kontra",
                     "Anderes Wort für \"rechtmässig\"?|||l _ _ _ _ _ _|||l _ g _ t _ m|||legitim",
                     "Anderes Wort für Bratrost?|||G _ _ _ _|||G r _ _ l|||Grill",
                     "Anderes Wort für Werbung?|||R _ _ _ _ _ _|||R _ k l _ _ e|||Reklame",
                     "Anhaltende intensive Furcht vor einem speziellen Objekt oder einer bestimmten Situation oder Handlung?|||P _ _ _ _ _|||P h _ b _ e|||Phobie",
                     "Archimedes rannte nackt durch die Stadt und schrie: \"Ich habs\". Welcher Materialkonstante war er auf der Spur?|||D _ _ _ _ _|||D _ c h _ e|||Dichte",
                     "Auf welche Straße in New York schaut die Weltwirtschaft|||W _ _ _  S _ _ _ _ _|||W _ _ l  S t r _ _ t|||Wall Street",
                     "Auf welche Insel dürfen keine fremden Pferde mitgebracht werden?|||I _ _ _ _ _|||I s _ _ _ d|||Island",
                     "Auf welche Stadt wurde die erste Atombombe geworfen?|||H _ _ _ _ _ _ _ _|||H _ r o _ _ _ _ a|||Hiroshima",
                     "Auf welchem Berg soll Noahs Arche gelandet sein?|||A _ _ _ _ _|||A r _ r _ t|||Ararat",
                     "Auf welchem Kontinent gibt es Berge namens Dolomiten?|||E _ _ _ _ _|||Europa|||Europa",
                     "Welche Insel wird durch die Straße von Messina vom Festland getrennt?|||S _ _ _ _ _ _ _|||S _ z _ l _ _ n|||Sizilien"
                  ];
                  
                  // Quiz starten
                  $f = $fragen[array_rand($fragen)];
                  $t = explode("|||", $f);
                  $q = [
                     'aktiv' => true,
                     'frage' => trim($t[0]),
                     'tipp1' => trim($t[1]),
                     'tipp2' => trim($t[2]),
                     'antwort' => strtolower(trim($t[3])),
                     'start'       => time(),
                     'raum'        => (int)($_POST['room']??0),
                     'starter_id'  => $_SESSION['etchat_'.$this->_prefix.'user_id'],
                     'starter_name'=> $_SESSION['etchat_'.$this->_prefix.'username'],
                     'tipp1_sent'  => false,
                     'tipp2_sent'  => false,
                     'gewonnen'    => false
                  ];
                  
                  // In Datei speichern
                  file_put_contents($quizFile, json_encode($q));
                  // User- und Bot-Nachrichten
                  $user_id = $_SESSION['etchat_'.$this->_prefix.'user_id'];
                  $username = $_SESSION['etchat_'.$this->_prefix.'username'];
                  $current_time = time();
                  $username_safe = addslashes($username);
                  $frage_safe = addslashes($q['frage']);
                  $user_style = $this->getUserStyle($username);
                  // 1. User-Nachricht: Quiz gestartet
                  $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
                  ({$user_id},'{$username_safe} hat eine neue Quizfrage gestartet!','{$user_style}',{$current_time},".$q['raum'].",0)");
                  // 2. Bot-Nachricht: Frage
                  $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,'Frage: <b>{$frage_safe}</b>','color:#e67e22;font-weight:bold;',".($current_time + 1).",".$q['raum'].",0)");
                  // 3. Bot-Nachricht: Timer
                  $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,'90 Sekunden Zeit – und los!','color:#e67e22;',".($current_time + 2).",".$q['raum'].",0)");
               }
            }
         }
         
         // !stop Befehl
         if (strtolower($message) === '!stop' && $q['aktiv'] && !$q['gewonnen']) {
            $userPriv = $_SESSION['etchat_'.$this->_prefix.'user_priv'] ?? '';
            if (in_array($userPriv, ['admin','mod'])) {
               $quizbot_verarbeitet = true;
               $user_id = $_SESSION['etchat_'.$this->_prefix.'user_id'];
               $username = $_SESSION['etchat_'.$this->_prefix.'username'];
               $current_time = time();
               $username_safe = addslashes($username);
               $user_style = $this->getUserStyle($username);
               // 1. User-Nachricht: Quiz abgebrochen
               $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
               ({$user_id},'{$username_safe} hat die Quizfrage abgebrochen.','{$user_style}',{$current_time},".$q['raum'].",0)");
               // 2. Bot-Nachricht: Bestätigung
               $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,'Die Quizfrage wurde abgebrochen.','color:#e67e22;',".($current_time + 1).",".$q['raum'].",0)");
               
               $q['aktiv'] = false;
               $q['gewonnen'] = true;
               file_put_contents($quizFile, json_encode($q));
            }
         }
         
         // Antwort prüfen (nur wenn Quiz aktiv und noch nicht gewonnen)
         if ($q['aktiv'] && !$q['gewonnen'] && $q['raum'] == (int)$_POST['room'] && trim($message) !== '' && !$quizbot_verarbeitet) {
            // Einfacher, case-insensitiver Vergleich
            $user_answer = strtolower(trim($message));
            $correct_answer = strtolower(trim($q['antwort']));
            if ($user_answer === $correct_answer) {
               $username = $_SESSION['etchat_'.$this->_prefix.'username'];
               $user_id = $_SESSION['etchat_'.$this->_prefix.'user_id'];
               $current_time = time();
               $username_safe = addslashes($username);
               $antwort_safe = addslashes(ucwords($q['antwort']));
               $user_answer_text = addslashes(trim($_POST['message']));
               // Hole den User-Style mit der existierenden Funktion
               $user_style = $this->getUserStyle($username);
               // 1. Quiz SOFORT beenden
               $q['gewonnen'] = true;
               $q['aktiv'] = false;
               file_put_contents($quizFile, json_encode($q));
               // 2. User-Antwort ALS ECHTER USER
               $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
               ({$user_id}, '{$user_answer_text}','{$user_style}',{$current_time},{$q['raum']},0)");
               // 3. Gewinn-Meldung als Bot-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
               (1,'<span style=\"color:#34AF00;font-weight:bold;\">✓ RICHTIG! {$username_safe}!</span> Die Antwort war: <strong>{$antwort_safe}</strong>','color:#e67e22;'," . ($current_time + 1) . ",{$q['raum']},0)");
               // 4. Original-Nachricht löschen
               $_POST['message'] = '/window:';
               $quizbot_verarbeitet = true;
            }
         }
         
         // Wenn QuizBot die Nachricht verarbeitet hat, leere sie für MessageInserter
         if ($quizbot_verarbeitet) {
            $_POST['message'] = '';
         }
      }
   }

   /**
   * Holt die Stil-Parameter des Users aus POST oder Cookie
   *
   * @param string $username Benutzername
   * @return string CSS-Stil
   */
   private function getUserStyle($username) {
      // 1. Versuche aus POST-Parametern zu holen (aktuellste Werte)
      if (isset($_POST['color']) && !empty($_POST['color'])) {
         $color = htmlentities($_POST['color'], ENT_QUOTES, "UTF-8");
         $bold = isset($_POST['bold']) ? htmlentities($_POST['bold'], ENT_QUOTES, "UTF-8") : 'normal';
         $italic = isset($_POST['italic']) ? htmlentities($_POST['italic'], ENT_QUOTES, "UTF-8") : 'normal';
         
         // Style zusammenbauen wie in MessageInserter
         $style = "color:{$color};font-weight:{$bold};font-style:{$italic};";
         
         // Eventuell weitere Parameter
         if (isset($_POST['underline']) && $_POST['underline'] == 'underline') {
            $style .= "text-decoration:underline;";
         }
         
         return $style;
      }
      
      // 2. Fallback: Farbe aus Cookie holen
      $cookie_name = 'saved_color_' . $username;
      if (isset($_COOKIE[$cookie_name]) && !empty($_COOKIE[$cookie_name])) {
         $color = trim($_COOKIE[$cookie_name]);
         // Sicherstellen, dass es eine gültige CSS-Farbe ist
         if (preg_match('/^#?[0-9a-fA-F]{3,6}$/', $color)) {
            if (strpos($color, '#') !== 0) {
               $color = '#' . $color;
            }
            return 'color:' . $color . ';font-weight:normal;font-style:normal;';
         }
      }
      
      // 3. Standard-Stil
      return 'color:inherit;font-weight:normal;font-style:normal;';
   }


   /**
   * Creates the JSON-Output for AJAX-Request
   *
   * @param Array $feld this array contains the messages to be transmitted to the user
   * @uses ConnectDB::sqlGet()   
   * @uses ConnectDB::close()   
   * @uses StaticMethods::filtering()
   * @return void
   */
   private function makeJsonOutput($feld){
   
      $ausgabeJSON_Inhalt=array();

      // Get the smileys list
      $sml = $this->dbObj->sqlGet("SELECT etchat_smileys_sign, etchat_smileys_img FROM {$this->_prefix}etchat_smileys");

      // JSON creation
      if (is_array($feld)){
         $ausgabeJSON_Anfang = "{\"data\" : [";

         for ($a=0; $a < count($feld); $a++){
            // Blocking if the opponent user that is in the blocklist of user own session
            if (!$this->blockiere($feld[$a][6],$feld[$a][5])){
               
               // outputed messages counter, is used as a continuous message id in chat.js (changed since v307-Beta10)
               $message2send = addslashes(StaticMethods::filtering(stripslashes($feld[$a][2]), $sml, $this->_prefix));
               
               // private messages in extra window
               if (substr($message2send, 0, 8)=="/window:" && $feld[$a][5]!=0) {
                  $message2send = substr($message2send, 8, strlen($message2send));
                  $normal_message_counter = "";
               }
               else {
                  if (isset($_SESSION['etchat_'.$this->_prefix.'count'])) {
                     $_SESSION['etchat_'.$this->_prefix.'count']++;
                  } else {
                     $_SESSION['etchat_'.$this->_prefix.'count'] = 1;
                  }
                  $normal_message_counter = $_SESSION['etchat_'.$this->_prefix.'count'];
               }
               
               $ausgabeJSON_Inhalt[] = "{\"id\":\"".$normal_message_counter."\",\"user\":\"".(addslashes($feld[$a][1]))."\",\"user_id\":\"".(addslashes($feld[$a][6]))."\",\"message\":\"".$message2send."\",\"time\":\"".date("H:i",$feld[$a][3])."\",\"privat\":\"".$feld[$a][5]."\",\"css\":\"".$feld[$a][7]."\",\"priv\":\"".$feld[$a][8]."\",\"sex\":\"".$feld[$a][9]."\"}";
            }
         }

         $ausgabeJSON_Ende ="]}";
      }

      // close DB connection
      $this->dbObj->close();
      
      // make JSON-Output
      if (count($ausgabeJSON_Inhalt)>0) echo $ausgabeJSON_Anfang.implode(",", $ausgabeJSON_Inhalt).$ausgabeJSON_Ende;
   }
   

   
   /**
   * Every pull refreshes the user data in the session table, etchat_useronline
   *
   * @param Array $user_array requested data from user table
   * @param Array $raum_array requested data from room table
   * @param String $user_param_all User IP data for Blacklist
   * @uses ConnectDB::sqlGet()   
   * @uses ConnectDB::sqlSet()   
   * @return void
   */
   private function refreshUserSession($user_array, $raum_array, $user_param_all){
   
      $user_onlineid = $this->dbObj->sqlGet("SELECT etchat_onlineid FROM {$this->_prefix}etchat_useronline where etchat_onlineuser_fid = ".$_SESSION['etchat_'.$this->_prefix.'user_id']);

      // if the usersession was created and is now existing
      if(is_array($user_onlineid))
         $this->dbObj->sqlSet("UPDATE {$this->_prefix}etchat_useronline SET
            etchat_onlineuser_fid = ".$user_array[0][0].",
            etchat_onlinetimestamp = ".date('U').",
            etchat_onlineip = '".$user_param_all."',
            etchat_fid_room = ".$raum_array[0][0].",
            etchat_user_online_room_goup = ".$raum_array[0][2].",
            etchat_user_online_room_name = '".$raum_array[0][1]."',
            etchat_user_online_user_name = '".$user_array[0][1]."',
            etchat_user_online_user_priv = '".$user_array[0][2]."',
            etchat_user_online_user_sex = '".$user_array[0][3]."'
            WHERE etchat_onlineid = ".$user_onlineid[0][0]);
            
      // the user session is not yet existing, so create it
      else {
         $this->dbObj->sqlSet("INSERT INTO {$this->_prefix}etchat_useronline ( etchat_onlineuser_fid, etchat_onlinetimestamp, etchat_onlineip, etchat_fid_room, etchat_user_online_room_goup, etchat_user_online_room_name, etchat_user_online_user_name, etchat_user_online_user_priv, etchat_user_online_user_sex)
            VALUES ( '".$user_array[0][0]."', ".date('U').", '".$user_param_all."', ".$raum_array[0][0].", ".$raum_array[0][2].", '".$raum_array[0][1]."', '".$user_array[0][1]."', '".$user_array[0][2]."', '".$user_array[0][3]."')");
         
         // if user shoul be invisible on enter
         if ($_SESSION['etchat_'.$this->_prefix.'invisible_on_enter'])
            $this->dbObj->sqlSet("UPDATE {$this->_prefix}etchat_useronline SET
               etchat_user_online_user_status_img = 'status_invisible', etchat_user_online_user_status_text = ''
               WHERE etchat_onlineuser_fid = ".(int)$_SESSION['etchat_'.$this->_prefix.'user_id']);
               
         /*unset($_SESSION['etchat_'.$this->_prefix.'invisible_on_enter']);*/
      }
   }

   /**
   * Get all room from DB with all information
   *
   * @uses ConnectDB::sqlGet()   
   * @uses RoomAllowed
   * @uses RoomAllowed::$room_status if the room is open/closed/pw-protected
   * @return Array
   */
   private function getRoomArray(){

      // Get room Array
      $raum_array=$this->dbObj->sqlGet("SELECT etchat_id_room, etchat_roomname, etchat_room_goup, etchat_room_message FROM {$this->_prefix}etchat_rooms where etchat_id_room =".(int)$_POST['room']);

      // Checks if the posted roomID exists now, it could be just deleted by admin
      if (!is_array($raum_array)) {
         $_POST['room'] = 1;
         $raum_array=$this->dbObj->sqlGet("SELECT etchat_id_room, etchat_roomname, etchat_room_goup, etchat_room_message FROM {$this->_prefix}etchat_rooms where etchat_id_room = 1");
      }
      else{
         // who ist allowed to visit this room
         $room_allowed=new RoomAllowed($raum_array[0][2], $raum_array[0][0]);
         if ($room_allowed->room_status!=1){
            $_POST['room'] = 1;
            unset($_POST['message']);
            $raum_array=$this->dbObj->sqlGet("SELECT etchat_id_room, etchat_roomname, etchat_room_goup FROM {$this->_prefix}etchat_rooms where etchat_id_room = 1");
         }
      }
      
      return $raum_array;
   }


   /**
   * Checks if the user is in the kicklist now
   *
   * @uses ConnectDB::sqlGet()   
   * @uses ConnectDB::sqlSet()
   * @return bool
   */
   private function checkKicklist(){   
      
      // Get all data from the kick tab
      $kicklist=$this->dbObj->sqlGet("SELECT id from {$this->_prefix}etchat_kick_user where etchat_kicked_user_id = ".$_SESSION['etchat_'.$this->_prefix.'user_id']);
      
      if (is_array($kicklist)){
         
         // delete the user from kicklist
         $this->dbObj->sqlSet("delete from {$this->_prefix}etchat_kick_user where etchat_kicked_user_id = ".$_SESSION['etchat_'.$this->_prefix.'user_id']);

         $rechte_zum_kicken=$this->dbObj->sqlGet("select etchat_userprivilegien FROM {$this->_prefix}etchat_user where etchat_user_id = ".$_SESSION['etchat_'.$this->_prefix.'user_id']);
         
         if ($rechte_zum_kicken[0][0]!="admin" && $rechte_zum_kicken[0][0]!="mod") return true;
         else return false;
      }
      else return false;
   }

   
   /**
   * Print a error message, and close db connect
   *
   * @param  string $message Outputmessage, usualy "0" (if any error)
   * @uses ConnectDB::close()
   * @return void
   */
   private function errorOutput($message=0){
      echo $message;
      $this->dbObj->close();
   }

   
   /**
   * Creates a dataset with all needed messages for the user
   *
   * @uses ConnectDB::sqlGet()   
   * @uses ConnectDB::sqlSet()
   * @return Array
   */
   private function selectMessagesForTheUser(){
         
         
      // on first message / on entrance
      $where_sys_messages = '';
      if (empty($_SESSION['etchat_'.$this->_prefix.'last_id'])) {
      
         if (isset($_SESSION['etchat_'.$this->_prefix.'sys_messages']) && !$_SESSION['etchat_'.$this->_prefix.'sys_messages']){
            $where_sys_messages = "(etchat_user_fid<>1 or (etchat_user_fid=1 and etchat_privat=".$_SESSION['etchat_'.$this->_prefix.'user_id'].")) and ";
            $this->_messages_shown_on_entrance--;
         }   
      
         // checks if the own last_id is realy the last one (new since v307-Beta10)
         $counted_ids=$this->dbObj->sqlGet("SELECT count(etchat_id) FROM {$this->_prefix}etchat_messages WHERE etchat_id > ".$_SESSION['etchat_'.$this->_prefix.'my_first_mess_id']. " and (etchat_fid_room = ".(int)$_POST['room']." or etchat_fid_room = 0) and (etchat_privat=0 or etchat_privat=".$_SESSION['etchat_'.$this->_prefix.'user_id'].")");
         if (is_array($counted_ids) && $counted_ids[0][0]>=$this->_messages_shown_on_entrance) $this->_messages_shown_on_entrance+=$counted_ids[0][0];
         
         // get all messages
         $feld=$this->dbObj->sqlGet("SELECT etchat_id, etchat_username, etchat_text, etchat_timestamp, etchat_fid_room, etchat_privat, etchat_user_id, etchat_text_css, etchat_userprivilegien, etchat_usersex
            FROM {$this->_prefix}etchat_messages, {$this->_prefix}etchat_user where (etchat_fid_room = ".(int)$_POST['room']." or etchat_fid_room = 0 or etchat_privat=".$_SESSION['etchat_'.$this->_prefix.'user_id'].") and ".$where_sys_messages."
            (etchat_privat=0 or etchat_privat=".$_SESSION['etchat_'.$this->_prefix.'user_id']." or etchat_user_fid=".$_SESSION['etchat_'.$this->_prefix.'user_id'].") and etchat_user_id=etchat_user_fid ORDER BY etchat_id DESC LIMIT ".$this->_messages_shown_on_entrance);
         
         // Set last DB id
         $_SESSION['etchat_'.$this->_prefix.'last_id'] = $feld[0][0];
         
         $feld = array_reverse($feld);
      }
      else {
         
         if (isset($_SESSION['etchat_'.$this->_prefix.'sys_messages']) && !$_SESSION['etchat_'.$this->_prefix.'sys_messages']){
            $where_sys_messages = "(etchat_user_fid<>1 or (etchat_user_fid=1 and etchat_privat=".$_SESSION['etchat_'.$this->_prefix.'user_id'].")) and ";
         }   
      
         // get all messages
         $feld=$this->dbObj->sqlGet("SELECT etchat_id, etchat_username, etchat_text, etchat_timestamp, etchat_fid_room, etchat_privat, etchat_user_id, etchat_text_css, etchat_userprivilegien, etchat_usersex
            FROM {$this->_prefix}etchat_messages, {$this->_prefix}etchat_user WHERE (etchat_fid_room = ".(int)$_POST['room']." or etchat_fid_room = 0 or etchat_privat=".$_SESSION['etchat_'.$this->_prefix.'user_id'].")
            and etchat_id > ".$_SESSION['etchat_'.$this->_prefix.'last_id']." and ".$where_sys_messages."
            (etchat_privat=0 or etchat_privat=".$_SESSION['etchat_'.$this->_prefix.'user_id']." or etchat_user_fid=".$_SESSION['etchat_'.$this->_prefix.'user_id'].")
            and etchat_user_id=etchat_user_fid ORDER BY etchat_id ");
         
         if (is_array($feld)) $_SESSION['etchat_'.$this->_prefix.'last_id']= $feld[(count($feld)-1)][0];
         else
         // DE
         // Das ist wichtig hier die last_id aus der DB auszulesen sogar wenn für das Raum in bem sich der User befindet keine
         // neuen Messages gab. Sonst bleibt das last_id das alte und beim Raumwechsel kanns passieren, dass alle sonstigen Messages
         // aus dem Raum in den gewächselt wurde, ausgegeben werden.
         
         // EN
         // It is importent to get the last_id from the DB, even there is no messges for the user. Othewise it kan happen that
         // when the user is going to the other chat room hi's got all messges from this room
         {
            $id=$this->dbObj->sqlGet("SELECT etchat_id FROM {$this->_prefix}etchat_messages ORDER BY etchat_id DESC LIMIT 1");
            $_SESSION['etchat_'.$this->_prefix.'last_id']=$id[0][0];
         }
      }
      return $feld;
   }


   /**
   * Blocking if the opponent user that is in the blocklist of user own session
   *
   * @param int $user_id
   * @param int $privat_id
   * @return void
   */
   private function blockiere($user_id, $privat_id){
      if (isset ($_SESSION['etchat_'.$this->_prefix.'block_all']) && is_array ($_SESSION['etchat_'.$this->_prefix.'block_all']) && in_array($user_id, $_SESSION['etchat_'.$this->_prefix.'block_all'])) {
         return true;
      }
      
      if (isset ($_SESSION['etchat_'.$this->_prefix.'block_priv']) && is_array ($_SESSION['etchat_'.$this->_prefix.'block_priv']) && in_array($user_id, $_SESSION['etchat_'.$this->_prefix.'block_priv']) && $privat_id==$_SESSION['etchat_'.$this->_prefix.'user_id'])  {
         return true;
      }
   }

   
}


Getestet mit dem ET-Chat-v3.0.7-r3-PHP-8-b

War dieses Tutorial hilfreich für dich?
Nur Mitglieder können abstimmen!
Für 1 der Mitglieder war es hilfreich.
Für 0 der Mitglieder nicht.


Adventkranz
In 5 Tagen ist Heiligabend
Login
Name oder Email

Passwort



Noch kein Mitglied?
Klicke hier um dich zu registrieren

Passwort vergessen?
Um ein neues Passwort anzufordern klicke hier.
Wer ist im Chat?
Gäste willkommen!

0 User im Chat
Teamspeak
Harlekins Welt
Eingangshalle
« ★ » Allgemein « ★ »
Laberecke
Quasselbox
Up & Download
« ❑ » Intern « ❑ »
Besprechung
« ● » Abwesend « ● »
kurz < 30 Min.
lang > 30 Min.

Discord

Joinen
Slider
Security
Geschützt durch:
HP-Detect
Werbung
R8HL GERMANY

Über HP-4-Fun

HP-4-Fun

ist ein privates, nicht kommerzielles, Projekt, welches 2019 von Rolly8-HL und mir (Harlekin) gestartet wurde.

HP-4-Fun 2.0 ist nur für den Eigenbedarf geschrieben worden. Ein Downloadpaket von HP-4-Fun 2.0 wird es nicht geben!

Letzte Kommentare

Informationen

Zuletzt Online