<?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 StaticMethods
{
    public static function filtering($str, $sml, $_prefix)
    {
        $count_all = 0;

        // Steuerzeichen entfernen
        $str = preg_replace('/[\x00-\x1F]/', '', $str);

        // Smilies ersetzen
        foreach ($sml as $smiley) {
            $path = "./" . $smiley[1];
            if (is_file($path) && ($img = getimagesize($path))) {
                $str = str_replace(
                    $smiley[0],
                    "<img class=\"img_smiley\" src=\"{$smiley[1]}\" {$img[3]} id=\"smilchat_{$smiley[0]}\" style=\"cursor:pointer\">",
                    $str,
                    $count
                );
                if ($count > 0) {
                    $count_all += $count;
                }
            }
        }

        $max_smilies = (int)($_SESSION['etchat_' . $_prefix . 'chat_anzsmily'] ?? 6);
        if ($count_all > $max_smilies) {
            return "Max $max_smilies Smilies erlaubt!";
        }

        // Externe Links erkennen
        if (stripos($str, ']http://') === false && stripos($str, ']https://') === false) {
            $str = preg_replace(
                "/([\w]+:\/\/[\w\-?&;#~=\.\/\@]+[\w\/])/i",
                "<a target=\"_blank\" href=\"?Weiterleitung&url=$1\">Externer Link</a>",
                $str
            );
        }

        // [pvi] Bilder
        $str = preg_replace(
            '/\[pvi\](.*?)\[\/pvi\]/',
            "&nbsp;&nbsp;<a href=\"$1\" target=\"_blank\"><img class=\"img_chat\" src=\"$1\" alt=\"Bild gepostet\" title=\"Klicken, um das Bild zu vergrößern.\"/></a>",
            $str
        );

        // Bad Words laden
        if (!isset($_SESSION['etchat_' . $_prefix . '_badwords']) && file_exists("./lang/bad_words.xml")) {
            $xml = simplexml_load_file("./lang/bad_words.xml", 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOERROR | LIBXML_NOWARNING);
            if ($xml) {
                foreach ($xml->word as $bword) {
                    $exceptions = [];
                    if (isset($bword->except)) {
                        foreach ($bword->except as $except) {
                            $exceptions[] = trim((string)$except);
                        }
                    }
                    $_SESSION['etchat_' . $_prefix . '_badwords'][] = [
                        'in'     => trim((string)$bword['in']),
                        'out'    => trim((string)$bword['out']),
                        'except' => $exceptions
                    ];
                }
            }
        }

        // Bad Words anwenden
        if (isset($_SESSION['etchat_' . $_prefix . '_badwords'])) {
            foreach ($_SESSION['etchat_' . $_prefix . '_badwords'] as $bword) {
                if (!empty($bword['except'])) {
                    foreach ($bword['except'] as $ex) {
                        $str = str_replace($ex, "<norepl>{$ex}</norepl>", $str);
                    }
                }
            }

            foreach ($_SESSION['etchat_' . $_prefix . '_badwords'] as $bword) {
                $pattern = '/(?<!\<norepl\>)' . preg_quote($bword['in'], '/') . '(?!\<\/norepl\>)/ui';
                $str = preg_replace($pattern, $bword['out'], $str);
            }

            $str = str_ireplace(["<norepl>", "</norepl>"], "", $str);
        }

        // Video Embed (nur [video] BBCode)
        if (substr($str, 0, 8) !== "/window:") {

            // [img] BBCode
            if (stripos($str, '[img]') !== false && stripos($str, '[/img]') !== false && stripos($str, '?admin') === false) {
                $str = preg_replace(
                    '#\[img\](.*?)\[/img\]#i',
                    '<a href="$1" target="_blank"><img class="img_chat" src="$1" alt="Bild gepostet" title="Klicken, um das Bild zu vergrößern."/></a>',
                    $str
                );
            }

            // [video] BBCode mit YouTube, Dailymotion, Twitch VOD, TikTok
            $str = preg_replace_callback('/\[video\](.*?)\[\/video\]/i', function($matches){
                $url = trim($matches[1]);
                $embed = $url;

                // YouTube
                if (preg_match('~(?:https?://)?(?:www\.)?(?:youtube\.com/watch\?v=|youtu\.be/)([\w-]+)~i', $url, $m)) {
                    $embed = 'https://www.youtube.com/embed/' . $m[1];
                }
                // Dailymotion
                elseif (preg_match('~(?:https?://)?(?:www\.)?dailymotion\.com/video/([\w-]+)~i', $url, $m)) {
                    $embed = 'https://www.dailymotion.com/embed/video/' . $m[1];
                }
                // Twitch VOD
                elseif (preg_match('~(?:https?://)?(?:www\.)?twitch\.tv/videos/(\d+)~i', $url, $m)) {
                    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
                    $embed = 'https://player.twitch.tv/?video=' . $m[1] . '&parent=' . $host;
                }
                // TikTok
                elseif (preg_match('~(?:https?://)?(?:www\.)?tiktok\.com/.+/video/(\d+)~i', $url, $m)) {
                    $embed = 'https://www.tiktok.com/embed/' . $m[1];
                }

                return '<iframe width="425" height="344" src="' . $embed . '" frameborder="0" allowfullscreen></iframe>';
            }, $str);
        }

        return $str;
    }
}