From 3a52b1dfd11d12f5de387d63cd804de29586ce1b Mon Sep 17 00:00:00 2001 From: Marisa Kirisame Date: Mon, 23 Nov 2026 13:19:19 +0000 Subject: [PATCH] Add ChatFilter2, OverheadChat, EventGreeting and update several plugins New plugins: ChatFilter2, OverheadChat, EventGreeting. Updated: HostnameManager, Leader3 (chat and markers), NameFilter2 (plugin and config), PlayerRankings_nohlstats (rank display modes), custom-chatcolors (plugin and ccc.inc), Extend (sm_settimeleft). Add shared includes the plugins build against: Break, ChatFilter2, Couch, EventNotifier, TransmitManager, leader, ripext, unloze_playtime. --- ChatFilter2/configs/ChatFilter2.cfg | 582 +++++++ ChatFilter2/scripting/ChatFilter2.sp | 1339 +++++++++++++++++ ChatFilter2/scripting/include/ChatFilter2.inc | 50 + EventGreeting/scripting/EventGreeting.sp | 606 ++++++++ Extend/scripting/Extend.sp | 48 + HostnameManager/scripting/HostnameManager.sp | 228 ++- Leader3/scripting/Leader3.sp | 43 +- Leader3/scripting/leader3/chat.sp | 23 + Leader3/scripting/leader3/markers.sp | 117 +- NameFilter2/configs/NameFilter2.cfg | 121 +- NameFilter2/scripting/NameFilter2.sp | 548 ++++++- OverheadChat/scripting/OverheadChat.sp | 1046 +++++++++++++ .../scripting/PlayerRankings_nohlstats.sp | 221 ++- .../scripting/custom-chatcolors.sp | 204 ++- custom-chatcolors/scripting/include/ccc.inc | 16 +- includes/Break.inc | 51 + includes/ChatFilter2.inc | 50 + includes/Couch.inc | 1 + includes/EventNotifier.inc | 159 ++ includes/TransmitManager.inc | 30 + includes/leader.inc | 90 ++ includes/ripext.inc | 26 + includes/ripext/http.inc | 359 +++++ includes/ripext/json.inc | 400 +++++ includes/unloze_playtime.inc | 26 + 25 files changed, 6209 insertions(+), 175 deletions(-) create mode 100644 ChatFilter2/configs/ChatFilter2.cfg create mode 100644 ChatFilter2/scripting/ChatFilter2.sp create mode 100644 ChatFilter2/scripting/include/ChatFilter2.inc create mode 100644 EventGreeting/scripting/EventGreeting.sp create mode 100644 OverheadChat/scripting/OverheadChat.sp create mode 100644 includes/Break.inc create mode 100644 includes/ChatFilter2.inc create mode 120000 includes/Couch.inc create mode 100644 includes/EventNotifier.inc create mode 100644 includes/TransmitManager.inc create mode 100644 includes/leader.inc create mode 100644 includes/ripext.inc create mode 100644 includes/ripext/http.inc create mode 100644 includes/ripext/json.inc create mode 100644 includes/unloze_playtime.inc diff --git a/ChatFilter2/configs/ChatFilter2.cfg b/ChatFilter2/configs/ChatFilter2.cfg new file mode 100644 index 0000000..a2656bd --- /dev/null +++ b/ChatFilter2/configs/ChatFilter2.cfg @@ -0,0 +1,582 @@ +"ChatFilter2" +{ + // a message containing any of these is hidden from players with "Hiding Lennies" on. + // key = the character or substring (raw UTF-8), value unused + "lennies" + { + "°" "" + "ಠ" "" + "⚆" "" + "ʖ" "" + "͡" "" + "͜" "" + } + + // ASCII digits/symbols read as letters when matching bad words ("sh1t", "$hit", "a$$"). + // key = one ASCII digit or symbol, value = the letter it stands for. + // symbols at the start or end of a word may also just be punctuation ("shit!"), + // so words are tried both with and without them + "leet" + { + "4" "a" + "@" "a" + "3" "e" + "1" "i" + "!" "i" + "|" "i" + "0" "o" + "5" "s" + "$" "s" + "7" "t" + } + + // non-ASCII lookalikes read as ASCII letters when matching bad words. + // key = one character (raw UTF-8), value = one ASCII letter (case does not matter). + // any other non-ASCII character splits words. Lookalikes copied from NameFilter2.cfg + "confusables" + { + // Cyrillic lowercase + "а" "a" + "е" "e" + "о" "o" + "р" "p" + "с" "c" + "у" "y" + "х" "x" + "і" "i" + "ѕ" "s" + "ј" "j" + // Cyrillic uppercase + "А" "A" + "В" "B" + "Е" "E" + "К" "K" + "М" "M" + "Н" "H" + "О" "O" + "Р" "P" + "С" "C" + "Т" "T" + "Х" "X" + "Ѕ" "S" + "І" "I" + "Ј" "J" + "У" "Y" + "З" "3" + // Cyrillic mirrored/aesthetic lookalikes + "Я" "R" + "я" "r" + "И" "N" + "и" "n" + "в" "b" + "к" "k" + "м" "m" + "н" "h" + "т" "t" + // Cyrillic with diacritics, same lookalikes as their base letters + "Ѐ" "E" + "Ё" "E" + "ѐ" "e" + "ё" "e" + "Ї" "I" + "ї" "i" + "Ў" "Y" + "ў" "y" + "Ѝ" "N" + "Й" "N" + "ѝ" "n" + "й" "n" + // Greek + "Α" "A" + "Β" "B" + "Ε" "E" + "Ζ" "Z" + "Η" "H" + "Ι" "I" + "Κ" "K" + "Μ" "M" + "Ν" "N" + "Ο" "O" + "Ρ" "P" + "Τ" "T" + "Υ" "Y" + "Χ" "X" + "α" "a" + "ν" "v" + "ο" "o" + // Greek with tonos/dialytika, same lookalikes as their base letters + "Ά" "A" + "Έ" "E" + "Ή" "H" + "Ί" "I" + "Ϊ" "I" + "Ό" "O" + "Ύ" "Y" + "Ϋ" "Y" + "Ώ" "O" + "ά" "a" + "ή" "n" + "ό" "o" + "ώ" "w" + // Greek aesthetic lookalikes + "Λ" "A" + "Σ" "E" + "Δ" "A" + "Ω" "O" + "Θ" "O" + "θ" "o" + "μ" "u" + "ω" "w" + "η" "n" + // math symbols used as letters + "∂" "d" + "∑" "E" + // accented Latin, read as the base letter + "À" "a" + "Á" "a" + "Â" "a" + "Ã" "a" + "Ä" "a" + "Å" "a" + "Ç" "c" + "È" "e" + "É" "e" + "Ê" "e" + "Ë" "e" + "Ì" "i" + "Í" "i" + "Î" "i" + "Ï" "i" + "Ñ" "n" + "Ò" "o" + "Ó" "o" + "Ô" "o" + "Õ" "o" + "Ö" "o" + "Ù" "u" + "Ú" "u" + "Û" "u" + "Ü" "u" + "Ý" "y" + "à" "a" + "á" "a" + "â" "a" + "ã" "a" + "ä" "a" + "å" "a" + "ç" "c" + "è" "e" + "é" "e" + "ê" "e" + "ë" "e" + "ì" "i" + "í" "i" + "î" "i" + "ï" "i" + "ñ" "n" + "ò" "o" + "ó" "o" + "ô" "o" + "õ" "o" + "ö" "o" + "ù" "u" + "ú" "u" + "û" "u" + "ü" "u" + "ý" "y" + "ÿ" "y" + "Ā" "a" + "ā" "a" + "Ă" "a" + "ă" "a" + "Ą" "a" + "ą" "a" + "Ć" "c" + "ć" "c" + "Ĉ" "c" + "ĉ" "c" + "Ċ" "c" + "ċ" "c" + "Č" "c" + "č" "c" + "Ď" "d" + "ď" "d" + "Ē" "e" + "ē" "e" + "Ĕ" "e" + "ĕ" "e" + "Ė" "e" + "ė" "e" + "Ę" "e" + "ę" "e" + "Ě" "e" + "ě" "e" + "Ĝ" "g" + "ĝ" "g" + "Ğ" "g" + "ğ" "g" + "Ġ" "g" + "ġ" "g" + "Ģ" "g" + "ģ" "g" + "Ĥ" "h" + "ĥ" "h" + "Ĩ" "i" + "ĩ" "i" + "Ī" "i" + "ī" "i" + "Ĭ" "i" + "ĭ" "i" + "Į" "i" + "į" "i" + "İ" "i" + "Ĵ" "j" + "ĵ" "j" + "Ķ" "k" + "ķ" "k" + "Ĺ" "l" + "ĺ" "l" + "Ļ" "l" + "ļ" "l" + "Ľ" "l" + "ľ" "l" + "Ń" "n" + "ń" "n" + "Ņ" "n" + "ņ" "n" + "Ň" "n" + "ň" "n" + "Ō" "o" + "ō" "o" + "Ŏ" "o" + "ŏ" "o" + "Ő" "o" + "ő" "o" + "Ŕ" "r" + "ŕ" "r" + "Ŗ" "r" + "ŗ" "r" + "Ř" "r" + "ř" "r" + "Ś" "s" + "ś" "s" + "Ŝ" "s" + "ŝ" "s" + "Ş" "s" + "ş" "s" + "Š" "s" + "š" "s" + "Ţ" "t" + "ţ" "t" + "Ť" "t" + "ť" "t" + "Ũ" "u" + "ũ" "u" + "Ū" "u" + "ū" "u" + "Ŭ" "u" + "ŭ" "u" + "Ů" "u" + "ů" "u" + "Ű" "u" + "ű" "u" + "Ų" "u" + "ų" "u" + "Ŵ" "w" + "ŵ" "w" + "Ŷ" "y" + "ŷ" "y" + "Ÿ" "y" + "Ź" "z" + "ź" "z" + "Ż" "z" + "ż" "z" + "Ž" "z" + "ž" "z" + } + + // bad words censored for players with safe chat on, one '*' per character. + // Each section below is a category; key = the word or phrase, value unused. + // Case-insensitive, leet and confusables are applied, and repeated letters match + // ("fuuuck" matches "fuck", but "as" does not match "ass"). + // A plain word only matches a whole word. "*word*" also matches inside a word + // (censoring just that part), "word*" only at the start, "*word" only at the end. + // Entries with spaces are phrases: each word must be a whole word, in order, with any + // spaces or punctuation between them ("kill yourself" matches "KILL... yourself!!" but not + // "killyourself", which needs its own entry); '*' is allowed at the start of the first word + // and the end of the last. + // Words spelled out with one letter per word ("f u c k", "f.u.c.k") are joined and matched too. + // List built 2026-10-22 from 366k ZE chat lines (UNLOZE stats DB + 200 UNLOZE/NiDE SourceTV demos). + "words" + { + // slurs and hate + "slurs" + { + // n-word; "*nigg*" covers nigger/nigga/niggas and joined forms like "sandnigger" + "*nigg*" "" + "nig" "" + "nigs" "" + "niga" "" + "nigas" "" + "niger" "" + "nigers" "" + "nige" "" + "nignog*" "" + "negro" "" + "negros" "" + "negroes" "" + // homophobic + "*fag*" "" + "homo" "" + "homos" "" + "tranny" "" + "trannies" "" + "troon*" "" + "dyke" "" + "dykes" "" + "pidor*" "" + "pidar*" "" + "pidr*" "" + "maricon*" "" + "viado*" "" + "schwuchtel*" "" + // ableist + "*retard*" "" + "tard" "" + "tards" "" + "fucktard*" "" + "mongoloid*" "" + "spastic*" "" + // racial and ethnic + "kike" "" + "kikes" "" + "chink" "" + "chinks" "" + "spic" "" + "spics" "" + "gook" "" + "gooks" "" + "coon" "" + "coons" "" + "wetback*" "" + "beaner*" "" + "towelhead*" "" + "raghead*" "" + "paki" "" + "pakis" "" + "pajeet*" "" + // nazi + "heil hitler" "" + "sieg heil" "" + "1488" "" + "white power" "" + "gas the jews" "" + } + + // general profanity, English then other Latin-script languages + "profanity" + { + "*fuck*" "" + "fuk*" "" + "dafuk" "" + "phuck*" "" + "fck*" "" + "fk" "" + "fks" "" + "fking" "" + "fkin" "" + "fkn" "" + "fkng" "" + "fked" "" + "fker*" "" + "idfk" "" + "stfu" "" + "gtfo" "" + "*shit*" "" + "*bitch*" "" + "*cunt*" "" + "ass" "" + "asses" "" + "arse" "" + "*asshole*" "" + "dumbass*" "" + "fatass*" "" + "jackass*" "" + "smartass*" "" + "bastard*" "" + "*wanker*" "" + "twat*" "" + "prick" "" + "pricks" "" + "bollocks" "" + "tosser*" "" + "piss" "" + "pissed" "" + "pissing" "" + "*whore*" "" + "*slut*" "" + "hoe" "" + "hoes" "" + "motherf*" "" + "mothafuck*" "" + // Arabic, transliterated + "sharmut*" "" + // Russian, transliterated + "cyka" "" + "suka" "" + "blyat*" "" + "blyad*" "" + "blya" "" + "pizda*" "" + "pizdec*" "" + "pizdets*" "" + "nahui" "" + "nahuy" "" + "nahuj" "" + "zaebal*" "" + "eblan*" "" + "ebat" "" + "yebat*" "" + // Polish + "kurwa*" "" + "kurwy" "" + "chuj*" "" + "jebac*" "" + "jebany*" "" + "jebane" "" + "pierdol*" "" + "spierdalaj*" "" + "cipa" "" + // Czech, Hungarian, Serbo-Croatian, Finnish + "kurva" "" + "kurac" "" + "jebem*" "" + "vittu" "" + // Spanish, Portuguese + "puta" "" + "putas" "" + "puto" "" + "putos" "" + "hijueputa" "" + "mierda" "" + "pendejo*" "" + "cabron*" "" + "joder" "" + "verga" "" + "porra" "" + "caralho" "" + "fdp" "" + "merda" "" + // German + "scheisse" "" + "scheiss" "" + "hurensohn*" "" + "fotze" "" + "wichser" "" + "arschloch*" "" + "missgeburt" "" + // French + "putain" "" + "merde" "" + "connard*" "" + "connasse" "" + "salope*" "" + "encule*" "" + "ntm" "" + // Turkish + "amk" "" + "aq" "" + "orospu*" "" + "siktir*" "" + "sikerim" "" + "sikeyim" "" + "yarrak*" "" + } + + // telling someone to die or hurt themselves + "harassment" + { + "kys" "" + "killyourself" "" + "killurself" "" + "kill yourself" "" + "kill yourselves" "" + "kill urself" "" + "kill your self" "" + "kill ur self" "" + "kill yaself" "" + "neck yourself" "" + "neck urself" "" + "hang yourself" "" + "hang urself" "" + "go die" "" + "hope you die" "" + "hope u die" "" + "die in a fire" "" + "get cancer" "" + "get aids" "" + "drink bleach" "" + "get raped" "" + } + + // sexual terms + "sexual" + { + "dick" "" + "dicks" "" + "*dickhead*" "" + "cock" "" + "cocks" "" + "*cocksucker*" "" + "pussy*" "" + "pussi*" "" + "cum" "" + "cums" "" + "cumming" "" + "cuming" "" + "cumshot*" "" + "*cumslut*" "" + "jizz*" "" + "rape*" "" + "raping" "" + "rapist*" "" + "earape*" "" + "porn*" "" + "hentai" "" + "penis*" "" + "vagina*" "" + "tits" "" + "titties" "" + "boob" "" + "boobs" "" + "boobies" "" + "anal" "" + "dildo*" "" + "blowjob*" "" + "handjob*" "" + "horny" "" + "fap*" "" + "milf*" "" + "orgasm*" "" + "masturbat*" "" + "jerk off" "" + "jerking off" "" + "jack off" "" + "buceta" "" + } + } + + // never censored even when a wildcard above hits them: a bad word found entirely inside + // the part of a word an allow entry matches is skipped. Same syntax as the words, no phrases. + "allow" + { + "*snigger*" "" + "scunthorpe" "" + "shiitake*" "" + "rapeseed*" "" + "rapping" "" + "rapper*" "" + "assess*" "" + "yashito" "" + } +} diff --git a/ChatFilter2/scripting/ChatFilter2.sp b/ChatFilter2/scripting/ChatFilter2.sp new file mode 100644 index 0000000..cc5894e --- /dev/null +++ b/ChatFilter2/scripting/ChatFilter2.sp @@ -0,0 +1,1339 @@ +#pragma semicolon 1 +#pragma newdecls required +#pragma dynamic 16384 // CensorMessage/CensorRange keep per-character arrays on the stack + +#define CHATFILTER2_CORE + +#include +#include +#include +#include +#include + +#define CHAT_PREFIX "{cyan}[ChatFilter] {white}" +#define MAX_CENSOR_LENGTH 256 +#define MAX_WORD_RUNS 32 +#define MAX_CATEGORIES 32 // categories are bits in an int mask +#define MAX_PHRASE_WORDS 8 +#define MAX_ALLOWED_SPANS 16 +#define MIN_SPACED_LETTERS 3 // "f u c k": this many one-letter words in a row are joined + +#define FILTER_LENNIES 0 +#define FILTER_COMMANDS 1 +#define FILTER_CHAT 2 +#define FILTER_SAFECHAT 3 +#define FILTER_COUNT 4 + +// cookie names are shared with the old ChatFilter so players keep their settings +char g_sCookieNames[FILTER_COUNT][] = {"lennies_blocked", "commands_blocked", "chat_blocked", "safechat_enabled"}; +char g_sCookieDescs[FILTER_COUNT][] = {"are lennies blocked", "are commands blocked", "are messages from others players blocked", "are bad words censored"}; +char g_sMenuLabels[FILTER_COUNT][] = {"Hiding Lennies", "Hiding Commands", "Hiding all Messages", "Safe Chat"}; +char g_sEnabledMsgs[FILTER_COUNT][] = {"Lennies are now hidden.", "Commands are now hidden.", "Messages from all Players are now hidden.", "Safe chat enabled, bad words are now censored."}; +char g_sDisabledMsgs[FILTER_COUNT][] = {"Lennies are not hidden anymore.", "Commands are not hidden anymore.", "Messages from all Players are not hidden anymore.", "Safe chat disabled, bad words are not censored anymore."}; + +// used when the config is missing +char g_sDefaultLennies[][] = {"°", "ಠ", "⚆", "ʖ"}; + +// a config word, normalised to runs of equal characters ("fuck" -> f1 u1 c1 k1, "ass" -> a1 s2) +enum struct BadWord +{ + bool bAnyStart; // "*word": may start inside a token + bool bAnyEnd; // "word*": may end inside a token + int iRuns; + int iChar[MAX_WORD_RUNS]; + int iCount[MAX_WORD_RUNS]; + int iNext; // next whole word with the same letters, -1 ends the chain + int iCategory; // index into g_Categories, unused for allow words +} + +// "kill yourself": its words are g_PhraseWords[iFirst .. iFirst + iWords - 1] +enum struct Phrase +{ + int iFirst; + int iWords; + int iCategory; +} + +bool g_bFilter[MAXPLAYERS + 1][FILTER_COUNT]; +Handle g_hCookies[FILTER_COUNT]; +GlobalForward g_fwdOnSafeChatChanged; + +ArrayList g_Lennies; +ArrayList g_Categories; // category names, a word's category bit is 1 << index +ArrayList g_WholeWords; // BadWord +StringMap g_WholeWordHeads; // run letters -> first g_WholeWords index with them +ArrayList g_WildWords; // BadWord +ArrayList g_Phrases; // Phrase +ArrayList g_PhraseWords; // BadWord +ArrayList g_AllowWords; // BadWord, whole words of the allow list +StringMap g_AllowWordHeads; // run letters -> first g_AllowWords index with them +ArrayList g_AllowWildWords; // BadWord +StringMap g_Confusables; // codepoint -> ASCII letter +int g_iLeet[128]; // ASCII symbol/digit -> letter, 0 if none + +//---------------------------------------------------------------------------------------------------- +// Purpose: +//---------------------------------------------------------------------------------------------------- +public Plugin myinfo = +{ + name = "ChatFilter2", + author = "marisakirisame.net", + description = "Makes it possible to selfmute several things in chat and censor bad words", + version = "1.0" +} + +//---------------------------------------------------------------------------------------------------- +// Purpose: +//---------------------------------------------------------------------------------------------------- +public APLRes AskPluginLoad2(Handle myself, bool late, char[] error, int err_max) +{ + CreateNative("ChatFilter2_CensorText", Native_CensorText); + CreateNative("ChatFilter2_IsSafeChatEnabled", Native_IsSafeChatEnabled); + RegPluginLibrary("ChatFilter2"); + return APLRes_Success; +} + +//---------------------------------------------------------------------------------------------------- +// Purpose: +//---------------------------------------------------------------------------------------------------- +public void OnPluginStart() +{ + g_fwdOnSafeChatChanged = new GlobalForward("ChatFilter2_OnSafeChatChanged", ET_Ignore, Param_Cell, Param_Cell); + + RegConsoleCmd("sm_cf", OnToggleSettings, "ChatFilter Settings"); + RegConsoleCmd("sm_chatfilter", OnToggleSettings, "ChatFilter Settings"); + RegConsoleCmd("sm_hide_lennies", OnToggleLennies, "Toggle blocking Lennies"); + RegConsoleCmd("sm_hide_commands", OnToggleCommands, "Toggle blocking Commands"); + RegConsoleCmd("sm_hide_chat", OnToggleChat, "Toggle blocking other players Messages"); + RegConsoleCmd("sm_safechat", OnToggleSafeChat, "Toggle censoring bad words"); + RegAdminCmd("sm_chatfilter2_reload", Command_Reload, ADMFLAG_CONFIG, "Reloads the ChatFilter2 config"); + RegAdminCmd("sm_chatfilter2_test", Command_Test, ADMFLAG_CONFIG, "Shows how safe chat censors a message"); + + for(int i = 0; i < FILTER_COUNT; i++) + g_hCookies[i] = RegClientCookie(g_sCookieNames[i], g_sCookieDescs[i], CookieAccess_Protected); + + SetCookieMenuItem(MenuHandler_CookieMenu, 0, "ChatFilter"); + + LoadConfig(); + + for(int client = 1; client <= MaxClients; client++) + { + if(IsClientInGame(client) && AreClientCookiesCached(client)) + OnClientCookiesCached(client); + } +} + +//---------------------------------------------------------------------------------------------------- +// Purpose: +//---------------------------------------------------------------------------------------------------- +public Action OnToggleSettings(int client, int args) +{ + if(client) + ShowSettingsMenu(client); + return Plugin_Handled; +} + +public Action OnToggleLennies(int client, int args) +{ + if(client) + ToggleFilter(client, FILTER_LENNIES); + return Plugin_Handled; +} + +public Action OnToggleCommands(int client, int args) +{ + if(client) + ToggleFilter(client, FILTER_COMMANDS); + return Plugin_Handled; +} + +public Action OnToggleChat(int client, int args) +{ + if(client) + ToggleFilter(client, FILTER_CHAT); + return Plugin_Handled; +} + +public Action OnToggleSafeChat(int client, int args) +{ + if(client) + ToggleFilter(client, FILTER_SAFECHAT); + return Plugin_Handled; +} + +public Action Command_Reload(int client, int args) +{ + LoadConfig(); + ReplyToCommand(client, "[SM] ChatFilter2 config reloaded: %d words, %d wildcard words, %d phrases in %d categories, %d allowed, %d lennies.", + g_WholeWords.Length, g_WildWords.Length, g_Phrases.Length, g_Categories.Length, g_AllowWords.Length + g_AllowWildWords.Length, g_Lennies.Length); + return Plugin_Handled; +} + +public Action Command_Test(int client, int args) +{ + char sMessage[MAX_CENSOR_LENGTH]; + GetCmdArgString(sMessage, sizeof(sMessage)); + StripQuotes(sMessage); + + int iMatched; + if(!CensorMessage(sMessage, sizeof(sMessage), -1, iMatched)) + { + ReplyToCommand(client, "[SM] Not censored: %s", sMessage); + return Plugin_Handled; + } + + char sCategories[256]; + char sName[64]; + for(int i = 0; i < g_Categories.Length; i++) + { + if(!(iMatched & (1 << i))) + continue; + + g_Categories.GetString(i, sName, sizeof(sName)); + if(sCategories[0]) + StrCat(sCategories, sizeof(sCategories), ", "); + StrCat(sCategories, sizeof(sCategories), sName); + } + + ReplyToCommand(client, "[SM] Censored (%s): %s", sCategories, sMessage); + return Plugin_Handled; +} + +//---------------------------------------------------------------------------------------------------- +// Purpose: +//---------------------------------------------------------------------------------------------------- +void ShowSettingsMenu(int client) +{ + Menu menu = new Menu(MenuHandler_MainMenu); + + menu.SetTitle("ChatFilter Settings", client); + + char sBuffer[128]; + char sInfo[4]; + + for(int i = 0; i < FILTER_COUNT; i++) + { + Format(sBuffer, sizeof(sBuffer), "%s: %s", g_sMenuLabels[i], g_bFilter[client][i] ? "Enabled" : "Disabled"); + IntToString(i, sInfo, sizeof(sInfo)); + menu.AddItem(sInfo, sBuffer); + } + + menu.ExitBackButton = true; + + menu.Display(client, MENU_TIME_FOREVER); +} + +//---------------------------------------------------------------------------------------------------- +// Purpose: +//---------------------------------------------------------------------------------------------------- +public void MenuHandler_CookieMenu(int client, CookieMenuAction action, any info, char[] buffer, int maxlen) +{ + switch(action) + { + case(CookieMenuAction_DisplayOption): + { + Format(buffer, maxlen, "ChatFilter", client); + } + case(CookieMenuAction_SelectOption): + { + ShowSettingsMenu(client); + } + } +} + +//---------------------------------------------------------------------------------------------------- +// Purpose: +//---------------------------------------------------------------------------------------------------- +public int MenuHandler_MainMenu(Menu menu, MenuAction action, int client, int selection) +{ + switch(action) + { + case(MenuAction_Select): + { + ToggleFilter(client, selection); + ShowSettingsMenu(client); + } + case(MenuAction_Cancel): + { + if(selection == MenuCancel_ExitBack) + ShowCookieMenu(client); + } + case(MenuAction_End): + { + delete menu; + } + } + + return 0; +} + +//---------------------------------------------------------------------------------------------------- +// Purpose: +//---------------------------------------------------------------------------------------------------- +public Action CCC_OnChatMessage(int client, int author, const char[] message) +{ + // never filter a player's own messages + if(client == author) + return Plugin_Continue; + + if(g_bFilter[client][FILTER_CHAT]) + return Plugin_Handled; + + if(g_bFilter[client][FILTER_COMMANDS] && IsCommandMessage(message)) + return Plugin_Handled; + + if(g_bFilter[client][FILTER_LENNIES] && HasLenny(message)) + return Plugin_Handled; + + // ask CCC for the rewritten copy, see CCC_OnChatMessageRewrite + if(g_bFilter[client][FILTER_SAFECHAT] && (g_WholeWords.Length || g_WildWords.Length || g_Phrases.Length)) + return Plugin_Changed; + + return Plugin_Continue; +} + +//---------------------------------------------------------------------------------------------------- +// Purpose: called once per message when a recipient has safe chat enabled +//---------------------------------------------------------------------------------------------------- +public Action CCC_OnChatMessageRewrite(int author, char[] message, int maxlen) +{ + return CensorMessage(message, maxlen) ? Plugin_Changed : Plugin_Continue; +} + +//---------------------------------------------------------------------------------------------------- +// Purpose: +//---------------------------------------------------------------------------------------------------- +void ToggleFilter(int client, int filter) +{ + if(filter < 0 || filter >= FILTER_COUNT) + return; + + g_bFilter[client][filter] = !g_bFilter[client][filter]; + + SetClientCookie(client, g_hCookies[filter], g_bFilter[client][filter] ? "1" : ""); + + if(g_bFilter[client][filter]) + CPrintToChat(client, CHAT_PREFIX ... "%s", g_sEnabledMsgs[filter]); + else + CPrintToChat(client, CHAT_PREFIX ... "%s", g_sDisabledMsgs[filter]); + + if(filter == FILTER_SAFECHAT) + FireSafeChatChanged(client); +} + +void FireSafeChatChanged(int client) +{ + Call_StartForward(g_fwdOnSafeChatChanged); + Call_PushCell(client); + Call_PushCell(g_bFilter[client][FILTER_SAFECHAT]); + Call_Finish(); +} + +//---------------------------------------------------------------------------------------------------- +// Purpose: +//---------------------------------------------------------------------------------------------------- +public void OnClientCookiesCached(int client) +{ + char sBuffer[2]; + + for(int i = 0; i < FILTER_COUNT; i++) + { + GetClientCookie(client, g_hCookies[i], sBuffer, sizeof(sBuffer)); + g_bFilter[client][i] = sBuffer[0] != '\0'; + } + + // listeners start every client as off, so only a change needs telling + if(g_bFilter[client][FILTER_SAFECHAT]) + FireSafeChatChanged(client); +} + +//---------------------------------------------------------------------------------------------------- +// Purpose: natives +//---------------------------------------------------------------------------------------------------- +public int Native_CensorText(Handle plugin, int numParams) +{ + int maxlen = GetNativeCell(2); + + // CensorMessage skips messages this long; a truncated copy must not be written back + int len; + GetNativeStringLength(1, len); + if(len >= MAX_CENSOR_LENGTH) + return false; + + char sText[MAX_CENSOR_LENGTH]; + GetNativeString(1, sText, sizeof(sText)); + + if(!CensorMessage(sText, sizeof(sText))) + return false; + + SetNativeString(1, sText, maxlen); + return true; +} + +public int Native_IsSafeChatEnabled(Handle plugin, int numParams) +{ + int client = GetNativeCell(1); + if(client < 1 || client > MaxClients) + return false; + + return g_bFilter[client][FILTER_SAFECHAT]; +} + +//---------------------------------------------------------------------------------------------------- +// Purpose: +//---------------------------------------------------------------------------------------------------- +public void OnClientDisconnect(int client) +{ + for(int i = 0; i < FILTER_COUNT; i++) + g_bFilter[client][i] = false; +} + +//---------------------------------------------------------------------------------------------------- +// Purpose: "!command" after any leading color codes CCC or the player added +//---------------------------------------------------------------------------------------------------- +bool IsCommandMessage(const char[] message) +{ + int i = 0; + + for(;;) + { + int skip; + + if(message[i] == '\x07') + skip = 7; // \x07RRGGBB + else if(message[i] == '\x08') + skip = 9; // \x08RRGGBBAA + else if(message[i] >= '\x01' && message[i] <= '\x06') + skip = 1; + else + break; + + for(int k = 0; k < skip && message[i] != '\0'; k++) + i++; + } + + return message[i] == '!'; +} + +bool HasLenny(const char[] message) +{ + char sLenny[16]; + + for(int i = 0; i < g_Lennies.Length; i++) + { + g_Lennies.GetString(i, sLenny, sizeof(sLenny)); + + if(StrContains(message, sLenny, true) != -1) + return true; + } + + return false; +} + +//---------------------------------------------------------------------------------------------------- +// Purpose: replaces every bad word with one '*' per character; returns whether anything changed. +// iCategories is a mask of category bits to censor, iMatched gets the bits that were found +//---------------------------------------------------------------------------------------------------- +bool CensorMessage(char[] message, int maxlen, int iCategories = -1, int &iMatched = 0) +{ + iMatched = 0; + + int len = strlen(message); + if(len >= MAX_CENSOR_LENGTH) + return false; + + // per word character: normalised letter, byte span, leet symbol. + // a token is a run of word characters, iTokStart/iTokEnd are character indices + int iChars[MAX_CENSOR_LENGTH]; + int iStarts[MAX_CENSOR_LENGTH]; + int iEnds[MAX_CENSOR_LENGTH]; + bool bSoft[MAX_CENSOR_LENGTH]; + bool bStarred[MAX_CENSOR_LENGTH]; + int iTokStart[MAX_CENSOR_LENGTH]; + int iTokEnd[MAX_CENSOR_LENGTH]; + int n = 0; + int t = 0; + int iOpen = -1; // first character of the token being read + + int i = 0; + while(i < len) + { + int iStart = i; + int cp = DecodeUTF8Char(message, i); + + bool bIsSoft; + int iChar = NormalizeCp(cp, bIsSoft); + + // invisible characters neither split nor join a token, but get starred along with it + if(iChar == -1) + continue; + + if(iChar == 0) + { + if(iOpen != -1) + { + iTokStart[t] = iOpen; + iTokEnd[t++] = n; + iOpen = -1; + } + continue; + } + + if(iOpen == -1) + iOpen = n; + + iChars[n] = iChar; + iStarts[n] = iStart; + iEnds[n] = i; + bSoft[n] = bIsSoft; + n++; + } + + if(iOpen != -1) + { + iTokStart[t] = iOpen; + iTokEnd[t++] = n; + } + + for(int k = 0; k < t; k++) + CensorToken(iChars, iStarts, iEnds, bSoft, iTokStart[k], iTokEnd[k], iCategories, bStarred, iMatched); + + CensorSpacedLetters(iChars, iStarts, iEnds, iTokStart, iTokEnd, t, iCategories, bStarred, iMatched); + + CensorPhrases(iChars, iStarts, iEnds, bSoft, iTokStart, iTokEnd, t, iCategories, bStarred, iMatched); + + if(!iMatched) + return false; + + char sOut[MAX_CENSOR_LENGTH]; + int o = 0; + + i = 0; + while(i < len) + { + int iStart = i; + int cp = DecodeUTF8Char(message, i); + + if(bStarred[iStart]) + { + if(!IsIgnorableCp(cp)) + sOut[o++] = '*'; + } + else + { + for(int b = iStart; b < i; b++) + sOut[o++] = message[b]; + } + } + + sOut[o] = '\0'; + strcopy(message, maxlen, sOut); + + return true; +} + +// the character ranges of a token to try: whole, then without leet symbols at the edges, which may be +// punctuation ("shit!"); "$hit" still matches whole. Returns how many ranges were written +int TokenVariants(const bool[] bSoft, int iFirst, int iLast, int iLo[4], int iHi[4]) +{ + int lo = iFirst; + while(lo < iLast && bSoft[lo]) + lo++; + + int hi = iLast; + while(hi > lo && bSoft[hi - 1]) + hi--; + + iLo[0] = iFirst; + iHi[0] = iLast; + int v = 1; + + if(lo >= hi) + return v; + + if(lo > iFirst) + { + iLo[v] = lo; + iHi[v++] = iLast; + } + + if(hi < iLast) + { + iLo[v] = iFirst; + iHi[v++] = hi; + } + + if(lo > iFirst && hi < iLast) + { + iLo[v] = lo; + iHi[v++] = hi; + } + + return v; +} + +bool CensorToken(const int[] iChars, const int[] iStarts, const int[] iEnds, const bool[] bSoft, int iFirst, int iLast, int iCategories, bool[] bStarred, int &iMatched) +{ + int iLo[4]; + int iHi[4]; + int v = TokenVariants(bSoft, iFirst, iLast, iLo, iHi); + + for(int k = 0; k < v; k++) + { + if(CensorRange(iChars, iStarts, iEnds, iLo[k], iHi[k], iCategories, bStarred, iMatched, false)) + return true; + } + + return false; +} + +// "f u c k", "f.u.c.k": MIN_SPACED_LETTERS or more one-character tokens in a row are joined; wildcard words +// may match anywhere in the joined letters, whole words must match a stretch of them exactly +void CensorSpacedLetters(const int[] iChars, const int[] iStarts, const int[] iEnds, const int[] iTokStart, const int[] iTokEnd, int t, int iCategories, bool[] bStarred, int &iMatched) +{ + int jChars[MAX_CENSOR_LENGTH]; + int jStarts[MAX_CENSOR_LENGTH]; + int jEnds[MAX_CENSOR_LENGTH]; + + int k = 0; + while(k < t) + { + int m = 0; + while(k + m < t && iTokEnd[k + m] - iTokStart[k + m] == 1) + { + int c = iTokStart[k + m]; + jChars[m] = iChars[c]; + jStarts[m] = iStarts[c]; + jEnds[m] = iEnds[c]; + m++; + } + + if(m >= MIN_SPACED_LETTERS) + { + CensorRange(jChars, jStarts, jEnds, 0, m, iCategories, bStarred, iMatched, true); + CensorSpacedWholeWords(jChars, jStarts, jEnds, m, iCategories, bStarred, iMatched); + } + + k += m ? m : 1; + } +} + +// whole words in every stretch of the joined letters, built up one letter at a time +void CensorSpacedWholeWords(const int[] jChars, const int[] jStarts, const int[] jEnds, int m, int iCategories, bool[] bStarred, int &iMatched) +{ + int iRunCount[MAX_WORD_RUNS + 1]; + char sKey[MAX_WORD_RUNS + 2]; + BadWord word; + + for(int x = 0; x < m; x++) + { + int r = 0; + + for(int y = x; y < m; y++) + { + if(r && sKey[r - 1] == jChars[y]) + { + iRunCount[r - 1]++; + } + else + { + if(r == MAX_WORD_RUNS) + break; + + sKey[r] = jChars[y]; + iRunCount[r] = 1; + r++; + sKey[r] = '\0'; + } + + // the full stretch was already tried by CensorRange + if(y == x || (x == 0 && y == m - 1)) + continue; + + int iWord; + if(!g_WholeWordHeads.GetValue(sKey, iWord)) + continue; + + for(; iWord != -1; iWord = word.iNext) + { + g_WholeWords.GetArray(iWord, word); + + if(!(iCategories & (1 << word.iCategory)) || !RunsMatch(word, iRunCount, 0)) + continue; + + for(int c = x; c <= y; c++) + StarBytes(bStarred, jStarts[c], jEnds[c]); + iMatched |= 1 << word.iCategory; + break; + } + } + } +} + +// every word of a phrase must match a whole token, in order; the first word may start inside its token +// with a leading '*', the last may end inside its token with a trailing '*' +void CensorPhrases(const int[] iChars, const int[] iStarts, const int[] iEnds, const bool[] bSoft, const int[] iTokStart, const int[] iTokEnd, int t, int iCategories, bool[] bStarred, int &iMatched) +{ + Phrase phrase; + BadWord word; + int iMatchLo[MAX_PHRASE_WORDS]; + int iMatchHi[MAX_PHRASE_WORDS]; + + for(int p = 0; p < g_Phrases.Length; p++) + { + g_Phrases.GetArray(p, phrase); + + if(!(iCategories & (1 << phrase.iCategory))) + continue; + + for(int k = 0; k + phrase.iWords <= t; k++) + { + bool bMatch = true; + + for(int w = 0; w < phrase.iWords && bMatch; w++) + { + g_PhraseWords.GetArray(phrase.iFirst + w, word); + bMatch = TokenMatchesWord(word, iChars, bSoft, iTokStart[k + w], iTokEnd[k + w], iMatchLo[w], iMatchHi[w]); + } + + if(!bMatch) + continue; + + for(int w = 0; w < phrase.iWords; w++) + StarBytes(bStarred, iStarts[iMatchLo[w]], iEnds[iMatchHi[w] - 1]); + iMatched |= 1 << phrase.iCategory; + } + } +} + +// whether a phrase word matches a token; iMatchLo/iMatchHi get the matched character range +bool TokenMatchesWord(BadWord word, const int[] iChars, const bool[] bSoft, int iFirst, int iLast, int &iMatchLo, int &iMatchHi) +{ + int iLo[4]; + int iHi[4]; + int v = TokenVariants(bSoft, iFirst, iLast, iLo, iHi); + + int iRunChar[MAX_CENSOR_LENGTH]; + int iRunCount[MAX_CENSOR_LENGTH]; + int iRunStart[MAX_CENSOR_LENGTH]; + int iRunEnd[MAX_CENSOR_LENGTH]; + char sKey[MAX_CENSOR_LENGTH]; + + for(int k = 0; k < v; k++) + { + int r = BuildRuns(iChars, iLo[k], iHi[k], iRunChar, iRunCount, iRunStart, iRunEnd, sKey); + + for(int s = 0; s + word.iRuns <= r; s++) + { + if(!word.bAnyStart && s != 0) + break; + + if(!word.bAnyEnd && s + word.iRuns != r) + continue; + + if(!RunsMatchAt(word, iRunChar, iRunCount, s)) + continue; + + iMatchLo = iRunStart[s]; + iMatchHi = iRunEnd[s + word.iRuns - 1]; + return true; + } + } + + return false; +} + +// collapses characters lo..hi-1 into runs of equal characters; iRunStart/iRunEnd are character indices, +// sKey gets the run letters. Returns the number of runs +int BuildRuns(const int[] iChars, int lo, int hi, int[] iRunChar, int[] iRunCount, int[] iRunStart, int[] iRunEnd, char[] sKey) +{ + int r = 0; + + for(int i = lo; i < hi; i++) + { + if(r && iRunChar[r - 1] == iChars[i]) + { + iRunCount[r - 1]++; + iRunEnd[r - 1] = i + 1; + continue; + } + + iRunChar[r] = iChars[i]; + iRunCount[r] = 1; + iRunStart[r] = i; + iRunEnd[r] = i + 1; + sKey[r] = iChars[i]; + r++; + } + sKey[r] = '\0'; + + return r; +} + +// matches the characters lo..hi-1 against the bad words and stars the matches. bPerChar stars each +// character on its own (joined spaced letters keep their spaces), otherwise the whole byte span +bool CensorRange(const int[] iChars, const int[] iStarts, const int[] iEnds, int lo, int hi, int iCategories, bool[] bStarred, int &iMatched, bool bPerChar) +{ + int iRunChar[MAX_CENSOR_LENGTH]; + int iRunCount[MAX_CENSOR_LENGTH]; + int iRunStart[MAX_CENSOR_LENGTH]; + int iRunEnd[MAX_CENSOR_LENGTH]; + char sKey[MAX_CENSOR_LENGTH]; + int r = BuildRuns(iChars, lo, hi, iRunChar, iRunCount, iRunStart, iRunEnd, sKey); + + // run spans an allow word covers, bad words inside them are skipped + int iAllowS[MAX_ALLOWED_SPANS]; + int iAllowE[MAX_ALLOWED_SPANS]; + int iAllowCat[MAX_ALLOWED_SPANS]; + int a = FindMatches(g_AllowWords, g_AllowWordHeads, g_AllowWildWords, iRunChar, iRunCount, r, sKey, -1, iAllowS, iAllowE, iAllowCat, MAX_ALLOWED_SPANS); + + int iMatchS[MAX_CENSOR_LENGTH]; + int iMatchE[MAX_CENSOR_LENGTH]; + int iMatchCat[MAX_CENSOR_LENGTH]; + int m = FindMatches(g_WholeWords, g_WholeWordHeads, g_WildWords, iRunChar, iRunCount, r, sKey, iCategories, iMatchS, iMatchE, iMatchCat, sizeof(iMatchS)); + + bool bFound = false; + + for(int k = 0; k < m; k++) + { + bool bAllowed = false; + for(int j = 0; j < a && !bAllowed; j++) + bAllowed = iAllowS[j] <= iMatchS[k] && iMatchE[k] <= iAllowE[j]; + + if(bAllowed) + continue; + + int c1 = iRunStart[iMatchS[k]]; + int c2 = iRunEnd[iMatchE[k] - 1]; + + if(bPerChar) + { + for(int c = c1; c < c2; c++) + StarBytes(bStarred, iStarts[c], iEnds[c]); + } + else + { + StarBytes(bStarred, iStarts[c1], iEnds[c2 - 1]); + } + + iMatched |= 1 << iMatchCat[k]; + bFound = true; + } + + return bFound; +} + +// finds the words of one list in a run sequence: a whole word must cover all runs, a wildcard word any +// runs its '*' allow. Writes run spans [iMatchS, iMatchE) and categories; iCategories -1 takes every word. +// Returns the number of matches +int FindMatches(ArrayList hWhole, StringMap hHeads, ArrayList hWild, const int[] iRunChar, const int[] iRunCount, int r, const char[] sKey, int iCategories, + int[] iMatchS, int[] iMatchE, int[] iMatchCat, int iMax) +{ + int m = 0; + BadWord word; + + int iWord; + if(hHeads.GetValue(sKey, iWord)) + { + for(; iWord != -1; iWord = word.iNext) + { + hWhole.GetArray(iWord, word); + + if(!(iCategories & (1 << word.iCategory))) + continue; + + if(RunsMatch(word, iRunCount, 0)) + { + iMatchS[m] = 0; + iMatchE[m] = r; + iMatchCat[m] = word.iCategory; + m++; + break; + } + } + } + + for(int w = 0; w < hWild.Length && m < iMax; w++) + { + hWild.GetArray(w, word); + + if(!(iCategories & (1 << word.iCategory))) + continue; + + for(int s = 0; s + word.iRuns <= r && m < iMax; s++) + { + if(!word.bAnyStart && s != 0) + break; + + if(!word.bAnyEnd && s + word.iRuns != r) + continue; + + if(!RunsMatchAt(word, iRunChar, iRunCount, s)) + continue; + + iMatchS[m] = s; + iMatchE[m] = s + word.iRuns; + iMatchCat[m] = word.iCategory; + m++; + s += word.iRuns - 1; + } + } + + return m; +} + +// every run must repeat at least as often as in the word: "fuuuck" matches "fuck", "as" not "ass" +bool RunsMatch(BadWord word, const int[] iRunCount, int s) +{ + for(int k = 0; k < word.iRuns; k++) + { + if(iRunCount[s + k] < word.iCount[k]) + return false; + } + + return true; +} + +bool RunsMatchAt(BadWord word, const int[] iRunChar, const int[] iRunCount, int s) +{ + for(int k = 0; k < word.iRuns; k++) + { + if(iRunChar[s + k] != word.iChar[k]) + return false; + } + + return RunsMatch(word, iRunCount, s); +} + +void StarBytes(bool[] bStarred, int iStart, int iEnd) +{ + for(int b = iStart; b < iEnd; b++) + bStarred[b] = true; +} + +// returns the lowercase ASCII letter/digit a character counts as, 0 for a separator, +// -1 for an invisible character. bSoft is set for leet symbols that could be punctuation +int NormalizeCp(int cp, bool &bSoft) +{ + bSoft = false; + + if(cp >= 'A' && cp <= 'Z') + return cp + ('a' - 'A'); + + if(cp >= 'a' && cp <= 'z') + return cp; + + if(cp >= '0' && cp <= '9') + return g_iLeet[cp] ? g_iLeet[cp] : cp; + + if(cp > 0 && cp < sizeof(g_iLeet)) + { + bSoft = g_iLeet[cp] != 0; + return g_iLeet[cp]; + } + + if(IsIgnorableCp(cp)) + return -1; + + char sKey[12]; + IntToString(cp, sKey, sizeof(sKey)); + + int iLetter; + if(g_Confusables.GetValue(sKey, iLetter)) + return iLetter; + + return 0; +} + +// zero-width, bidi, soft hyphen, variation selectors and combining marks +bool IsIgnorableCp(int cp) +{ + return cp == 0x00AD + || (cp >= 0x0300 && cp <= 0x036F) + || (cp >= 0x200B && cp <= 0x200F) + || (cp >= 0x202A && cp <= 0x202E) + || (cp >= 0x2060 && cp <= 0x2064) + || (cp >= 0xFE00 && cp <= 0xFE0F) + || cp == 0xFEFF; +} + +int DecodeUTF8Char(const char[] s, int &i) +{ + int b = s[i] & 0xFF; + if(b < 0x80) + { + i++; + return b; + } + + int len; + int cp; + if((b & 0xE0) == 0xC0) { len = 2; cp = b & 0x1F; } + else if((b & 0xF0) == 0xE0) { len = 3; cp = b & 0x0F; } + else if((b & 0xF8) == 0xF0) { len = 4; cp = b & 0x07; } + else + { + i++; + return -1; + } + + for(int k = 1; k < len; k++) + { + int cb = s[i + k] & 0xFF; + if((cb & 0xC0) != 0x80) + { + i++; + return -1; + } + cp = (cp << 6) | (cb & 0x3F); + } + + i += len; + return cp; +} + +//---------------------------------------------------------------------------------------------------- +// Purpose: +//---------------------------------------------------------------------------------------------------- +void LoadConfig() +{ + delete g_Lennies; + delete g_Categories; + delete g_WholeWords; + delete g_WholeWordHeads; + delete g_WildWords; + delete g_Phrases; + delete g_PhraseWords; + delete g_AllowWords; + delete g_AllowWordHeads; + delete g_AllowWildWords; + delete g_Confusables; + + g_Lennies = new ArrayList(ByteCountToCells(16)); + g_Categories = new ArrayList(ByteCountToCells(64)); + g_WholeWords = new ArrayList(sizeof(BadWord)); + g_WholeWordHeads = new StringMap(); + g_WildWords = new ArrayList(sizeof(BadWord)); + g_Phrases = new ArrayList(sizeof(Phrase)); + g_PhraseWords = new ArrayList(sizeof(BadWord)); + g_AllowWords = new ArrayList(sizeof(BadWord)); + g_AllowWordHeads = new StringMap(); + g_AllowWildWords = new ArrayList(sizeof(BadWord)); + g_Confusables = new StringMap(); + + for(int i = 0; i < sizeof(g_iLeet); i++) + g_iLeet[i] = 0; + + static char sConfigFile[PLATFORM_MAX_PATH]; + BuildPath(Path_SM, sConfigFile, sizeof(sConfigFile), "configs/ChatFilter2.cfg"); + + KeyValues Config = new KeyValues("ChatFilter2"); + if(!FileExists(sConfigFile) || !Config.ImportFromFile(sConfigFile)) + { + LogError("Could not load config \"%s\", safe chat is disabled", sConfigFile); + delete Config; + + for(int i = 0; i < sizeof(g_sDefaultLennies); i++) + g_Lennies.PushString(g_sDefaultLennies[i]); + return; + } + + char sKey[64]; + char sValue[64]; + + if(Config.JumpToKey("lennies")) + { + if(Config.GotoFirstSubKey(false)) + { + do + { + Config.GetSectionName(sKey, sizeof(sKey)); + + if(sKey[0]) + g_Lennies.PushString(sKey); + } while(Config.GotoNextKey(false)); + Config.GoBack(); + } + Config.GoBack(); + } + + // leet and confusables must be loaded before the words, which are normalised with them + if(Config.JumpToKey("leet")) + { + if(Config.GotoFirstSubKey(false)) + { + do + { + Config.GetSectionName(sKey, sizeof(sKey)); + Config.GetString(NULL_STRING, sValue, sizeof(sValue)); + + int iLetter = ToLetter(sValue); + if(sKey[1] != '\0' || sKey[0] <= ' ' || sKey[0] >= sizeof(g_iLeet) || IsCharAlpha(sKey[0]) || !iLetter) + LogError("Invalid leet entry \"%s\" \"%s\", needs one ASCII symbol or digit and one letter", sKey, sValue); + else + g_iLeet[sKey[0]] = iLetter; + } while(Config.GotoNextKey(false)); + Config.GoBack(); + } + Config.GoBack(); + } + + if(Config.JumpToKey("confusables")) + { + if(Config.GotoFirstSubKey(false)) + { + do + { + Config.GetSectionName(sKey, sizeof(sKey)); + Config.GetString(NULL_STRING, sValue, sizeof(sValue)); + + int iPos = 0; + int cp = DecodeUTF8Char(sKey, iPos); + int iLetter = ToLetter(sValue); + if(cp < 0x80 || sKey[iPos] != '\0' || !iLetter) + { + LogError("Invalid confusable \"%s\" \"%s\", needs one non-ASCII character and one letter", sKey, sValue); + continue; + } + + char sCp[12]; + IntToString(cp, sCp, sizeof(sCp)); + g_Confusables.SetValue(sCp, iLetter); + } while(Config.GotoNextKey(false)); + Config.GoBack(); + } + Config.GoBack(); + } + + // each section in "words" is a category; plain keys directly in "words" go to "uncategorised" + if(Config.JumpToKey("words")) + { + if(Config.GotoFirstSubKey(false)) + { + do + { + Config.GetSectionName(sKey, sizeof(sKey)); + + if(Config.GetDataType(NULL_STRING) != KvData_None) + { + AddWord(sKey, GetCategory("uncategorised")); + continue; + } + + int iCategory = GetCategory(sKey); + + if(Config.GotoFirstSubKey(false)) + { + do + { + Config.GetSectionName(sKey, sizeof(sKey)); + AddWord(sKey, iCategory); + } while(Config.GotoNextKey(false)); + Config.GoBack(); + } + } while(Config.GotoNextKey(false)); + Config.GoBack(); + } + Config.GoBack(); + } + + if(Config.JumpToKey("allow")) + { + if(Config.GotoFirstSubKey(false)) + { + do + { + Config.GetSectionName(sKey, sizeof(sKey)); + AddWord(sKey, -1); + } while(Config.GotoNextKey(false)); + Config.GoBack(); + } + Config.GoBack(); + } + + delete Config; +} + +// index of a category by name, added if new; categories past MAX_CATEGORIES share the last one +int GetCategory(const char[] sName) +{ + int iCategory = g_Categories.FindString(sName); + if(iCategory != -1) + return iCategory; + + if(g_Categories.Length == MAX_CATEGORIES) + { + LogError("More than %d word categories, \"%s\" is merged into the last one", MAX_CATEGORIES, sName); + return MAX_CATEGORIES - 1; + } + + return g_Categories.PushString(sName); +} + +// lowercase ASCII letter or digit of a one-character config value, 0 if invalid +int ToLetter(const char[] sValue) +{ + if(sValue[0] == '\0' || sValue[1] != '\0' || sValue[0] >= 0x80) + return 0; + + if(!IsCharAlpha(sValue[0]) && !IsCharNumeric(sValue[0])) + return 0; + + return CharToLower(sValue[0]); +} + +// adds a bad word or phrase to a category, or to the allow list if iCategory is -1 +void AddWord(const char[] sEntry, int iCategory) +{ + if(FindCharInString(sEntry, ' ') != -1) + { + if(iCategory == -1) + LogError("Skipping allow entry \"%s\": phrases are not supported there", sEntry); + else + AddPhrase(sEntry, iCategory); + return; + } + + BadWord word; + char sKey[MAX_WORD_RUNS + 1]; + if(!ParseWord(sEntry, sEntry, word, sKey)) + return; + + word.iCategory = iCategory < 0 ? 0 : iCategory; + + ArrayList hWhole = iCategory == -1 ? g_AllowWords : g_WholeWords; + StringMap hHeads = iCategory == -1 ? g_AllowWordHeads : g_WholeWordHeads; + ArrayList hWild = iCategory == -1 ? g_AllowWildWords : g_WildWords; + + if(word.bAnyStart || word.bAnyEnd) + { + hWild.PushArray(word); + return; + } + + int iHead; + if(hHeads.GetValue(sKey, iHead)) + word.iNext = iHead; + + hHeads.SetValue(sKey, hWhole.PushArray(word)); +} + +// "kill yourself": words split on spaces, '*' only at the start of the first and the end of the last +void AddPhrase(const char[] sEntry, int iCategory) +{ + char sParts[MAX_PHRASE_WORDS + 1][64]; + int iParts = ExplodeString(sEntry, " ", sParts, sizeof(sParts), sizeof(sParts[])); + + BadWord words[MAX_PHRASE_WORDS]; + int iWords = 0; + char sKey[MAX_WORD_RUNS + 1]; + + for(int i = 0; i < iParts; i++) + { + if(!sParts[i][0]) + continue; // double spaces + + if(iWords == MAX_PHRASE_WORDS) + { + LogError("Skipping phrase \"%s\": more than %d words", sEntry, MAX_PHRASE_WORDS); + return; + } + + if(!ParseWord(sParts[i], sEntry, words[iWords], sKey)) + return; + + iWords++; + } + + for(int i = 0; i < iWords; i++) + { + if((words[i].bAnyStart && i > 0) || (words[i].bAnyEnd && i < iWords - 1)) + { + LogError("Skipping phrase \"%s\": '*' is only allowed at the start or end of the phrase", sEntry); + return; + } + } + + Phrase phrase; + phrase.iFirst = g_PhraseWords.Length; + phrase.iWords = iWords; + phrase.iCategory = iCategory; + + for(int i = 0; i < iWords; i++) + { + words[i].iCategory = iCategory; + g_PhraseWords.PushArray(words[i]); + } + + g_Phrases.PushArray(phrase); +} + +// normalises one config word ("*word*") into runs; sKey gets the run letters. sEntry is the full +// config entry, for error messages +bool ParseWord(const char[] sWord, const char[] sEntry, BadWord word, char sKey[MAX_WORD_RUNS + 1]) +{ + word.iNext = -1; + word.iRuns = 0; + word.bAnyStart = false; + word.bAnyEnd = false; + + int len = strlen(sWord); + int iFirst = 0; + int iLast = len; + + if(len && sWord[0] == '*') + { + word.bAnyStart = true; + iFirst++; + } + + if(iLast > iFirst && sWord[iLast - 1] == '*') + { + word.bAnyEnd = true; + iLast--; + } + + int i = iFirst; + while(i < iLast) + { + int cp = DecodeUTF8Char(sWord, i); + + bool bSoft; + int iChar = NormalizeCp(cp, bSoft); + + if(iChar == -1) + continue; + + if(iChar == 0) + { + LogError("Skipping bad word \"%s\": only letters, digits, leet symbols and spaces between phrase words are allowed", sEntry); + return false; + } + + if(word.iRuns && word.iChar[word.iRuns - 1] == iChar) + { + word.iCount[word.iRuns - 1]++; + continue; + } + + if(word.iRuns == MAX_WORD_RUNS) + { + LogError("Skipping bad word \"%s\": longer than %d letters", sEntry, MAX_WORD_RUNS); + return false; + } + + word.iChar[word.iRuns] = iChar; + word.iCount[word.iRuns] = 1; + sKey[word.iRuns] = iChar; + word.iRuns++; + } + sKey[word.iRuns] = '\0'; + + if(!word.iRuns) + { + LogError("Skipping empty bad word \"%s\"", sEntry); + return false; + } + + return true; +} diff --git a/ChatFilter2/scripting/include/ChatFilter2.inc b/ChatFilter2/scripting/include/ChatFilter2.inc new file mode 100644 index 0000000..88c3b35 --- /dev/null +++ b/ChatFilter2/scripting/include/ChatFilter2.inc @@ -0,0 +1,50 @@ +#if defined _ChatFilter2_included_ + #endinput +#endif +#define _ChatFilter2_included_ + +/** + * Censors bad words in a string the same way safe chat does, with every category. + * + * @param text String to censor in place + * @param maxlen Size of text + * @return True if anything was censored + */ +native bool ChatFilter2_CensorText(char[] text, int maxlen); + +/** + * Checks if a client has safe chat enabled. + * + * @param client Client index + * @return True if safe chat is enabled + */ +native bool ChatFilter2_IsSafeChatEnabled(int client); + +/** + * Called when a client toggles safe chat, and when their cookies load with safe chat enabled. + * + * @param client Client index + * @param enabled True if safe chat is now enabled + */ +forward void ChatFilter2_OnSafeChatChanged(int client, bool enabled); + +#if !defined CHATFILTER2_CORE +public SharedPlugin __pl_ChatFilter2 = +{ + name = "ChatFilter2", + file = "ChatFilter2.smx", +#if defined REQUIRE_PLUGIN + required = 1, +#else + required = 0, +#endif +}; + +#if !defined REQUIRE_PLUGIN +public void __pl_ChatFilter2_SetNTVOptional() +{ + MarkNativeAsOptional("ChatFilter2_CensorText"); + MarkNativeAsOptional("ChatFilter2_IsSafeChatEnabled"); +} +#endif +#endif // CHATFILTER2_CORE diff --git a/EventGreeting/scripting/EventGreeting.sp b/EventGreeting/scripting/EventGreeting.sp new file mode 100644 index 0000000..f3828c2 --- /dev/null +++ b/EventGreeting/scripting/EventGreeting.sp @@ -0,0 +1,606 @@ +#pragma semicolon 1 + +#include +#include +#include + +#undef REQUIRE_PLUGIN +#include +#define REQUIRE_PLUGIN + +#pragma newdecls required + +#define PLUGIN_VERSION "1.0" + +#define GREETING_TITLE "UNLOZE.com" +#define PLACEHOLDER_EVENT "Test Event" +#define MAX_NAME_CHARS 64 +// Skip greetings rather than push a busy map towards the 2048 edict limit. +#define EDICT_HEADROOM 1900 +// Stock model on every client; its "forward" attachment sits on ValveBiped.forward, a child of +// Bip01_Head1, so it follows the head of any ValveBiped skeleton it bone-merges onto. +#define HELPER_MODEL "models/player/ct_urban.mdl" +#define HELPER_ATTACHMENT "forward" +#define HELPER_CLASS "prop_dynamic" // created as prop_dynamic_override, which spawns as prop_dynamic + +#define EF_BONEMERGE (1 << 0) +#define EF_NOSHADOW (1 << 4) +#define EF_NORECEIVESHADOW (1 << 6) +#define EF_BONEMERGE_FASTCULL (1 << 7) +#define EF_PARENT_ANIMATES (1 << 9) + +#define MOVEMENT_BUTTONS (IN_FORWARD|IN_BACK|IN_MOVELEFT|IN_MOVERIGHT|IN_JUMP|IN_DUCK) + +// sm_eventgreeting_anchor: what the text is parented to +enum +{ + ANCHOR_HEAD = 0, // "forward" attachment of a bone-merged helper; sways with the head animation + ANCHOR_PLAYER, // the player; offset corrected for pitch and eye height every tick + ANCHOR_VIEWMODEL // the viewmodel, at the eyes with the view angles; bobs with the gun +} + +ConVar g_cvEventIsOn; +ConVar g_cvAnchor; +ConVar g_cvDuration; +ConVar g_cvOffset; +ConVar g_cvSize; +ConVar g_cvFont; +ConVar g_cvMaxChars; + +bool g_bEventNotifier; +bool g_bWorldTextBroken; + +// One greeting per player per map +bool g_bGreeted[MAXPLAYERS + 1]; +int g_iTextRef[MAXPLAYERS + 1] = {INVALID_ENT_REFERENCE, ...}; +int g_iHelperRef[MAXPLAYERS + 1] = {INVALID_ENT_REFERENCE, ...}; +float g_flExpireAt[MAXPLAYERS + 1]; // 0 until the player first moves +int g_iAnchor[MAXPLAYERS + 1]; +float g_flLastPitch[MAXPLAYERS + 1]; +float g_flLastEyeHeight[MAXPLAYERS + 1]; + +// Per entity, read by the transmit hook +int g_iEntOwner[2049]; + +public Plugin myinfo = +{ + name = "EventGreeting", + author = "marisakirisame.net", + description = "Greets players on their first spawn during events with the active event's name", + version = PLUGIN_VERSION, + url = "" +}; + +public void OnPluginStart() +{ + // Owned by VIP_Reward. CreateConVar on an existing cvar would add it to this plugin's list, and + // AutoExecConfig would then write sv_event_is_on "0" into EventGreeting.cfg, turning event mode + // off every map. So only create it when VIP_Reward hasn't (yet), and keep it out of the cfg. + g_cvEventIsOn = FindConVar("sv_event_is_on"); + if (g_cvEventIsOn == null) + g_cvEventIsOn = CreateConVar("sv_event_is_on", "0", "Cvar decides whether event mode is on or not.", FCVAR_DONTRECORD); + g_cvEventIsOn.AddChangeHook(OnEventIsOnChanged); + + // lines are centred with space padding, which is only exact in a monospaced font + g_cvFont = CreateConVar("sm_eventgreeting_font", "8", "point_worldtext font (8 = Roboto Mono with outline)", 0, true, 0.0, true, 12.0); + g_cvSize = CreateConVar("sm_eventgreeting_size", "3.0", "Text size", 0, true, 0.5); + g_cvAnchor = CreateConVar("sm_eventgreeting_anchor", "2", "0 = head attachment of a bone-merged helper (sways with the head animation, 2 edicts), 1 = the player (turns at network rate), 2 = the viewmodel (bobs with the gun)", 0, true, 0.0, true, 2.0); + g_cvOffset = CreateConVar("sm_eventgreeting_offset", "64 0 0", "Text position \"x y z\" relative to the anchor (x is forward)"); + g_cvDuration = CreateConVar("sm_eventgreeting_duration", "5.0", "Seconds the greeting stays after the player first moves", 0, true, 0.0); + g_cvMaxChars = CreateConVar("sm_eventgreeting_max_chars", "32", "Maximum characters of the event name; longer names end in ...", 0, true, 8.0, true, float(MAX_NAME_CHARS)); + AutoExecConfig(true, "EventGreeting"); + + RegAdminCmd("sm_eventgreeting_test", Cmd_Test, ADMFLAG_RCON, "sm_eventgreeting_test [target] - show the greeting now, ignoring sv_event_is_on and earlier greetings"); + RegAdminCmd("sm_eventgreeting_debug", Cmd_Debug, ADMFLAG_RCON, "sm_eventgreeting_debug - list live greetings"); + + HookEvent("player_spawn", Event_PlayerSpawn); + HookEvent("player_death", Event_KillGreeting); + HookEvent("player_team", Event_KillGreeting); +} + +public void OnPluginEnd() +{ + for (int i = 1; i <= MaxClients; i++) + KillGreeting(i); +} + +public void OnAllPluginsLoaded() +{ + g_bEventNotifier = LibraryExists("EventNotifier"); +} + +public void OnLibraryAdded(const char[] name) +{ + if (StrEqual(name, "EventNotifier")) + g_bEventNotifier = true; +} + +public void OnLibraryRemoved(const char[] name) +{ + if (StrEqual(name, "EventNotifier")) + g_bEventNotifier = false; +} + +public void OnMapStart() +{ + g_bWorldTextBroken = false; + PrecacheModel(HELPER_MODEL); + + // the previous map's entities are gone, so only the bookkeeping needs resetting + for (int i = 1; i <= MaxClients; i++) + { + g_bGreeted[i] = false; + g_iTextRef[i] = INVALID_ENT_REFERENCE; + g_iHelperRef[i] = INVALID_ENT_REFERENCE; + } +} + +public void OnClientConnected(int client) +{ + g_bGreeted[client] = false; +} + +public void OnClientDisconnect(int client) +{ + KillGreeting(client); +} + +void OnEventIsOnChanged(ConVar convar, const char[] oldValue, const char[] newValue) +{ + if (convar.BoolValue) + return; + + for (int i = 1; i <= MaxClients; i++) + KillGreeting(i); +} + +//---------------------------------------------------------------------------------------------------- +// Spawning +//---------------------------------------------------------------------------------------------------- +public void Event_PlayerSpawn(Event event, const char[] name, bool dontBroadcast) +{ + if (!g_cvEventIsOn.BoolValue) + return; + + // eye position and team aren't final during the event + RequestFrame(Frame_Greet, event.GetInt("userid")); +} + +void Frame_Greet(int userid) +{ + int client = GetClientOfUserId(userid); + if (client == 0 || g_bGreeted[client] || IsFakeClient(client) || !g_cvEventIsOn.BoolValue) + return; + + if (!IsPlayerAlive(client) || GetClientTeam(client) < 2) + return; + + char eventName[EVENT_STR_LEN]; + if (!FindActiveEventName(eventName, sizeof(eventName))) + return; + + if (ShowGreeting(client, eventName)) + g_bGreeted[client] = true; +} + +public void Event_KillGreeting(Event event, const char[] name, bool dontBroadcast) +{ + int client = GetClientOfUserId(event.GetInt("userid")); + if (client != 0) + KillGreeting(client); +} + +// The active event is one in progress, else the one whose start is nearest to now (past or future). +bool FindActiveEventName(char[] buffer, int maxlen) +{ + if (!g_bEventNotifier || !EventNotifier_HasFetched()) + return false; + + int now = GetTime(); + int best = -1; + int bestDistance; + + int count = EventNotifier_GetEventCount(); + for (int i = 0; i < count; i++) + { + EventInfo ev; + if (!EventNotifier_GetEvent(i, ev, sizeof(ev)) || ev.start == 0) + continue; + + if (ev.end > 0 && now >= ev.start && now < ev.end) + { + best = i; + break; + } + + int distance = now > ev.start ? now - ev.start : ev.start - now; + if (best == -1 || distance < bestDistance) + { + best = i; + bestDistance = distance; + } + } + + if (best == -1) + return false; + + EventInfo ev; + EventNotifier_GetEvent(best, ev, sizeof(ev)); + strcopy(buffer, maxlen, ev.name); + return true; +} + +bool ShowGreeting(int client, const char[] eventName) +{ + KillGreeting(client); + + if (g_bWorldTextBroken || GetEntityCount() >= EDICT_HEADROOM) + return false; + + char text[2 * (MAX_NAME_CHARS + 8)]; + if (!FormatGreeting(eventName, text, sizeof(text))) + return false; + + int anchor = g_cvAnchor.IntValue; + int parent = client; + int helper = -1; + if (anchor == ANCHOR_HEAD) + { + helper = SpawnHelper(client); + if (helper == -1) + return false; + parent = helper; + } + else if (anchor == ANCHOR_VIEWMODEL) + { + int viewmodel = GetEntPropEnt(client, Prop_Send, "m_hViewModel", 0); + if (viewmodel != -1) + parent = viewmodel; + else + anchor = ANCHOR_PLAYER; + } + + int ent = SpawnWorldText(client, parent, anchor, text); + if (ent == -1) + { + if (helper != -1) + AcceptEntityInput(helper, "Kill"); + return false; + } + + g_iHelperRef[client] = helper != -1 ? EntIndexToEntRef(helper) : INVALID_ENT_REFERENCE; + g_iTextRef[client] = EntIndexToEntRef(ent); + g_flExpireAt[client] = 0.0; + return true; +} + +// Invisible copy of the player's skeleton; the text hangs off its head attachment, so the client +// keeps it in front of the face it draws without the server moving it. +int SpawnHelper(int client) +{ + int ent = CreateEntityByName("prop_dynamic_override"); + if (ent == -1) + return -1; + + DispatchKeyValue(ent, "model", HELPER_MODEL); + DispatchKeyValue(ent, "solid", "0"); + DispatchKeyValue(ent, "DisableBoneFollowers", "1"); + DispatchKeyValue(ent, "disableshadows", "1"); + DispatchKeyValue(ent, "disablereceiveshadows", "1"); + if (!DispatchSpawn(ent)) + { + AcceptEntityInput(ent, "Kill"); + return -1; + } + + // RENDER_NONE rather than EF_NODRAW: EF_NODRAW stops the entity being sent at all, and the + // client needs it to place the text. + SetEntityRenderMode(ent, RENDER_NONE); + + // CBaseEntity::FollowEntity() recipe (see Leader3's glow shell): the client only bone-merges + // with EF_BONEMERGE, a move parent and MOVETYPE_NONE. + float origin[3], angles[3]; + GetClientAbsOrigin(client, origin); + GetClientAbsAngles(client, angles); + TeleportEntity(ent, origin, angles, NULL_VECTOR); + + SetVariantString("!activator"); + AcceptEntityInput(ent, "SetParent", client, ent); + SetEntityMoveType(ent, MOVETYPE_NONE); + SetEntProp(ent, Prop_Send, "m_fEffects", + EF_BONEMERGE|EF_BONEMERGE_FASTCULL|EF_NOSHADOW|EF_NORECEIVESHADOW|EF_PARENT_ANIMATES); + + g_iEntOwner[ent] = client; + SDKHook(ent, SDKHook_SetTransmit, Hook_OwnerOnlyTransmit); + return ent; +} + +int SpawnWorldText(int client, int parent, int anchor, const char[] text) +{ + int ent = CreateEntityByName("point_worldtext"); + if (ent == -1) + { + g_bWorldTextBroken = true; + LogMessage("point_worldtext could not be created; event greetings are off for this map."); + return -1; + } + + char font[4], size[16]; + g_cvFont.GetString(font, sizeof(font)); + g_cvSize.GetString(size, sizeof(size)); + + DispatchKeyValue(ent, "message", text); + DispatchKeyValue(ent, "font", font); + DispatchKeyValue(ent, "textsize", size); + DispatchKeyValue(ent, "color", "255 255 255 255"); + DispatchKeyValue(ent, "orientation", "1"); + DispatchSpawn(ent); + + float eyes[3]; + GetClientEyePosition(client, eyes); + TeleportEntity(ent, eyes, NULL_VECTOR, NULL_VECTOR); + + SetVariantString("!activator"); + AcceptEntityInput(ent, "SetParent", parent, ent); + if (anchor == ANCHOR_HEAD) + { + SetVariantString(HELPER_ATTACHMENT); + AcceptEntityInput(ent, "SetParentAttachment", ent, ent); + } + + g_iAnchor[client] = anchor; + SetTextOffset(client, ent); + + g_iEntOwner[ent] = client; + SDKHook(ent, SDKHook_SetTransmit, Hook_OwnerOnlyTransmit); + return ent; +} + +// Sets the text's local origin (it is parented, so TeleportEntity sets the local origin). +// The client rotates children of the local player by the full view angles about the FEET, so for +// ANCHOR_PLAYER the eye height is added in the rotated frame: the world up vector in that frame is +// (-sin pitch, 0, cos pitch). The pitch comes from the server, so this is redone as it changes. +void SetTextOffset(int client, int ent) +{ + float local[3]; + GetOffset(local); + + if (g_iAnchor[client] == ANCHOR_PLAYER) + { + float angles[3]; + GetClientEyeAngles(client, angles); + float eyeHeight = GetEntPropFloat(client, Prop_Send, "m_vecViewOffset[2]"); + float pitch = DegToRad(angles[0]); + + local[0] -= eyeHeight * Sine(pitch); + local[2] += eyeHeight * Cosine(pitch); + + g_flLastPitch[client] = angles[0]; + g_flLastEyeHeight[client] = eyeHeight; + } + + TeleportEntity(ent, local, NULL_VECTOR, NULL_VECTOR); +} + +bool PlayerOffsetChanged(int client) +{ + float angles[3]; + GetClientEyeAngles(client, angles); + float eyeHeight = GetEntPropFloat(client, Prop_Send, "m_vecViewOffset[2]"); + return FloatAbs(angles[0] - g_flLastPitch[client]) > 0.1 || FloatAbs(eyeHeight - g_flLastEyeHeight[client]) > 0.1; +} + +void GetOffset(float local[3]) +{ + char value[64], parts[3][16]; + g_cvOffset.GetString(value, sizeof(value)); + int count = ExplodeString(value, " ", parts, sizeof(parts), sizeof(parts[])); + for (int i = 0; i < 3; i++) + local[i] = i < count ? StringToFloat(parts[i]) : 0.0; +} + +public Action Hook_OwnerOnlyTransmit(int ent, int client) +{ + return client == g_iEntOwner[ent] ? Plugin_Continue : Plugin_Handled; +} + +//---------------------------------------------------------------------------------------------------- +// Expiry and cleanup +//---------------------------------------------------------------------------------------------------- +public void OnPlayerRunCmdPost(int client, int buttons) +{ + if (g_iTextRef[client] == INVALID_ENT_REFERENCE || g_flExpireAt[client] != 0.0) + return; + + if (buttons & MOVEMENT_BUTTONS) + g_flExpireAt[client] = GetGameTime() + g_cvDuration.FloatValue; +} + +public void OnGameFrame() +{ + float now = GetGameTime(); + + for (int client = 1; client <= MaxClients; client++) + { + if (g_iTextRef[client] == INVALID_ENT_REFERENCE) + continue; + + if (LiveEntRef(g_iTextRef[client]) == -1 + || (g_iHelperRef[client] != INVALID_ENT_REFERENCE && LiveEntRef(g_iHelperRef[client], HELPER_CLASS) == -1) + || (g_flExpireAt[client] != 0.0 && now >= g_flExpireAt[client]) + || !IsClientInGame(client) || !IsPlayerAlive(client)) + { + // also catches entities the round restart removed + KillGreeting(client); + continue; + } + + if (g_iAnchor[client] == ANCHOR_PLAYER && PlayerOffsetChanged(client)) + SetTextOffset(client, EntRefToEntIndex(g_iTextRef[client])); + } +} + +void KillGreeting(int client) +{ + KillEntRef(g_iTextRef[client]); + KillEntRef(g_iHelperRef[client], HELPER_CLASS); + g_iTextRef[client] = INVALID_ENT_REFERENCE; + g_iHelperRef[client] = INVALID_ENT_REFERENCE; +} + +void KillEntRef(int ref, const char[] expectedClass = "point_worldtext") +{ + int ent = LiveEntRef(ref, expectedClass); + if (ent != -1) + AcceptEntityInput(ent, "Kill"); +} + +// Resolves an entity reference, returning -1 unless it is still a live edict of the expected class. +int LiveEntRef(int ref, const char[] expectedClass = "point_worldtext") +{ + if (ref == INVALID_ENT_REFERENCE) + return -1; + + int ent = EntRefToEntIndex(ref); + if (ent == INVALID_ENT_REFERENCE || !IsValidEdict(ent)) + return -1; + + char classname[32]; + GetEdictClassname(ent, classname, sizeof(classname)); + return StrEqual(classname, expectedClass) ? ent : -1; +} + +//---------------------------------------------------------------------------------------------------- +// Text: point_worldtext only draws printable ASCII, so anything else is dropped from the event name. +// Both lines are space-padded to the same length so they centre in a monospaced font. +//---------------------------------------------------------------------------------------------------- +bool FormatGreeting(const char[] eventName, char[] output, int maxlen) +{ + char name[MAX_NAME_CHARS + 4]; + int maxChars = g_cvMaxChars.IntValue; + int len = 0; + bool truncated = false; + + for (int i = 0; eventName[i] != '\0'; i++) + { + if (eventName[i] < ' ' || eventName[i] > '~') + continue; + + // no leading or doubled spaces left behind by dropped characters + if (eventName[i] == ' ' && (len == 0 || name[len - 1] == ' ')) + continue; + + if (len >= maxChars) + { + truncated = true; + break; + } + + name[len++] = eventName[i]; + } + + while (len > 0 && name[len - 1] == ' ') + len--; + name[len] = '\0'; + + if (len == 0) + return false; + + if (truncated) + StrCat(name, sizeof(name), "..."); + + char title[MAX_NAME_CHARS + 4], line[MAX_NAME_CHARS + 4]; + int width = strlen(name) > strlen(GREETING_TITLE) ? strlen(name) : strlen(GREETING_TITLE); + PadLine(GREETING_TITLE, width, title, sizeof(title)); + PadLine(name, width, line, sizeof(line)); + Format(output, maxlen, "%s\n%s", title, line); + return true; +} + +void PadLine(const char[] text, int width, char[] output, int maxlen) +{ + int pad = width - strlen(text); + int left = pad / 2; + + output[0] = '\0'; + for (int c = 0; c < left; c++) + StrCat(output, maxlen, " "); + StrCat(output, maxlen, text); + for (int c = left; c < pad; c++) + StrCat(output, maxlen, " "); +} + +//---------------------------------------------------------------------------------------------------- +// Commands +//---------------------------------------------------------------------------------------------------- +public Action Cmd_Test(int client, int args) +{ + int target = client; + if (args >= 1) + { + char arg[64]; + GetCmdArg(1, arg, sizeof(arg)); + target = FindTarget(client, arg, false, false); + if (target == -1) + return Plugin_Handled; + } + + if (target == 0 || !IsPlayerAlive(target)) + { + ReplyToCommand(client, "[EventGreeting] The target must be an alive player."); + return Plugin_Handled; + } + + char eventName[EVENT_STR_LEN]; + if (FindActiveEventName(eventName, sizeof(eventName))) + ReplyToCommand(client, "[EventGreeting] Active event: %s", eventName); + else + { + strcopy(eventName, sizeof(eventName), PLACEHOLDER_EVENT); + ReplyToCommand(client, "[EventGreeting] No active event (EventNotifier %s), using \"%s\".", + g_bEventNotifier ? "has no events" : "not loaded", eventName); + } + + char text[2 * (MAX_NAME_CHARS + 8)]; + if (FormatGreeting(eventName, text, sizeof(text))) + { + ReplaceString(text, sizeof(text), "\n", "|\n|"); + ReplyToCommand(client, "|%s|", text); + } + + if (ShowGreeting(target, eventName)) + ReplyToCommand(client, "[EventGreeting] Shown to %N.", target); + else + ReplyToCommand(client, "[EventGreeting] Could not show the greeting (edicts, worldtext or empty name)."); + + return Plugin_Handled; +} + +public Action Cmd_Debug(int client, int args) +{ + ReplyToCommand(client, "[EventGreeting] sv_event_is_on %d, EventNotifier %s, entities %d", + g_cvEventIsOn.IntValue, g_bEventNotifier ? "loaded" : "missing", GetEntityCount()); + + float now = GetGameTime(); + bool shown = false; + for (int i = 1; i <= MaxClients; i++) + { + if (g_iTextRef[i] == INVALID_ENT_REFERENCE) + continue; + + char state[32]; + if (g_flExpireAt[i] == 0.0) + strcopy(state, sizeof(state), "waiting for movement"); + else + FormatEx(state, sizeof(state), "%.1fs left", g_flExpireAt[i] - now); + + ReplyToCommand(client, " %N: text %d, helper %d, %s", i, + LiveEntRef(g_iTextRef[i]), LiveEntRef(g_iHelperRef[i], HELPER_CLASS), state); + shown = true; + } + + if (!shown) + ReplyToCommand(client, "[EventGreeting] No live greetings."); + + return Plugin_Handled; +} diff --git a/Extend/scripting/Extend.sp b/Extend/scripting/Extend.sp index 6044439..985c35c 100644 --- a/Extend/scripting/Extend.sp +++ b/Extend/scripting/Extend.sp @@ -87,6 +87,7 @@ public void OnPluginStart() { RegAdminCmd("sm_extendmap", Command_Extend, ADMFLAG_GENERIC, "Add more time to mp_timelimit"); RegAdminCmd("sm_extend", Command_ExtendVote, ADMFLAG_GENERIC, "sm_extend [time] - Start an extendvote"); + RegAdminCmd("sm_settimeleft", Command_SetTimeLeft, ADMFLAG_GENERIC, "sm_settimeleft - Set the time left on the map"); // Relies on the m_fRoundStartTime gamerules prop, which only Counter-Strike games have EngineVersion engine = GetEngineVersion(); @@ -229,6 +230,53 @@ public Action Command_ExtendVote(int client, int argc) return Plugin_Handled; } +public Action Command_SetTimeLeft(int client, int argc) +{ + if (argc < 1) + { + ReplyToCommand(client, "[SM] Usage: sm_settimeleft "); + return Plugin_Handled; + } + + char sArgs[16]; + GetCmdArg(1, sArgs, sizeof(sArgs)); + + int iTargetMinutes; + if (!StringToIntEx(sArgs, iTargetMinutes) || iTargetMinutes < 1) + { + ReplyToCommand(client, "[SM] Invalid value, minutes must be 1 or more"); + return Plugin_Handled; + } + + int iOldLimit = g_cvarMpTimeLimit.IntValue; + int iTimeLeft; + if (iOldLimit <= 0 || !GetMapTimeLeft(iTimeLeft) || iTimeLeft == -1) + { + ReplyToCommand(client, "[SM] There is no time limit on this map, set mp_timelimit instead"); + return Plugin_Handled; + } + + // mp_timelimit counts from map start, so add the time already played. + // It only holds whole minutes, so the result is within 30 seconds of the target. + int iElapsed = iOldLimit * 60 - iTimeLeft; + int iNewLimit = RoundToNearest(float(iElapsed + iTargetMinutes * 60) / 60.0); + if (iNewLimit < 1) + iNewLimit = 1; + + g_cvarMpTimeLimit.IntValue = iNewLimit; + if (iNewLimit > iOldLimit) + CancelGameOver(); + + int iNewTimeLeft = iNewLimit * 60 - iElapsed; + if (iNewTimeLeft < 0) + iNewTimeLeft = 0; + + LogAction(client, -1, "\"%L\" set the time left to \"%d\" minutes (mp_timelimit %d -> %d)", client, iTargetMinutes, iOldLimit, iNewLimit); + PrintToChatAll("[SM] %N set the time left to %d:%02d.", client, iNewTimeLeft / 60, iNewTimeLeft % 60); + + return Plugin_Handled; +} + public Action Command_RoundExtend(int client, int argc) { float fElapsedTime = (GetGameTime() - GameRules_GetPropFloat("m_fRoundStartTime")) / 60.0; diff --git a/HostnameManager/scripting/HostnameManager.sp b/HostnameManager/scripting/HostnameManager.sp index 29a601d..4a80203 100644 --- a/HostnameManager/scripting/HostnameManager.sp +++ b/HostnameManager/scripting/HostnameManager.sp @@ -3,18 +3,26 @@ #include #undef REQUIRE_PLUGIN +#include #include #include #define REQUIRE_PLUGIN #pragma newdecls required -ConVar g_cvInfoMessage; ConVar g_cvHostname; ConVar g_cvFormattedHostname; +ConVar g_cvHostIP; +ConVar g_cvHostPort; +ConVar g_cvPassword; +ConVar g_cvMaxLength; +ConVar g_cvSendToClients; +// Dropped in this order while the hostname is longer than sm_hostname_max_length. +char g_sFoldOrder[][] = { "LagCompensation", "NoSteam" }; + +bool g_bCouchLoaded; bool g_bHHLoaded; -bool g_bNemesis; bool g_bSDLoaded; @@ -34,7 +42,12 @@ public Plugin myinfo = public void OnPluginStart() { g_cvHostname = FindConVar("hostname"); - g_cvFormattedHostname = CreateConVar("sm_hostname_format", "{HH}UNLOZE | {GM} | LagCompensation | NoSteam{SD}", "HH = HappyHour, , GM = GameMode, SD = StageDisplay"); + g_cvHostIP = FindConVar("hostip"); + g_cvHostPort = FindConVar("hostport"); + g_cvPassword = FindConVar("sv_password"); + g_cvFormattedHostname = CreateConVar("sm_hostname_format", "{HH}UNLOZE | {GM} | LagCompensation | NoSteam{SD}", "HH = HappyHour, GM = GameMode (Nemesis Zombie Escape > Couch Escape > Zombie Escape), SD = StageDisplay"); + g_cvMaxLength = CreateConVar("sm_hostname_max_length", "63", "Fold LagCompensation, then NoSteam, out of the hostname while it is longer than this many bytes (the server browser shows at most 63)", 0, true, 1.0, true, 127.0); + g_cvSendToClients = CreateConVar("sm_hostname_send_to_clients", "1", "Send the new hostname to connected clients so their scoreboard updates without a reconnect", 0, true, 0.0, true, 1.0); CreateTimer(60.0, TimerRepeat, INVALID_HANDLE, TIMER_REPEAT); @@ -46,17 +59,17 @@ public void OnPluginStart() //---------------------------------------------------------------------------------------------------- public void OnAllPluginsLoaded() { + g_bCouchLoaded = LibraryExists("Couch"); g_bHHLoaded = LibraryExists("HappyHour"); g_bSDLoaded = LibraryExists("StageDisplay"); +} - if((g_cvInfoMessage = FindConVar("sm_info_message_file")) == INVALID_HANDLE) - SetFailState("Failed to find sm_info_message_file cvar."); - - char sFile[PLATFORM_MAX_PATH]; - g_cvInfoMessage.GetString(sFile, sizeof(sFile)); - OnClassesPathChange(g_cvInfoMessage, "", sFile); - - HookConVarChange(g_cvInfoMessage, OnClassesPathChange); +//---------------------------------------------------------------------------------------------------- +// Purpose: server.cfg resets the hostname every map, and this also runs on a late load. +//---------------------------------------------------------------------------------------------------- +public void OnConfigsExecuted() +{ + RefreshHostname(); } //---------------------------------------------------------------------------------------------------- @@ -64,6 +77,9 @@ public void OnAllPluginsLoaded() //---------------------------------------------------------------------------------------------------- public void OnLibraryAdded(const char[] sName) { + if (strcmp(sName, "Couch", false) == 0) + g_bCouchLoaded = true; + if (strcmp(sName, "HappyHour", false) == 0) g_bHHLoaded = true; @@ -76,6 +92,13 @@ public void OnLibraryAdded(const char[] sName) //---------------------------------------------------------------------------------------------------- public void OnLibraryRemoved(const char[] sName) { + // Unloading Couch doesn't fire Couch_OnCouchRemoved, so drop the couch game mode here. + if (strcmp(sName, "Couch", false) == 0) + { + g_bCouchLoaded = false; + RefreshHostname(); + } + if (strcmp(sName, "HappyHour", false) == 0) g_bHHLoaded = false; @@ -130,28 +153,189 @@ public void RefreshHostname() else ReplaceString(sFormattedHostname, sizeof(sFormattedHostname), "{SD}", "", true); - if (g_bNemesis) + if (IsNemesisMap()) ReplaceString(sFormattedHostname, sizeof(sFormattedHostname), "{GM}", "Nemesis Zombie Escape", true); + else if (IsCouchPresent()) + ReplaceString(sFormattedHostname, sizeof(sFormattedHostname), "{GM}", "Couch Escape", true); else ReplaceString(sFormattedHostname, sizeof(sFormattedHostname), "{GM}", "Zombie Escape", true); - int iLength = strlen(sFormattedHostname); - if(iLength > 55) //if too long trim lagcomp - ReplaceString(sFormattedHostname, sizeof(sFormattedHostname), "LagCompensation | ", "", true); + TidyHostname(sFormattedHostname); + + for (int i = 0; i < sizeof(g_sFoldOrder) && strlen(sFormattedHostname) > g_cvMaxLength.IntValue; i++) + { + ReplaceString(sFormattedHostname, sizeof(sFormattedHostname), g_sFoldOrder[i], "", true); + TidyHostname(sFormattedHostname); + } + + char sCurrentHostname[128]; + g_cvHostname.GetString(sCurrentHostname, sizeof(sCurrentHostname)); + + if (strcmp(sFormattedHostname, sCurrentHostname, true) == 0) + return; g_cvHostname.SetString(sFormattedHostname, false, false); + + if (g_cvSendToClients.BoolValue) + SendHostname(sFormattedHostname); +} + +//---------------------------------------------------------------------------------------------------- +// Purpose: The scoreboard only reads the hostname from server_spawn, which the client's engine fires +// locally from svc_ServerInfo on connect. Send a copy straight to each client so it never +// reaches server-side listeners, and fill every field so other client listeners +// (mumble, abuse report, steam share) see the same values they got on connect. +//---------------------------------------------------------------------------------------------------- +void SendHostname(const char[] sHostname) +{ + Event hEvent = CreateEvent("server_spawn", true); + if (hEvent == null) + return; + + int iIP = g_cvHostIP.IntValue; + int iPort = g_cvHostPort.IntValue; + + char sAddress[32]; + Format(sAddress, sizeof(sAddress), "%d.%d.%d.%d:%d", (iIP >>> 24) & 0xFF, (iIP >>> 16) & 0xFF, (iIP >>> 8) & 0xFF, iIP & 0xFF, iPort); + + char sGame[32]; + GetGameFolderName(sGame, sizeof(sGame)); + + char sMap[PLATFORM_MAX_PATH]; + GetCurrentMap(sMap, sizeof(sMap)); + + char sPassword[64]; + g_cvPassword.GetString(sPassword, sizeof(sPassword)); + + hEvent.SetString("hostname", sHostname); + hEvent.SetString("address", sAddress); + hEvent.SetInt("ip", iIP); + hEvent.SetInt("port", iPort); + hEvent.SetString("game", sGame); + hEvent.SetString("mapname", sMap); + hEvent.SetInt("maxplayers", MaxClients); + hEvent.SetString("os", "LINUX"); + hEvent.SetBool("dedicated", IsDedicatedServer()); + hEvent.SetBool("password", sPassword[0] != '\0'); + + for (int client = 1; client <= MaxClients; client++) + { + if (!IsClientInGame(client) || IsFakeClient(client)) + continue; + + hEvent.FireToClient(client); + } + + // FireToClient does not free the event. + hEvent.Cancel(); +} + +//---------------------------------------------------------------------------------------------------- +// Purpose: The couch entity is purged on every round restart and respawned at round start, so a +// remembered placement counts too, otherwise the hostname would flicker each round. +//---------------------------------------------------------------------------------------------------- +bool IsCouchPresent() +{ + if (!g_bCouchLoaded) + return false; + + return Couch_GetCouch() != -1 || Couch_IsPlaced(); } //---------------------------------------------------------------------------------------------------- // Purpose: //---------------------------------------------------------------------------------------------------- -public void OnClassesPathChange(ConVar convar, const char[] oldValue, const char[] newValue) +public void Couch_OnCouchSpawned(int couch) { - char sFile[PLATFORM_MAX_PATH]; - BuildPath(Path_SM, sFile, sizeof(sFile), "%s", newValue); + RefreshHostname(); +} - if (StrContains(sFile, "nemesis", false) != -1) - g_bNemesis = true; - else - g_bNemesis = false; +//---------------------------------------------------------------------------------------------------- +// Purpose: Couch_Remove fires this before it forgets the placement, so wait a frame. +//---------------------------------------------------------------------------------------------------- +public void Couch_OnCouchRemoved() +{ + RequestFrame(Frame_RefreshHostname); +} + +//---------------------------------------------------------------------------------------------------- +// Purpose: +//---------------------------------------------------------------------------------------------------- +public void Frame_RefreshHostname(any data) +{ + RefreshHostname(); +} + +//---------------------------------------------------------------------------------------------------- +// Purpose: Empty tokens and folded tags leave separators and spaces behind. +//---------------------------------------------------------------------------------------------------- +void TidyHostname(char[] sText) +{ + DropEmptySeparators(sText); + CollapseSpaces(sText); +} + +//---------------------------------------------------------------------------------------------------- +// Purpose: {SD} brings its own " | ", so a format like "{GM} | {SD}" leaves "| |" with a stage and a +// trailing "|" without one. Drop any separator with nothing but spaces on one side. +//---------------------------------------------------------------------------------------------------- +void DropEmptySeparators(char[] sText) +{ + int iOut = 0; + for (int i = 0; sText[i] != '\0'; i++) + { + if (sText[i] == '|') + { + int iLast = iOut; + while (iLast > 0 && sText[iLast - 1] == ' ') + iLast--; + + if (iLast == 0 || sText[iLast - 1] == '|') + continue; + } + + sText[iOut++] = sText[i]; + } + + while (iOut > 0 && (sText[iOut - 1] == ' ' || sText[iOut - 1] == '|')) + iOut--; + + sText[iOut] = '\0'; +} + +//---------------------------------------------------------------------------------------------------- +// Purpose: Tokens that resolve to nothing leave their surrounding spaces behind, so squash any run +// of spaces down to one and trim the ends. +//---------------------------------------------------------------------------------------------------- +void CollapseSpaces(char[] sText) +{ + int iOut = 0; + for (int i = 0; sText[i] != '\0'; i++) + { + if (sText[i] == ' ' && (iOut == 0 || sText[iOut - 1] == ' ')) + continue; + + sText[iOut++] = sText[i]; + } + + if (iOut > 0 && sText[iOut - 1] == ' ') + iOut--; + + sText[iOut] = '\0'; +} + +//---------------------------------------------------------------------------------------------------- +// Purpose: Looked up every refresh because not every server runs the InfoMessage plugin, and it +// may load after us. +//---------------------------------------------------------------------------------------------------- +bool IsNemesisMap() +{ + ConVar cvInfoMessage = FindConVar("sm_info_message_file"); + if (cvInfoMessage == null) + return false; + + char sFile[PLATFORM_MAX_PATH]; + cvInfoMessage.GetString(sFile, sizeof(sFile)); + + return StrContains(sFile, "nemesis", false) != -1; } \ No newline at end of file diff --git a/Leader3/scripting/Leader3.sp b/Leader3/scripting/Leader3.sp index 5333f08..b1fdb03 100644 --- a/Leader3/scripting/Leader3.sp +++ b/Leader3/scripting/Leader3.sp @@ -15,6 +15,7 @@ #undef REQUIRE_PLUGIN #include +#include #define REQUIRE_PLUGIN #pragma newdecls required @@ -98,7 +99,15 @@ bool g_bLeaderWhitelisted[MAXPLAYERS + 1]; bool g_bForceLeaderMute; bool g_bForceMuted[MAXPLAYERS + 1]; +// Our own copy of ZR's zombie flag. ZR_IsClientZombie throws on dead clients and team is +// unreliable at death (ZR round-end balancing puts living zombies on CT), so player_death +// reads this instead. Set on infection, cleared on spawn/cure/disconnect like ZR's own flag. +bool g_bZombie[MAXPLAYERS + 1]; + bool g_bAFKManager; +bool g_bChatFilter2; +// ChatFilter2 safe chat per client, kept by ChatFilter2_OnSafeChatChanged so transmit hooks need no native call +bool g_bSafeChat[MAXPLAYERS + 1]; bool g_bWorldTextBroken; GlobalForward g_fwdOnLeaderAdded; @@ -227,6 +236,13 @@ public void OnPluginStart() AddMultiTargetFilter("@!leaders", Filter_NotLeaders, "everyone but the Leaders", false); AddMultiTargetFilter("@leader", Filter_Leader, "the Primary Leader", false); AddMultiTargetFilter("@!leader", Filter_NotLeader, "everyone but the Primary Leader", false); + + // Late load: pick up zombies infected before we were running. + for (int i = 1; i <= MaxClients; i++) + { + if (IsClientInGame(i)) + g_bZombie[i] = IsLivingZombie(i); + } } public void OnPluginEnd() @@ -240,18 +256,24 @@ public void OnPluginEnd() public void OnAllPluginsLoaded() { g_bAFKManager = LibraryExists("AFKManager"); + if (LibraryExists("ChatFilter2")) + Chat_OnChatFilter2Added(); } public void OnLibraryAdded(const char[] name) { if (StrEqual(name, "AFKManager")) g_bAFKManager = true; + else if (StrEqual(name, "ChatFilter2")) + Chat_OnChatFilter2Added(); } public void OnLibraryRemoved(const char[] name) { if (StrEqual(name, "AFKManager")) g_bAFKManager = false; + else if (StrEqual(name, "ChatFilter2")) + Chat_OnChatFilter2Removed(); } public void OnMapStart() @@ -357,6 +379,9 @@ public void OnClientDisconnect(int client) BaseComm_SetClientMute(client, false); g_bForceMuted[client] = false; } + + g_bZombie[client] = false; + g_bSafeChat[client] = false; } public void Event_RoundStart(Event event, const char[] name, bool dontBroadcast) @@ -368,6 +393,12 @@ public void Event_RoundStart(Event event, const char[] name, bool dontBroadcast) public void Event_PlayerSpawn(Event event, const char[] name, bool dontBroadcast) { int userid = event.GetInt("userid"); + + // Everyone spawns human (ZR clears its flag here too); infection after spawn sets it again. + int client = GetClientOfUserId(userid); + if (client > 0) + g_bZombie[client] = false; + // Attach effects slightly late: at spawn time ZR state and position may not be final. CreateTimer(0.3, Timer_ResumeEffects, userid, TIMER_FLAG_NO_MAPCHANGE); } @@ -386,9 +417,11 @@ public void Event_PlayerDeath(Event event, const char[] name, bool dontBroadcast if (client <= 0) return; - // Toll and announce only for an active (human) leader falling; an infected leader dying later as a zombie stays quiet. - // ZR_IsClientHuman throws on dead clients, so go by team: zombified leaders sit on T. - bool diedAsHuman = GetClientTeam(client) == CS_TEAM_CT; + // Toll and announce only for an active (human) leader falling. A leader who was infected, + // or picked as mother zombie, and then dies as a zombie stays quiet. ZR's fake infection + // death fires before ZR_OnClientInfected, so g_bZombie is still false for that one and the + // toll marks the infection. + bool diedAsHuman = !g_bZombie[client]; if (IsLeader(client) && diedAsHuman) { @@ -421,6 +454,8 @@ public void Event_PlayerTeam(Event event, const char[] name, bool dontBroadcast) public void ZR_OnClientInfected(int client, int attacker, bool motherInfect, bool respawnOverride, bool respawn) { + g_bZombie[client] = true; + char verb[80]; if (attacker > 0 && attacker <= MaxClients && attacker != client) Format(verb, sizeof(verb), "has been infected by \x04%N\x01", attacker); @@ -432,6 +467,8 @@ public void ZR_OnClientInfected(int client, int attacker, bool motherInfect, boo public void ZR_OnClientHumanPost(int client, bool respawn, bool protect) { + g_bZombie[client] = false; + if (IsEffectsActive(client)) Effects_Resume(client); } diff --git a/Leader3/scripting/leader3/chat.sp b/Leader3/scripting/leader3/chat.sp index b817ad7..7844fd1 100644 --- a/Leader3/scripting/leader3/chat.sp +++ b/Leader3/scripting/leader3/chat.sp @@ -18,6 +18,29 @@ public Action OnClientSayCommand(int client, const char[] command, const char[] return Plugin_Handled; } +//---------------------------------------------------------------------------------------------------- +// ChatFilter2 (optional): safe chat players get censored marker titles. +//---------------------------------------------------------------------------------------------------- +public void ChatFilter2_OnSafeChatChanged(int client, bool enabled) +{ + g_bSafeChat[client] = enabled; +} + +void Chat_OnChatFilter2Added() +{ + g_bChatFilter2 = true; + for (int i = 1; i <= MaxClients; i++) + g_bSafeChat[i] = IsClientInGame(i) && ChatFilter2_IsSafeChatEnabled(i); +} + +// Censored copies stay up but nobody counts as safe chat any more, so everyone sees the raw text. +void Chat_OnChatFilter2Removed() +{ + g_bChatFilter2 = false; + for (int i = 1; i <= MaxClients; i++) + g_bSafeChat[i] = false; +} + //---------------------------------------------------------------------------------------------------- // Force-mute: while any leader is talking, mute everyone without admin access. //---------------------------------------------------------------------------------------------------- diff --git a/Leader3/scripting/leader3/markers.sp b/Leader3/scripting/leader3/markers.sp index 733cbf6..a862839 100644 --- a/Leader3/scripting/leader3/markers.sp +++ b/Leader3/scripting/leader3/markers.sp @@ -1,6 +1,8 @@ //---------------------------------------------------------------------------------------------------- // Leader3 markers: unloze_ping prop_dynamic markers with point_worldtext titles. // The ArrayList is the authoritative store; entities are respawned from it every round. +// A title that ChatFilter2 censors gets a second text entity; SetTransmit shows the censored +// one to safe chat players and the raw one to everyone else. //---------------------------------------------------------------------------------------------------- enum struct Marker @@ -10,9 +12,11 @@ enum struct Marker int skin; float pos[3]; char title[128]; + char censoredTitle[128]; // empty when ChatFilter2 is missing or the title is clean float placedAt; int propRef; int textRef; + int censoredTextRef; } ArrayList g_alMarkers; @@ -97,9 +101,11 @@ void Marker_Place(int client, int skin) marker.skin = skin; marker.pos = pos; marker.title[0] = '\0'; + marker.censoredTitle[0] = '\0'; marker.placedAt = GetGameTime(); marker.propRef = INVALID_ENT_REFERENCE; marker.textRef = INVALID_ENT_REFERENCE; + marker.censoredTextRef = INVALID_ENT_REFERENCE; int idx = g_alMarkers.PushArray(marker); SpawnMarkerProp(idx); @@ -136,7 +142,10 @@ bool Marker_GetTitle(int client, int skin, char[] buf, int maxlen) if (marker.title[0] == '\0') return false; - strcopy(buf, maxlen, marker.title); + if (g_bSafeChat[client] && marker.censoredTitle[0] != '\0') + strcopy(buf, maxlen, marker.censoredTitle); + else + strcopy(buf, maxlen, marker.title); return true; } @@ -190,6 +199,17 @@ void UppercaseAllLowerTitle(char[] text) } } +void Marker_CensorTitle(Marker marker) +{ + marker.censoredTitle[0] = '\0'; + if (!g_bChatFilter2 || marker.title[0] == '\0') + return; + + strcopy(marker.censoredTitle, sizeof(marker.censoredTitle), marker.title); + if (!ChatFilter2_CensorText(marker.censoredTitle, sizeof(marker.censoredTitle))) + marker.censoredTitle[0] = '\0'; +} + void Marker_SetTitle(int client, const char[] text) { int userid = GetClientUserId(client); @@ -217,6 +237,7 @@ void Marker_SetTitle(int client, const char[] text) g_alMarkers.GetArray(lastIdx, marker); strcopy(marker.title, sizeof(marker.title), text); UppercaseAllLowerTitle(marker.title); + Marker_CensorTitle(marker); g_alMarkers.SetArray(lastIdx, marker); Marker_UpdateText(lastIdx); @@ -228,7 +249,23 @@ void Marker_SetTitle(int client, const char[] text) PrintToChat(client, "%sTitle removed from your \x04%s\x01 marker.", PREFIX, skinName); return; } - PrintToChatAll("%s\x04%N\x01 marked \x04%s\x01: \x04%s", PREFIX, client, skinName, marker.title); + + if (marker.censoredTitle[0] == '\0') + { + PrintToChatAll("%s\x04%N\x01 marked \x04%s\x01: \x04%s", PREFIX, client, skinName, marker.title); + return; + } + + for (int i = 1; i <= MaxClients; i++) + { + if (!IsClientInGame(i)) + continue; + + if (g_bSafeChat[i]) + PrintToChat(i, "%s\x04%N\x01 marked \x04%s\x01: \x04%s", PREFIX, client, skinName, marker.censoredTitle); + else + PrintToChat(i, "%s\x04%N\x01 marked \x04%s\x01: \x04%s", PREFIX, client, skinName, marker.title); + } } //---------------------------------------------------------------------------------------------------- @@ -266,18 +303,41 @@ void SpawnMarkerText(int idx) if (marker.title[0] == '\0' || g_bWorldTextBroken) return; + float pos[3]; + ComputeMarkerTextPos(marker, pos); + + int ent = SpawnWorldText(marker.title, pos); + if (ent == -1) + return; + marker.textRef = EntIndexToEntRef(ent); + + // The raw text is hidden from safe chat players even if the censored copy fails to spawn. + if (marker.censoredTitle[0] != '\0') + { + SDKHook(ent, SDKHook_SetTransmit, Hook_TitleRawTransmit); + + int censored = SpawnWorldText(marker.censoredTitle, pos); + if (censored != -1) + { + SDKHook(censored, SDKHook_SetTransmit, Hook_TitleCensoredTransmit); + marker.censoredTextRef = EntIndexToEntRef(censored); + } + } + + g_alMarkers.SetArray(idx, marker); +} + +int SpawnWorldText(const char[] text, const float pos[3]) +{ int ent = CreateEntityByName("point_worldtext"); if (ent == -1) { // Engine build without point_worldtext: titles stay chat-only for this map. g_bWorldTextBroken = true; LogMessage("point_worldtext could not be created; marker titles will not render in the world."); - return; + return -1; } - char text[192]; - Format(text, sizeof(text), "%s", marker.title); - DispatchKeyValue(ent, "message", text); DispatchKeyValue(ent, "font", "10"); DispatchKeyValue(ent, "textsize", "12"); @@ -285,13 +345,18 @@ void SpawnMarkerText(int idx) DispatchKeyValue(ent, "orientation", "1"); DispatchKeyValue(ent, "rainbow", "1"); DispatchSpawn(ent); - - float pos[3]; - ComputeMarkerTextPos(marker, pos); TeleportEntity(ent, pos, NULL_VECTOR, NULL_VECTOR); + return ent; +} - marker.textRef = EntIndexToEntRef(ent); - g_alMarkers.SetArray(idx, marker); +public Action Hook_TitleRawTransmit(int ent, int client) +{ + return g_bSafeChat[client] ? Plugin_Handled : Plugin_Continue; +} + +public Action Hook_TitleCensoredTransmit(int ent, int client) +{ + return g_bSafeChat[client] ? Plugin_Continue : Plugin_Handled; } void ComputeMarkerTextPos(const Marker marker, float pos[3]) @@ -339,33 +404,42 @@ void Marker_UpdateText(int idx) Marker marker; g_alMarkers.GetArray(idx, marker); - if (marker.title[0] == '\0') + int ent = LiveEntRef(marker.textRef, "point_worldtext"); + int censored = LiveEntRef(marker.censoredTextRef, "point_worldtext"); + + // No title, a lost entity, or a title that gained or lost its censored copy: respawn. + // The last case is rare, and respawning keeps the transmit hooks in step with the entities. + if (marker.title[0] == '\0' || ent == -1 || (marker.censoredTitle[0] != '\0') != (censored != -1)) { KillEntRef(marker.textRef, "point_worldtext"); + KillEntRef(marker.censoredTextRef, "point_worldtext"); marker.textRef = INVALID_ENT_REFERENCE; + marker.censoredTextRef = INVALID_ENT_REFERENCE; g_alMarkers.SetArray(idx, marker); - return; - } - - int ent = LiveEntRef(marker.textRef, "point_worldtext"); - if (ent == -1) - { SpawnMarkerText(idx); return; } - SetVariantString(marker.title); - AcceptEntityInput(ent, "SetText"); - float pos[3]; ComputeMarkerTextPos(marker, pos); + + SetVariantString(marker.title); + AcceptEntityInput(ent, "SetText"); TeleportEntity(ent, pos, NULL_VECTOR, NULL_VECTOR); + + if (censored != -1) + { + SetVariantString(marker.censoredTitle); + AcceptEntityInput(censored, "SetText"); + TeleportEntity(censored, pos, NULL_VECTOR, NULL_VECTOR); + } } void Marker_KillEnts(Marker marker) { KillEntRef(marker.propRef, "prop_dynamic"); KillEntRef(marker.textRef, "point_worldtext"); + KillEntRef(marker.censoredTextRef, "point_worldtext"); } void KillEntRef(int ref, const char[] expectedClass) @@ -400,6 +474,7 @@ void Markers_OnRoundStart() g_alMarkers.GetArray(i, marker); marker.propRef = INVALID_ENT_REFERENCE; marker.textRef = INVALID_ENT_REFERENCE; + marker.censoredTextRef = INVALID_ENT_REFERENCE; g_alMarkers.SetArray(i, marker); SpawnMarkerProp(i); diff --git a/NameFilter2/configs/NameFilter2.cfg b/NameFilter2/configs/NameFilter2.cfg index e5cea36..7b1ac97 100644 --- a/NameFilter2/configs/NameFilter2.cfg +++ b/NameFilter2/configs/NameFilter2.cfg @@ -13,7 +13,7 @@ // at least this many letters/digits is kept as-is, unicode decoration // and all, unless an advert or banned filter matches. An admin can // target such a name by its typeable part. 0 disables the exemption - "keep_typeable_run" "5" + "keep_typeable_run" "4" // non-ASCII characters that are always kept. // accented Latin letters (À-ÿ, Latin Extended-A) are also kept, but only @@ -55,6 +55,8 @@ "У" "Y" "З" "3" // Cyrillic mirrored/aesthetic lookalikes + "Ш" "W" + "ш" "w" "Я" "R" "я" "r" "И" "N" @@ -64,6 +66,18 @@ "м" "m" "н" "h" "т" "t" + "є" "e" + "Є" "E" + "ц" "u" + "п" "n" + "г" "r" + "Г" "r" + "ґ" "r" + "Ґ" "r" + "ь" "b" + "Ь" "b" + "ч" "4" + "Ч" "4" // Cyrillic with diacritics, same lookalikes as their base letters "Ѐ" "E" "Ё" "E" @@ -110,6 +124,8 @@ "ό" "o" "ώ" "w" // Greek aesthetic lookalikes + "Ξ" "E" + "ξ" "e" "Λ" "A" "Σ" "E" "Δ" "A" @@ -119,11 +135,110 @@ "μ" "u" "ω" "w" "η" "n" + "ι" "i" + "ρ" "p" + "κ" "k" + "τ" "t" + "υ" "u" + "ε" "e" + "ς" "c" + "χ" "x" + "γ" "y" + "π" "n" + "σ" "o" // math symbols used as letters "∂" "d" "∑" "E" } + // Cyrillic spelled out phonetically (simplified BGN/PCGN), for words that + // are really Cyrillic. Runs before "confusables"; a Latin word with only + // lookalike Cyrillic mixed in ("аdmin"), or a word mixing in Greek or styled + // letters ("ιηƒιηιтє"), is left to the confusables instead, and only its + // Cyrillic letters without a confusable are spelled out. + // key = the Cyrillic letter (raw UTF-8), value = Latin spelling + "transliterate" + { + // Russian + "а" "a" + "б" "b" + "в" "v" + "г" "g" + "д" "d" + "е" "e" + "ё" "e" + "ж" "zh" + "з" "z" + "и" "i" + "й" "y" + "к" "k" + "л" "l" + "м" "m" + "н" "n" + "о" "o" + "п" "p" + "р" "r" + "с" "s" + "т" "t" + "у" "u" + "ф" "f" + "х" "kh" + "ц" "ts" + "ч" "ch" + "ш" "sh" + "щ" "shch" + "ъ" "" + "ы" "y" + "ь" "" + "э" "e" + "ю" "yu" + "я" "ya" + "А" "A" + "Б" "B" + "В" "V" + "Г" "G" + "Д" "D" + "Е" "E" + "Ё" "E" + "Ж" "Zh" + "З" "Z" + "И" "I" + "Й" "Y" + "К" "K" + "Л" "L" + "М" "M" + "Н" "N" + "О" "O" + "П" "P" + "Р" "R" + "С" "S" + "Т" "T" + "У" "U" + "Ф" "F" + "Х" "Kh" + "Ц" "Ts" + "Ч" "Ch" + "Ш" "Sh" + "Щ" "Shch" + "Ъ" "" + "Ы" "Y" + "Ь" "" + "Э" "E" + "Ю" "Yu" + "Я" "Ya" + // Ukrainian/Belarusian + "і" "i" + "ї" "yi" + "є" "ye" + "ґ" "g" + "ў" "u" + "І" "I" + "Ї" "Yi" + "Є" "Ye" + "Ґ" "G" + "Ў" "U" + } + // regexes (case-insensitive) whose matches are REMOVED from the name; // the rest of the name is kept. Applied to the pure-ASCII folded name. "adverts" @@ -144,7 +259,9 @@ "6" "@((!?)me|(c?)t(s?)|(!?)admins|(!?)friends|random((c?)t?)|humans|spec|alive|dead|aim|bots)" } - // replacement names; picked deterministically (client % count, next-free probe) + // replacement names; picked by Steam account (account id % count, next-free + // probe), so a player keeps the same one across visits. Reordering or + // adding names reshuffles who gets which "names" { "1" "Reimu Hakurei" diff --git a/NameFilter2/scripting/NameFilter2.sp b/NameFilter2/scripting/NameFilter2.sp index 58b4b37..9320d4a 100644 --- a/NameFilter2/scripting/NameFilter2.sp +++ b/NameFilter2/scripting/NameFilter2.sp @@ -9,6 +9,7 @@ #define MAX_STACKED_MARKS 2 // combining marks allowed on one letter (Vietnamese needs 2) #define RELOAD_FILE "data/namefilter2_reload.dat" #define RELOAD_MAX_AGE 120 // seconds; older saves are from a previous server run +#define MAX_RENAME_RETRIES 2 enum struct SavedName { @@ -18,10 +19,21 @@ enum struct SavedName char sCurrent[MAX_NAME_LENGTH]; } +// a filtered player who left; their client keeps the name we gave them +// (ChangeName runs `name` on the client), so they rejoin wearing it +enum struct PastName +{ + char sOriginal[MAX_NAME_LENGTH]; + char sAssigned[MAX_NAME_LENGTH]; + bool bReplaced; +} + char g_sOriginalName[MAXPLAYERS + 1][MAX_NAME_LENGTH]; char g_sAssignedName[MAXPLAYERS + 1][MAX_NAME_LENGTH]; // the filtered name we gave the player +char g_sBlockEventName[MAXPLAYERS + 1][MAX_NAME_LENGTH]; // raw name whose player_changename to hide +int g_iRenameRetries[MAXPLAYERS + 1]; ArrayList g_SavedNames; // original names saved over a plugin reload -int g_iBlockNameChangeEvents[MAXPLAYERS + 1] = {0, ...}; +StringMap g_PastNames; // engine auth id -> PastName, for the whole server run bool g_bFilteredOnConnect[MAXPLAYERS + 1]; bool g_bReplacedOnConnect[MAXPLAYERS + 1]; bool g_bLastFilterReplaced; // whether the last FilterName() assigned a replacement name @@ -31,6 +43,8 @@ ArrayList g_BannedExprs; ArrayList g_ReplacementNames; ArrayList g_ConfusableFrom; ArrayList g_ConfusableTo; +StringMap g_ConfusableSet; // confusable keys, for spotting spoofed Latin words +StringMap g_Transliterate; // Cyrillic letter -> phonetic Latin ArrayList g_WhitelistCps; int g_iMinNameLength = 2; int g_iMinSurvivedPct = 50; @@ -52,6 +66,9 @@ public void OnPluginStart() RegConsoleCmd("sm_originalname", Command_OriginalName, "Show a player's original name"); RegConsoleCmd("sm_changednames", Command_ChangedNames, "List all players whose names were changed"); RegAdminCmd("sm_namefilter2_reload", Command_Reload, ADMFLAG_CONFIG, "Reload the NameFilter2 config"); + RegAdminCmd("sm_namefilter2_test", Command_Test, ADMFLAG_CONFIG, "Show what the filter makes of a name"); + + g_PastNames = new StringMap(); LoadConfig(); LoadSavedNames(); @@ -88,6 +105,25 @@ public void OnPluginEnd() hFile.WriteString(sCurrent, true); } + // userid 0 ends the client list; the past names follow + hFile.WriteInt32(0); + + StringMapSnapshot snap = g_PastNames.Snapshot(); + for(int i = 0; i < snap.Length; i++) + { + char sAuth[64]; + snap.GetKey(i, sAuth, sizeof(sAuth)); + + PastName past; + g_PastNames.GetArray(sAuth, past, sizeof(past)); + + hFile.WriteString(sAuth, true); + hFile.WriteString(past.sOriginal, true); + hFile.WriteString(past.sAssigned, true); + hFile.WriteInt8(past.bReplaced); + } + delete snap; + delete hFile; } @@ -106,13 +142,25 @@ void LoadSavedNames() if(hFile.ReadInt32(iSaved) && GetTime() - iSaved <= RELOAD_MAX_AGE) { SavedName saved; - while(hFile.ReadInt32(saved.iUserId) + while(hFile.ReadInt32(saved.iUserId) && saved.iUserId && hFile.ReadString(saved.sOriginal, sizeof(saved.sOriginal)) != -1 && hFile.ReadString(saved.sAssigned, sizeof(saved.sAssigned)) != -1 && hFile.ReadString(saved.sCurrent, sizeof(saved.sCurrent)) != -1) { g_SavedNames.PushArray(saved); } + + char sAuth[64]; + PastName past; + int iReplaced; + while(hFile.ReadString(sAuth, sizeof(sAuth)) != -1 + && hFile.ReadString(past.sOriginal, sizeof(past.sOriginal)) != -1 + && hFile.ReadString(past.sAssigned, sizeof(past.sAssigned)) != -1 + && hFile.ReadInt8(iReplaced)) + { + past.bReplaced = iReplaced != 0; + g_PastNames.SetArray(sAuth, past, sizeof(past)); + } } delete hFile; @@ -145,7 +193,8 @@ bool RestoreSavedName(int client, const char[] sName) public void OnClientConnected(int client) { - g_iBlockNameChangeEvents[client] = 0; + g_sBlockEventName[client][0] = '\0'; + g_iRenameRetries[client] = 0; g_bFilteredOnConnect[client] = false; g_bReplacedOnConnect[client] = false; g_sAssignedName[client][0] = '\0'; @@ -169,6 +218,12 @@ public void OnClientConnected(int client) } } +public void OnClientAuthorized(int client, const char[] auth) +{ + if(!IsFakeClient(client) && IsClientInGame(client)) + CheckRejoinedName(client); +} + public void OnClientPutInServer(int client) { if(IsFakeClient(client)) @@ -177,12 +232,17 @@ public void OnClientPutInServer(int client) char sName[MAX_NAME_LENGTH]; GetClientName(client, sName, sizeof(sName)); + // the client can re-send its raw name during signon, undoing the + // OnClientConnected rename (or bringing a new name with it) + char sRaw[MAX_NAME_LENGTH]; + strcopy(sRaw, sizeof(sRaw), sName); + if(FilterName(client, sName)) { g_bFilteredOnConnect[client] = true; if(g_bLastFilterReplaced) g_bReplacedOnConnect[client] = true; - g_iBlockNameChangeEvents[client] = 2; + strcopy(g_sOriginalName[client], MAX_NAME_LENGTH, sRaw); strcopy(g_sAssignedName[client], MAX_NAME_LENGTH, sName); SetClientName(client, sName); } @@ -192,21 +252,100 @@ public void OnClientPutInServer(int client) NotifyAdminsFiltered(client, sName, g_bReplacedOnConnect[client]); NotifyClientRenamed(client, sName, g_bReplacedOnConnect[client]); } + else if(IsClientAuthorized(client)) + CheckRejoinedName(client); } public void OnClientDisconnect(int client) { + if(!IsFakeClient(client) && IsClientAuthorized(client)) + { + char sAuth[64]; + if(GetClientAuthId(client, AuthId_Engine, sAuth, sizeof(sAuth))) + { + if(g_sAssignedName[client][0]) + { + PastName past; + strcopy(past.sOriginal, sizeof(past.sOriginal), g_sOriginalName[client]); + strcopy(past.sAssigned, sizeof(past.sAssigned), g_sAssignedName[client]); + past.bReplaced = IsReplacementName(g_sAssignedName[client]); + g_PastNames.SetArray(sAuth, past, sizeof(past)); + } + else + g_PastNames.Remove(sAuth); + } + } + g_sOriginalName[client][0] = '\0'; g_sAssignedName[client][0] = '\0'; - g_iBlockNameChangeEvents[client] = 0; + g_sBlockEventName[client][0] = '\0'; + g_iRenameRetries[client] = 0; g_bFilteredOnConnect[client] = false; g_bReplacedOnConnect[client] = false; } +// a player whose client still carries a name we gave them earlier gets the +// notices again, with the original restored when this server run saw it. +// Runs once per connection: whichever of auth and put-in-server comes last +void CheckRejoinedName(int client) +{ + if(g_sAssignedName[client][0] || g_bFilteredOnConnect[client]) + return; + + char sName[MAX_NAME_LENGTH]; + GetClientName(client, sName, sizeof(sName)); + + char sAuth[64]; + PastName past; + if(GetClientAuthId(client, AuthId_Engine, sAuth, sizeof(sAuth)) + && g_PastNames.GetArray(sAuth, past, sizeof(past)) + && StrEqual(sName, past.sAssigned)) + { + strcopy(g_sOriginalName[client], MAX_NAME_LENGTH, past.sOriginal); + strcopy(g_sAssignedName[client], MAX_NAME_LENGTH, past.sAssigned); + g_bFilteredOnConnect[client] = true; + g_bReplacedOnConnect[client] = past.bReplaced; + + NotifyAdminsFiltered(client, sName, past.bReplaced); + NotifyClientRenamed(client, sName, past.bReplaced); + return; + } + + if(IsReplacementName(sName)) + { + NotifyAdminsUnknownOriginal(client, sName); + NotifyClientRenamed(client, sName, true); + } +} + +// true if the change from the player's original name to sNewName only +// trimmed or collapsed spaces and removed invisible characters +bool IsCosmeticChange(int client, const char[] sNewName, bool bReplaced) +{ + if(bReplaced) + return false; + + char sTidied[MAX_NAME_LENGTH]; + strcopy(sTidied, sizeof(sTidied), g_sOriginalName[client]); + StripInvisible(sTidied); + NormalizeWhitespace(sTidied); + + return StrEqual(sTidied, sNewName); +} + +// cosmetic changes get only the server console line void NotifyAdminsFiltered(int client, const char[] sNewName, bool bReplaced) { - PrintToServer("[NameFilter2] \"%s\" (#%d) was %s \"%s\"", g_sOriginalName[client], GetClientUserId(client), - bReplaced ? "given replacement name" : "renamed to", sNewName); + char sOriginal[MAX_NAME_LENGTH]; + SanitizeForLog(g_sOriginalName[client], sOriginal, sizeof(sOriginal)); + + bool bCosmetic = IsCosmeticChange(client, sNewName, bReplaced); + + PrintToServer("[NameFilter2] \"%s\" (#%d) was %s \"%s\"", sOriginal, GetClientUserId(client), + bReplaced ? "given replacement name" : bCosmetic ? "tidied to" : "renamed to", sNewName); + + if(bCosmetic) + return; for(int i = 1; i <= MaxClients; i++) { @@ -216,29 +355,57 @@ void NotifyAdminsFiltered(int client, const char[] sNewName, bool bReplaced) if(!CheckCommandAccess(i, "sm_namefilter2_notify", ADMFLAG_GENERIC)) continue; - PrintToChat(i, CHAT_PREFIX ... " \x07FF6060%s\x01 (#%d) was renamed to \x0760FF60%s\x01", g_sOriginalName[client], GetClientUserId(client), sNewName); + PrintToChat(i, CHAT_PREFIX ... " \x07FF6060%s\x01 (#%d) was renamed to \x0760FF60%s\x01", sOriginal, GetClientUserId(client), sNewName); + } +} + +void NotifyAdminsUnknownOriginal(int client, const char[] sName) +{ + PrintToServer("[NameFilter2] \"%s\" (#%d) joined with a replacement name, original name unknown", sName, GetClientUserId(client)); + + for(int i = 1; i <= MaxClients; i++) + { + if(!IsClientInGame(i) || IsFakeClient(i)) + continue; + + if(!CheckCommandAccess(i, "sm_namefilter2_notify", ADMFLAG_GENERIC)) + continue; + + PrintToChat(i, CHAT_PREFIX ... " \x0760FF60%s\x01 (#%d) joined with a replacement name, original name unknown", sName, GetClientUserId(client)); } } void NotifyClientRenamed(int client, const char[] sNewName, bool bReplaced) { + if(IsCosmeticChange(client, sNewName, bReplaced)) + return; + if(bReplaced) PrintToChat(client, CHAT_PREFIX ... " Your name was unable to be filtered and was replaced with \x0760FF60%s\x01.", sNewName); else PrintToChat(client, CHAT_PREFIX ... " Your name was filtered to \x0760FF60%s\x01.", sNewName); } +// changes to the name we gave the player are ours and stay hidden, as is the +// event of a raw change whose SayText2 we filtered. Matching by name instead +// of counting messages means a message that never arrives cannot leave a +// stale block that lets the player's next rename skip the filter public Action Event_ChangeName(Event event, const char[] name, bool dontBroadcast) { int client = GetClientOfUserId(event.GetInt("userid")); - if(g_iBlockNameChangeEvents[client]) - { - g_iBlockNameChangeEvents[client]--; - SetEventBroadcast(event, true); - return Plugin_Handled; - } + if(!client) + return Plugin_Continue; - return Plugin_Continue; + char sNewName[MAX_NAME_LENGTH]; + event.GetString("newname", sNewName, sizeof(sNewName)); + + if(g_sBlockEventName[client][0] && StrEqual(sNewName, g_sBlockEventName[client])) + g_sBlockEventName[client][0] = '\0'; + else if(!g_sAssignedName[client][0] || !StrEqual(sNewName, g_sAssignedName[client])) + return Plugin_Continue; + + SetEventBroadcast(event, true); + return Plugin_Handled; } public Action UserMessage_SayText2(UserMsg msg_id, BfRead msg, const int[] players, int playersNum, bool reliable, bool init) @@ -278,16 +445,10 @@ public Action UserMessage_SayText2(UserMsg msg_id, BfRead msg, const int[] playe if(client < 1 || client > MaxClients) return Plugin_Continue; - if(g_iBlockNameChangeEvents[client]) - { - g_iBlockNameChangeEvents[client]--; - return Plugin_Handled; - } - - // the name we gave them (Timer_ChangeName's re-apply or any later echo of - // it); let it broadcast but keep the original it was filtered from + // the name we gave them: SetClientName's own change, or any later echo + // of it; keep the original it was filtered from if(g_sAssignedName[client][0] && StrEqual(sNewName, g_sAssignedName[client])) - return Plugin_Continue; + return Plugin_Handled; strcopy(g_sOriginalName[client], MAX_NAME_LENGTH, sNewName); g_sAssignedName[client][0] = '\0'; @@ -295,14 +456,13 @@ public Action UserMessage_SayText2(UserMsg msg_id, BfRead msg, const int[] playe if(FilterName(client, sNewName)) { strcopy(g_sAssignedName[client], MAX_NAME_LENGTH, sNewName); + strcopy(g_sBlockEventName[client], MAX_NAME_LENGTH, g_sOriginalName[client]); + g_iRenameRetries[client] = 0; // CCSPlayer::ChangeName sends this SayText2 before it fires the event // and stores the new name, so a SetClientName from in here is undone // as soon as we return. Re-apply later instead, even when the filtered - // name equals the old one: 3 = this change's event, then the timer's - // SayText2 and event - g_iBlockNameChangeEvents[client] = 3; - + // name equals the old one DataPack pack = new DataPack(); pack.WriteCell(GetClientUserId(client)); pack.WriteString(sNewName); @@ -321,18 +481,51 @@ public Action Timer_ChangeName(Handle timer, any data) DataPack pack = view_as(data); pack.Reset(); - int client = GetClientOfUserId(pack.ReadCell()); + int iUserId = pack.ReadCell(); + int client = GetClientOfUserId(iUserId); char sName[MAX_NAME_LENGTH]; pack.ReadString(sName, sizeof(sName)); bool bReplaced = view_as(pack.ReadCell()); delete pack; - if(client) + // a later rename by the player superseded this one + if(!client || !StrEqual(sName, g_sAssignedName[client])) + return Plugin_Stop; + + SetClientName(client, sName); + NotifyAdminsFiltered(client, sName, bReplaced); + NotifyClientRenamed(client, sName, bReplaced); + + CreateTimer(0.5, Timer_VerifyName, iUserId); + + return Plugin_Stop; +} + +// the rename should have taken effect inside SetClientName; if it did not, +// say so and try again, so a player never keeps a raw name unnoticed +public Action Timer_VerifyName(Handle timer, int iUserId) +{ + int client = GetClientOfUserId(iUserId); + if(!client || !g_sAssignedName[client][0]) + return Plugin_Stop; + + char sName[MAX_NAME_LENGTH]; + GetClientName(client, sName, sizeof(sName)); + if(StrEqual(sName, g_sAssignedName[client])) + return Plugin_Stop; + + char sSafe[MAX_NAME_LENGTH]; + SanitizeForLog(sName, sSafe, sizeof(sSafe)); + + bool bRetry = g_iRenameRetries[client]++ < MAX_RENAME_RETRIES; + PrintToServer("[NameFilter2] rename of #%d to \"%s\" did not stick (name is \"%s\")%s", iUserId, + g_sAssignedName[client], sSafe, bRetry ? ", retrying" : ""); + + if(bRetry) { - SetClientName(client, sName); - NotifyAdminsFiltered(client, sName, bReplaced); - NotifyClientRenamed(client, sName, bReplaced); + SetClientName(client, g_sAssignedName[client]); + CreateTimer(0.5, Timer_VerifyName, iUserId); } return Plugin_Stop; @@ -365,13 +558,11 @@ public Action Command_OriginalName(int client, int args) for(int i = 0; i < iCount; i++) { - char sCurrent[MAX_NAME_LENGTH]; - GetClientName(aTargets[i], sCurrent, sizeof(sCurrent)); - - if(StrEqual(sCurrent, g_sOriginalName[aTargets[i]])) - ReplyToCommand(client, "[SM] %N's name was not changed.", aTargets[i]); + char sLine[256]; + if(DescribeNameChange(aTargets[i], sLine, sizeof(sLine))) + ReplyToCommand(client, "[SM] %s", sLine); else - ReplyToCommand(client, "[SM] %N's original name: %s", aTargets[i], g_sOriginalName[aTargets[i]]); + ReplyToCommand(client, "[SM] %N's name was not changed.", aTargets[i]); } return Plugin_Handled; @@ -380,18 +571,17 @@ public Action Command_OriginalName(int client, int args) public Action Command_ChangedNames(int client, int args) { int iFound = 0; - char sCurrent[MAX_NAME_LENGTH]; + char sLine[256]; for(int i = 1; i <= MaxClients; i++) { if(!IsClientConnected(i) || IsFakeClient(i)) continue; - GetClientName(i, sCurrent, sizeof(sCurrent)); - if(StrEqual(sCurrent, g_sOriginalName[i])) + if(!DescribeNameChange(i, sLine, sizeof(sLine))) continue; - PrintToConsole(client, "%s - original name: %s", sCurrent, g_sOriginalName[i]); + PrintToConsole(client, "%s", sLine); iFound++; } @@ -403,6 +593,92 @@ public Action Command_ChangedNames(int client, int args) return Plugin_Handled; } +// " - original name: " for a player whose name we changed, +// including one who rejoined wearing a replacement name; false otherwise +bool DescribeNameChange(int client, char[] sLine, int Length) +{ + char sCurrent[MAX_NAME_LENGTH]; + GetClientName(client, sCurrent, sizeof(sCurrent)); + + char sOriginal[MAX_NAME_LENGTH]; + SanitizeForLog(g_sOriginalName[client], sOriginal, sizeof(sOriginal)); + + if(g_sAssignedName[client][0]) + { + if(StrEqual(sCurrent, g_sAssignedName[client])) + FormatEx(sLine, Length, "%s - original name: %s", sCurrent, sOriginal); + else + FormatEx(sLine, Length, "%s - original name: %s (filter did not stick, expected %s)", sCurrent, sOriginal, g_sAssignedName[client]); + return true; + } + + if(!StrEqual(sCurrent, g_sOriginalName[client])) + { + FormatEx(sLine, Length, "%s - original name: %s", sCurrent, sOriginal); + return true; + } + + if(IsReplacementName(sCurrent)) + { + FormatEx(sLine, Length, "%s - original name: unknown (joined with a replacement name)", sCurrent); + return true; + } + + return false; +} + +// a configured replacement name, or AssignReplacementName's " " +// fallback for when they are all taken +bool IsReplacementName(const char[] sName) +{ + char sCandidate[MAX_NAME_LENGTH]; + for(int i = 0; i < g_ReplacementNames.Length; i++) + { + g_ReplacementNames.GetString(i, sCandidate, sizeof(sCandidate)); + + int iLen = strlen(sCandidate); + if(strncmp(sName, sCandidate, iLen) != 0) + continue; + + if(sName[iLen] == '\0') + return true; + + if(sName[iLen] != ' ' || sName[iLen + 1] == '\0') + continue; + + int k = iLen + 1; + while(IsCharNumeric(sName[k])) + k++; + if(sName[k] == '\0') + return true; + } + + return false; +} + +public Action Command_Test(int client, int args) +{ + if(args < 1) + { + ReplyToCommand(client, "[SM] Usage: sm_namefilter2_test "); + return Plugin_Handled; + } + + char sName[MAX_NAME_LENGTH]; + GetCmdArgString(sName, sizeof(sName)); + StripQuotes(sName); + + char sIn[MAX_NAME_LENGTH]; + SanitizeForLog(sName, sIn, sizeof(sIn)); + + // client 0 only steers which replacement name is picked + bool bChanged = FilterName(0, sName); + ReplyToCommand(client, "[SM] \"%s\" -> \"%s\"%s", sIn, sName, + g_bLastFilterReplaced ? " (replacement)" : (bChanged ? "" : " (unchanged)")); + + return Plugin_Handled; +} + public Action Command_Reload(int client, int args) { LoadConfig(); @@ -433,6 +709,8 @@ void LoadConfig() delete g_ReplacementNames; delete g_ConfusableFrom; delete g_ConfusableTo; + delete g_ConfusableSet; + delete g_Transliterate; delete g_WhitelistCps; static char sConfigFile[PLATFORM_MAX_PATH]; @@ -472,6 +750,7 @@ void LoadConfig() g_ConfusableFrom = new ArrayList(ByteCountToCells(16)); g_ConfusableTo = new ArrayList(ByteCountToCells(16)); + g_ConfusableSet = new StringMap(); if(Config.JumpToKey("confusables")) { if(Config.GotoFirstSubKey(false)) @@ -486,6 +765,7 @@ void LoadConfig() { g_ConfusableFrom.PushString(sFrom); g_ConfusableTo.PushString(sBuffer); + g_ConfusableSet.SetValue(sFrom, true); } } while(Config.GotoNextKey(false)); Config.GoBack(); @@ -493,6 +773,25 @@ void LoadConfig() Config.GoBack(); } + g_Transliterate = new StringMap(); + if(Config.JumpToKey("transliterate")) + { + if(Config.GotoFirstSubKey(false)) + { + do + { + char sFrom[16]; + Config.GetSectionName(sFrom, sizeof(sFrom)); + Config.GetString(NULL_STRING, sBuffer, sizeof(sBuffer)); + + if(sFrom[0]) + g_Transliterate.SetString(sFrom, sBuffer); + } while(Config.GotoNextKey(false)); + Config.GoBack(); + } + Config.GoBack(); + } + g_AdvertExprs = new ArrayList(); if(Config.JumpToKey("adverts")) { @@ -565,8 +864,10 @@ bool FilterName(int client, char[] sName, int Length = MAX_NAME_LENGTH) char sBefore[MAX_NAME_LENGTH]; strcopy(sBefore, sizeof(sBefore), sName); - // applies to kept names too, so none can hide characters or pose as another + // applies to kept names too, so none can hide characters or pose as + // another ("Name " next to "Name") StripInvisible(sName); + NormalizeWhitespace(sName); char sClean[MAX_NAME_LENGTH]; strcopy(sClean, sizeof(sClean), sName); @@ -576,6 +877,7 @@ bool FilterName(int client, char[] sName, int Length = MAX_NAME_LENGTH) bool bKeepOriginal = HasTypeableRun(sClean); bool bContentRemoved = false; + TransliterateCyrillic(sName, Length); ApplyConfusables(sName, Length); int iLettersBefore = CountLetters(sName); @@ -711,6 +1013,34 @@ void StripInvisible(char[] sName) sName[w] = '\0'; } +// copy of a name that is safe to print: invalid UTF-8 and control +// characters become '?' (journald hides whole lines containing them) +void SanitizeForLog(const char[] sIn, char[] sOut, int Length) +{ + int r = 0; + int w = 0; + + while(sIn[r] != '\0') + { + int rStart = r; + int cp = DecodeUTF8Char(sIn, r); + + if(cp < 0 || cp < 0x20 || (cp >= 0x7F && cp <= 0x9F)) + { + if(w + 1 >= Length) + break; + sOut[w++] = '?'; + continue; + } + + if(w + (r - rStart) >= Length) + break; + for(int k = rStart; k < r; k++) + sOut[w++] = sIn[k]; + } + sOut[w] = '\0'; +} + bool IsInvisibleCp(int cp) { return cp < 0x20 || (cp >= 0x7F && cp <= 0x9F) // C0/C1 controls, DEL @@ -741,6 +1071,126 @@ bool IsCombiningMarkCp(int cp) || (cp >= 0xFE20 && cp <= 0xFE2F); // half marks } +// spells out each word containing Cyrillic phonetically (Киллер -> Killer), +// unless it is a Latin word with only lookalike Cyrillic mixed in (a spoof +// such as "аdmin") or mixes in other scripts, which ApplyConfusables folds +// back to the Latin text it imitates. All-caps words stay all-caps (ЖУК -> ZHUK) +void TransliterateCyrillic(char[] sName, int Length) +{ + char sOut[MAX_NAME_LENGTH * 2]; + int w = 0; + int r = 0; + + while(sName[r] != '\0') + { + if(sName[r] == ' ') + { + if(w + 1 < sizeof(sOut)) + sOut[w++] = ' '; + r++; + continue; + } + + int iEnd = r; + while(sName[iEnd] != '\0' && sName[iEnd] != ' ') + iEnd++; + + bool bUpper; + bool bSpell = IsCyrillicWord(sName, r, iEnd, bUpper); + int wStart = w; + + while(r < iEnd) + { + int rStart = r; + int cp = DecodeUTF8Char(sName, r); + + char sChar[8]; + for(int k = rStart; k < r && k - rStart < sizeof(sChar) - 1; k++) + sChar[k - rStart] = sName[k]; + sChar[r - rStart < sizeof(sChar) ? r - rStart : sizeof(sChar) - 1] = '\0'; + + // in a lookalike word, Cyrillic without a confusable is still + // spelled out rather than lost when FoldToASCII strips it + bool bDummy; + char sTo[16]; + if(!IsCyrillicCp(cp) + || (!bSpell && g_ConfusableSet.GetValue(sChar, bDummy)) + || !g_Transliterate.GetString(sChar, sTo, sizeof(sTo))) + strcopy(sTo, sizeof(sTo), sChar); + + for(int k = 0; sTo[k] != '\0' && w + 1 < sizeof(sOut); k++) + sOut[w++] = sTo[k]; + } + + if(bSpell && bUpper) + { + for(int k = wStart; k < w; k++) + sOut[k] = CharToUpper(sOut[k]); + } + } + sOut[w] = '\0'; + + strcopy(sName, Length, sOut); +} + +// true if the word in s[iStart, iEnd) should be transliterated: it has +// Cyrillic, is not a Latin word whose Cyrillic letters are all confusables, +// and has no letters from other scripts. Real Cyrillic words never mix in +// Greek or styled letters; a word that does ("ιηƒιηιтє") is decoration that +// imitates Latin. bUpper is set when it has two or more Cyrillic letters, +// all uppercase +bool IsCyrillicWord(const char[] s, int iStart, int iEnd, bool &bUpper) +{ + bool bLatin = false; + bool bOtherScript = false; + bool bAllConfusable = true; + int iCyrillic = 0; + int iLower = 0; + + int i = iStart; + while(i < iEnd) + { + int iChar = i; + int cp = DecodeUTF8Char(s, i); + + if((cp >= 'a' && cp <= 'z') || (cp >= 'A' && cp <= 'Z')) + { + bLatin = true; + continue; + } + + if(!IsCyrillicCp(cp)) + { + if(cp >= 0x80 && IsLetterCp(cp)) + bOtherScript = true; + continue; + } + + iCyrillic++; + // basic lowercase block, then upper/lower pairs from U+0460 on + if((cp >= 0x430 && cp <= 0x45F) || (cp >= 0x460 && cp & 1)) + iLower++; + + char sChar[8]; + int iLen = i - iChar; + for(int k = 0; k < iLen && k < sizeof(sChar) - 1; k++) + sChar[k] = s[iChar + k]; + sChar[iLen < sizeof(sChar) ? iLen : sizeof(sChar) - 1] = '\0'; + + bool bDummy; + if(!g_ConfusableSet.GetValue(sChar, bDummy)) + bAllConfusable = false; + } + + bUpper = iCyrillic >= 2 && !iLower; + return iCyrillic && !bOtherScript && !(bLatin && bAllConfusable); +} + +bool IsCyrillicCp(int cp) +{ + return cp >= 0x400 && cp <= 0x4FF; +} + void ApplyConfusables(char[] sName, int Length) { char sFrom[16]; @@ -1135,12 +1585,18 @@ void NormalizeWhitespace(char[] sName) TrimString(sName); } +// picked by Steam account, so a player gets the same replacement name on +// every visit (unless someone else is wearing it); the slot is the fallback +// for clients without one void AssignReplacementName(int client, char[] sName, int Length) { g_bLastFilterReplaced = true; int iCount = g_ReplacementNames.Length; - int iBase = client % iCount; + int iSeed = client > 0 ? GetSteamAccountID(client, false) : 0; + if(!iSeed) + iSeed = client; + int iBase = (iSeed & 0x7FFFFFFF) % iCount; char sCandidate[MAX_NAME_LENGTH]; for(int i = 0; i < iCount; i++) @@ -1170,5 +1626,5 @@ void AssignReplacementName(int client, char[] sName, int Length) } g_ReplacementNames.GetString(iBase, sCandidate, sizeof(sCandidate)); - Format(sName, Length, "%s %d", sCandidate, GetClientUserId(client)); + Format(sName, Length, "%s %d", sCandidate, client ? GetClientUserId(client) : 0); } diff --git a/OverheadChat/scripting/OverheadChat.sp b/OverheadChat/scripting/OverheadChat.sp new file mode 100644 index 0000000..fb1ea99 --- /dev/null +++ b/OverheadChat/scripting/OverheadChat.sp @@ -0,0 +1,1046 @@ +#pragma semicolon 1 + +#include +#include +#include +#include + +#undef REQUIRE_PLUGIN +#include +#define REQUIRE_PLUGIN + +#undef REQUIRE_EXTENSIONS +#include +#define REQUIRE_EXTENSIONS + +#pragma newdecls required + +#define PLUGIN_VERSION "1.0" + +#define PREFIX "\x04[OverheadChat]\x01 " + +#define MAX_TEXT_LENGTH 256 +#define MAX_TOKENS 128 +#define MAX_LINES 8 +#define MAX_LINE_LENGTH 72 // sm_overheadchat_line_chars max plus room for "..." +// Skip bubbles rather than push a busy map towards the 2048 edict limit. +#define EDICT_HEADROOM 1900 +#define OBS_MODE_IN_EYE 4 +// Stock model on every client; its "forward" attachment sits on ValveBiped.forward, a child of +// Bip01_Head1, so it follows the head of any ValveBiped skeleton it bone-merges onto. +#define HELPER_MODEL "models/player/ct_urban.mdl" +#define HELPER_ATTACHMENT "forward" +#define HELPER_CLASS "prop_dynamic" // created as prop_dynamic_override, which spawns as prop_dynamic + +#define EF_BONEMERGE (1 << 0) +#define EF_NOSHADOW (1 << 4) +#define EF_NORECEIVESHADOW (1 << 6) +#define EF_BONEMERGE_FASTCULL (1 << 7) +#define EF_PARENT_ANIMATES (1 << 9) + +// SelfMute has no include on the shared path and registers no library; checked with GetFeatureStatus. +native bool SelfMute_IsIgnoring(int client, int target); + +enum +{ + TEXT_RAW = 0, // the only copy, shown to everyone + TEXT_RAW_PAIRED, // has a censored sibling, hidden from safe chat players + TEXT_CENSORED // shown to safe chat players only +} + +enum +{ + HIDDEN_NOT = 0, + HIDDEN_AUTHOR, + HIDDEN_SETTING_OFF, + HIDDEN_TEAM_CHAT, + HIDDEN_HIDE, + HIDDEN_SELFMUTE, + HIDDEN_SAFE_CHAT_COPY, + HIDDEN_FIRST_PERSON, + HIDDEN_RANGE +} + +ConVar g_cvFont; +ConVar g_cvSize; +ConVar g_cvHeight; +ConVar g_cvLineSpacing; +ConVar g_cvRange; +ConVar g_cvLineChars; +ConVar g_cvMaxLines; +ConVar g_cvMinAlnum; +ConVar g_cvDuration; +ConVar g_cvDurationPerChar; +ConVar g_cvDurationMax; +ConVar g_cvTypeTime; + +Cookie g_hCookie; +bool g_bEnabled[MAXPLAYERS + 1]; + +bool g_bChatFilter2; +// ChatFilter2 safe chat per client, kept by ChatFilter2_OnSafeChatChanged so the transmit hook needs no native call +bool g_bSafeChat[MAXPLAYERS + 1]; + +bool g_bWorldTextBroken; + +// TransmitManager extension, used by Hide_TransmitManager (sm_hide) to hide players from a viewer +bool g_bTransmitManager; + +// One bubble per author +int g_iTextRef[MAXPLAYERS + 1] = {INVALID_ENT_REFERENCE, ...}; +int g_iCensoredRef[MAXPLAYERS + 1] = {INVALID_ENT_REFERENCE, ...}; +int g_iHelperRef[MAXPLAYERS + 1] = {INVALID_ENT_REFERENCE, ...}; +int g_iLineCount[MAXPLAYERS + 1]; +float g_flExpireAt[MAXPLAYERS + 1]; +float g_flShownAt[MAXPLAYERS + 1]; +char g_sBubbleText[MAXPLAYERS + 1][MAX_TEXT_LENGTH]; // full wrapped text, typed out by the animation +char g_sBubbleCensored[MAXPLAYERS + 1][MAX_TEXT_LENGTH]; +int g_iTypedChars[MAXPLAYERS + 1]; // what the text entities show now, see TypedChars() +float g_vecBubblePos[MAXPLAYERS + 1][3]; // server-side estimate, for the range check +int g_iBubbleTeam[MAXPLAYERS + 1]; // say_team team, -1 for all chat +bool g_bIgnored[MAXPLAYERS + 1][MAXPLAYERS + 1]; // [author][viewer], SelfMute snapshot at send time + +// Per text entity, read by the transmit hook +int g_iEntAuthor[2049]; +int g_iEntKind[2049]; + +public Plugin myinfo = +{ + name = "OverheadChat", + author = "marisakirisame.net", + description = "Shows chat messages briefly above the author's head", + version = PLUGIN_VERSION, + url = "" +}; + +public APLRes AskPluginLoad2(Handle myself, bool late, char[] error, int err_max) +{ + MarkNativeAsOptional("SelfMute_IsIgnoring"); + MarkNativeAsOptional("TransmitManager_GetEntityState"); + return APLRes_Success; +} + +public void OnPluginStart() +{ + g_cvFont = CreateConVar("sm_overheadchat_font", "4", "point_worldtext font (4 = Liberation Sans, 8 = Roboto Mono with outline)", 0, true, 0.0, true, 12.0); + g_cvSize = CreateConVar("sm_overheadchat_size", "4.0", "Text size", 0, true, 0.5); + g_cvHeight = CreateConVar("sm_overheadchat_height", "16.0", "Height of the text above the author's head"); + g_cvLineSpacing = CreateConVar("sm_overheadchat_line_spacing", "4.5", "Extra height per line after the first, so longer messages clear the head", 0, true, 0.0); + g_cvRange = CreateConVar("sm_overheadchat_range", "350.0", "Maximum distance at which the text is shown", 0, true, 0.0); + g_cvLineChars = CreateConVar("sm_overheadchat_line_chars", "24", "Maximum characters per line", 0, true, 8.0, true, 64.0); + g_cvMaxLines = CreateConVar("sm_overheadchat_max_lines", "2", "Maximum lines; longer messages end in ...", 0, true, 1.0, true, float(MAX_LINES)); + g_cvMinAlnum = CreateConVar("sm_overheadchat_min_alnum", "2", "Letters/digits that must remain after removing lennies", 0, true, 1.0); + g_cvDuration = CreateConVar("sm_overheadchat_duration", "4.0", "Base seconds a message is shown", 0, true, 0.5); + g_cvDurationPerChar = CreateConVar("sm_overheadchat_duration_per_char", "0.05", "Extra seconds per character", 0, true, 0.0); + g_cvDurationMax = CreateConVar("sm_overheadchat_duration_max", "10.0", "Maximum seconds a message is shown", 0, true, 0.5); + g_cvTypeTime = CreateConVar("sm_overheadchat_type_time", "0.3", "Seconds to type a message out when shown and to backspace it before removal; 0 for no animation", 0, true, 0.0, true, 2.0); + AutoExecConfig(true, "OverheadChat"); + + // On by default. The setting was opt-in under "overheadchat_enabled"; a new cookie means a "0" + // saved under that one doesn't keep anyone off. + g_hCookie = new Cookie("overheadchat", "Show other players' chat above their heads (0 = off)", CookieAccess_Protected); + SetCookieMenuItem(CookieMenu_OverheadChat, 0, "Overhead Chat"); + + RegConsoleCmd("sm_overheadchat", Cmd_Toggle, "Toggle seeing chat above players' heads"); + RegAdminCmd("sm_overheadchat_say", Cmd_Say, ADMFLAG_RCON, "sm_overheadchat_say - show a bubble as if the target said it"); + RegAdminCmd("sm_overheadchat_test", Cmd_Test, ADMFLAG_RCON, "sm_overheadchat_test - print the text a bubble would show"); + RegAdminCmd("sm_overheadchat_debug", Cmd_Debug, ADMFLAG_RCON, "sm_overheadchat_debug - list live bubbles and who can see them"); + + HookEvent("player_death", Event_KillBubble); + HookEvent("player_spawn", Event_KillBubble); + HookEvent("player_team", Event_KillBubble); + + // Late load: clients may already be in game with cached cookies. + for (int i = 1; i <= MaxClients; i++) + { + if (IsClientConnected(i) && AreClientCookiesCached(i)) + OnClientCookiesCached(i); + } +} + +public void OnPluginEnd() +{ + for (int i = 1; i <= MaxClients; i++) + KillBubble(i); +} + +public void OnAllPluginsLoaded() +{ + CheckTransmitManager(); + + if (LibraryExists("ChatFilter2")) + OnChatFilter2Added(); +} + +public void OnLibraryAdded(const char[] name) +{ + if (StrEqual(name, "ChatFilter2")) + OnChatFilter2Added(); +} + +public void OnLibraryRemoved(const char[] name) +{ + if (StrEqual(name, "ChatFilter2")) + { + // Censored copies stay up but nobody counts as safe chat any more, so everyone sees the raw text. + g_bChatFilter2 = false; + for (int i = 1; i <= MaxClients; i++) + g_bSafeChat[i] = false; + } +} + +void OnChatFilter2Added() +{ + g_bChatFilter2 = true; + for (int i = 1; i <= MaxClients; i++) + g_bSafeChat[i] = IsClientInGame(i) && ChatFilter2_IsSafeChatEnabled(i); +} + +public void ChatFilter2_OnSafeChatChanged(int client, bool enabled) +{ + g_bSafeChat[client] = enabled; +} + +void CheckTransmitManager() +{ + g_bTransmitManager = GetFeatureStatus(FeatureType_Native, "TransmitManager_GetEntityState") == FeatureStatus_Available; +} + +public void OnMapStart() +{ + g_bWorldTextBroken = false; + PrecacheModel(HELPER_MODEL); + CheckTransmitManager(); +} + +public void OnClientConnected(int client) +{ + g_bEnabled[client] = true; + g_bSafeChat[client] = false; +} + +public void OnClientDisconnect(int client) +{ + KillBubble(client); +} + +//---------------------------------------------------------------------------------------------------- +// Setting: viewer-side, on unless turned off, a toggle in the Client Preferences menu (sm_settings / !settings). +//---------------------------------------------------------------------------------------------------- +public void OnClientCookiesCached(int client) +{ + char val[4]; + g_hCookie.Get(client, val, sizeof(val)); + g_bEnabled[client] = !StrEqual(val, "0"); +} + +void ToggleSetting(int client) +{ + g_bEnabled[client] = !g_bEnabled[client]; + g_hCookie.Set(client, g_bEnabled[client] ? "1" : "0"); + PrintToChat(client, "%sOverhead chat is now %s.", PREFIX, g_bEnabled[client] ? "enabled" : "disabled"); +} + +public void CookieMenu_OverheadChat(int client, CookieMenuAction action, any info, char[] buffer, int maxlen) +{ + switch (action) + { + case CookieMenuAction_DisplayOption: + { + FormatEx(buffer, maxlen, "Overhead Chat: %s", g_bEnabled[client] ? "On" : "Off"); + } + case CookieMenuAction_SelectOption: + { + ToggleSetting(client); + ShowCookieMenu(client); // re-show with the new state + } + } +} + +public Action Cmd_Toggle(int client, int args) +{ + if (!client) + { + ReplyToCommand(client, "[OverheadChat] This command can only be used in game."); + return Plugin_Handled; + } + + if (!AreClientCookiesCached(client)) + { + ReplyToCommand(client, "[OverheadChat] Your settings have not loaded yet, try again in a moment."); + return Plugin_Handled; + } + + ToggleSetting(client); + return Plugin_Handled; +} + +public Action Cmd_Say(int client, int args) +{ + if (args < 2) + { + ReplyToCommand(client, "[OverheadChat] Usage: sm_overheadchat_say "); + return Plugin_Handled; + } + + char argString[MAX_TEXT_LENGTH], targetArg[MAX_TARGET_LENGTH]; + GetCmdArgString(argString, sizeof(argString)); + int textStart = BreakString(argString, targetArg, sizeof(targetArg)); + + int target = FindTarget(client, targetArg, false, false); + if (target == -1) + return Plugin_Handled; + + if (!IsPlayerAlive(target)) + { + ReplyToCommand(client, "[OverheadChat] %N is not alive.", target); + return Plugin_Handled; + } + + char text[MAX_TEXT_LENGTH]; + strcopy(text, sizeof(text), argString[textStart]); + StripQuotes(text); + + if (!ShowBubble(target, text, -1)) + ReplyToCommand(client, "[OverheadChat] Nothing to show after removing lennies, or no free edicts."); + + return Plugin_Handled; +} + +public Action Cmd_Test(int client, int args) +{ + char text[MAX_TEXT_LENGTH], stripped[MAX_TEXT_LENGTH], joined[MAX_TEXT_LENGTH]; + GetCmdArgString(text, sizeof(text)); + StripQuotes(text); + + if (!StripLennies(text, stripped, sizeof(stripped))) + { + ReplyToCommand(client, "[OverheadChat] No bubble (kept: \"%s\")", stripped); + return Plugin_Handled; + } + + // lines between bars so the centring padding is visible + char wrapped[MAX_TEXT_LENGTH]; + WrapBubbleText(stripped, wrapped, sizeof(wrapped)); + BuildTypedText(wrapped, -1, joined, sizeof(joined)); + ReplaceString(joined, sizeof(joined), "\n", "|\n|"); + ReplyToCommand(client, "[OverheadChat]\n|%s|", joined); + return Plugin_Handled; +} + +//---------------------------------------------------------------------------------------------------- +// Chat capture. _Post never fires for messages another plugin blocked (gags, Leader3 titles). +//---------------------------------------------------------------------------------------------------- +public void OnClientSayCommand_Post(int client, const char[] command, const char[] sArgs) +{ + if (client <= 0 || !IsClientInGame(client) || !IsPlayerAlive(client)) + return; + + bool teamChat = StrEqual(command, "say_team"); + if (!teamChat && !StrEqual(command, "say")) + return; + + // commands and admin chat + if (sArgs[0] == '!' || sArgs[0] == '/' || sArgs[0] == '@') + return; + + ShowBubble(client, sArgs, teamChat ? GetClientTeam(client) : -1); +} + +public void Event_KillBubble(Event event, const char[] name, bool dontBroadcast) +{ + int client = GetClientOfUserId(event.GetInt("userid")); + if (client) + KillBubble(client); +} + +//---------------------------------------------------------------------------------------------------- +// Bubbles: point_worldtext attached to the head of an invisible helper model that bone-merges onto +// the author, so every client places the text on the head it draws itself. The server never moves +// the text. A message ChatFilter2 censors gets a second text entity; SetTransmit shows the censored +// one to safe chat players and the raw one to everyone else (same split as Leader3 markers). +//---------------------------------------------------------------------------------------------------- + +// Returns false if nothing was shown. team is the say_team team, or -1 for all chat. +bool ShowBubble(int author, const char[] message, int team) +{ + if (g_bWorldTextBroken) + return false; + + char text[MAX_TEXT_LENGTH]; + if (!StripLennies(message, text, sizeof(text))) + return false; + + char censored[MAX_TEXT_LENGTH]; + strcopy(censored, sizeof(censored), text); + bool hasCensored = g_bChatFilter2 && ChatFilter2_CensorText(censored, sizeof(censored)) && !StrEqual(censored, text); + + // censoring keeps the length, so both copies wrap to the same lines + g_iLineCount[author] = WrapBubbleText(text, g_sBubbleText[author], sizeof(g_sBubbleText[])); + if (hasCensored) + WrapBubbleText(censored, g_sBubbleCensored[author], sizeof(g_sBubbleCensored[])); + + // the entities start blank and OnGameFrame types the text out + float now = GetGameTime(); + g_flShownAt[author] = now; + g_iTypedChars[author] = g_cvTypeTime.FloatValue > 0.0 ? 0 : -1; + + char wrapped[MAX_TEXT_LENGTH], wrappedCensored[MAX_TEXT_LENGTH]; + BuildTypedText(g_sBubbleText[author], g_iTypedChars[author], wrapped, sizeof(wrapped)); + if (hasCensored) + BuildTypedText(g_sBubbleCensored[author], g_iTypedChars[author], wrappedCensored, sizeof(wrappedCensored)); + + int helper = LiveEntRef(g_iHelperRef[author], HELPER_CLASS); + int ent = LiveEntRef(g_iTextRef[author]); + int censoredEnt = LiveEntRef(g_iCensoredRef[author]); + + // Replace in place; respawn only when the bubble gains or loses its censored copy, + // which keeps the entity kinds in step with the transmit hook. + if (helper != -1 && ent != -1 && hasCensored == (censoredEnt != -1)) + { + SetVariantString(wrapped); + AcceptEntityInput(ent, "SetText"); + SetTextOffset(ent, author); // the line count may have changed + + if (censoredEnt != -1) + { + SetVariantString(wrappedCensored); + AcceptEntityInput(censoredEnt, "SetText"); + SetTextOffset(censoredEnt, author); + } + } + else + { + KillBubble(author); + + if (GetEntityCount() >= EDICT_HEADROOM) + return false; + + UpdateBubblePos(author); + + helper = SpawnHelper(author); + if (helper == -1) + return false; + g_iHelperRef[author] = EntIndexToEntRef(helper); + + ent = SpawnWorldText(author, helper, wrapped, hasCensored ? TEXT_RAW_PAIRED : TEXT_RAW); + if (ent == -1) + { + KillBubble(author); + return false; + } + g_iTextRef[author] = EntIndexToEntRef(ent); + + // The raw text stays hidden from safe chat players even if the censored copy fails to spawn. + if (hasCensored) + { + censoredEnt = SpawnWorldText(author, helper, wrappedCensored, TEXT_CENSORED); + if (censoredEnt != -1) + g_iCensoredRef[author] = EntIndexToEntRef(censoredEnt); + } + } + + // team is checked live in the transmit hook, since ZR infection switches teams mid-bubble + g_iBubbleTeam[author] = team; + + bool selfMute = GetFeatureStatus(FeatureType_Native, "SelfMute_IsIgnoring") == FeatureStatus_Available; + for (int viewer = 1; viewer <= MaxClients; viewer++) + g_bIgnored[author][viewer] = IsClientInGame(viewer) && selfMute && SelfMute_IsIgnoring(viewer, author); + + // the duration is time fully shown; typing out and backspacing come on top + float duration = g_cvDuration.FloatValue + g_cvDurationPerChar.FloatValue * strlen(text); + if (duration > g_cvDurationMax.FloatValue) + duration = g_cvDurationMax.FloatValue; + g_flExpireAt[author] = now + duration + 2.0 * g_cvTypeTime.FloatValue; + + UpdateBubblePos(author); // the range check uses it + return true; +} + +// Invisible copy of the author's skeleton; the text hangs off its head attachment. +int SpawnHelper(int author) +{ + int ent = CreateEntityByName("prop_dynamic_override"); + if (ent == -1) + return -1; + + DispatchKeyValue(ent, "model", HELPER_MODEL); + DispatchKeyValue(ent, "solid", "0"); + DispatchKeyValue(ent, "DisableBoneFollowers", "1"); + DispatchKeyValue(ent, "disableshadows", "1"); + DispatchKeyValue(ent, "disablereceiveshadows", "1"); + if (!DispatchSpawn(ent)) + { + AcceptEntityInput(ent, "Kill"); + return -1; + } + + // RENDER_NONE rather than EF_NODRAW: EF_NODRAW stops the entity being sent at all, and the + // client needs it to place the text. + SetEntityRenderMode(ent, RENDER_NONE); + + // CBaseEntity::FollowEntity() recipe (see Leader3's glow shell): the client only bone-merges + // with EF_BONEMERGE, a move parent and MOVETYPE_NONE. + float origin[3], angles[3]; + GetClientAbsOrigin(author, origin); + GetClientAbsAngles(author, angles); + TeleportEntity(ent, origin, angles, NULL_VECTOR); + + SetVariantString("!activator"); + AcceptEntityInput(ent, "SetParent", author, ent); + SetEntityMoveType(ent, MOVETYPE_NONE); + SetEntProp(ent, Prop_Send, "m_fEffects", + EF_BONEMERGE|EF_BONEMERGE_FASTCULL|EF_NOSHADOW|EF_NORECEIVESHADOW|EF_PARENT_ANIMATES); + + g_iEntAuthor[ent] = author; + SDKHook(ent, SDKHook_SetTransmit, Hook_HelperTransmit); + return ent; +} + +int SpawnWorldText(int author, int helper, const char[] text, int kind) +{ + int ent = CreateEntityByName("point_worldtext"); + if (ent == -1) + { + g_bWorldTextBroken = true; + LogMessage("point_worldtext could not be created; overhead chat is off for this map."); + return -1; + } + + char font[4], size[16]; + g_cvFont.GetString(font, sizeof(font)); + g_cvSize.GetString(size, sizeof(size)); + + DispatchKeyValue(ent, "message", text); + DispatchKeyValue(ent, "font", font); + DispatchKeyValue(ent, "textsize", size); + DispatchKeyValue(ent, "color", "255 255 255 255"); + DispatchKeyValue(ent, "orientation", "1"); + DispatchSpawn(ent); + + TeleportEntity(ent, g_vecBubblePos[author], NULL_VECTOR, NULL_VECTOR); + SetVariantString("!activator"); + AcceptEntityInput(ent, "SetParent", helper, ent); + SetVariantString(HELPER_ATTACHMENT); + AcceptEntityInput(ent, "SetParentAttachment", ent, ent); + SetTextOffset(ent, author); + + g_iEntAuthor[ent] = author; + g_iEntKind[ent] = kind; + SDKHook(ent, SDKHook_SetTransmit, Hook_BubbleTransmit); + return ent; +} + +// Offset from the head attachment. Its z axis is within 4 degrees of world up when the head is +// level (ct_urban reference pose), so a z offset puts the text straight above the head. +void SetTextOffset(int ent, int author) +{ + float local[3]; + local[2] = BubbleHeight(author); + TeleportEntity(ent, local, NULL_VECTOR, NULL_VECTOR); // parented: sets the local origin +} + +// Each extra line lifts the text so the bottom line keeps clear of the head. +float BubbleHeight(int author) +{ + return g_cvHeight.FloatValue + g_cvLineSpacing.FloatValue * (g_iLineCount[author] - 1); +} + +void KillBubble(int author) +{ + KillEntRef(g_iTextRef[author]); + KillEntRef(g_iCensoredRef[author]); + KillEntRef(g_iHelperRef[author], HELPER_CLASS); + g_iTextRef[author] = INVALID_ENT_REFERENCE; + g_iCensoredRef[author] = INVALID_ENT_REFERENCE; + g_iHelperRef[author] = INVALID_ENT_REFERENCE; +} + +// Server-side estimate of where the text is, used only for the range check: the eyes are within +// a few units of the head attachment the client places the text on. +void UpdateBubblePos(int author) +{ + GetClientEyePosition(author, g_vecBubblePos[author]); + g_vecBubblePos[author][2] += BubbleHeight(author); +} + +public void OnGameFrame() +{ + float now = GetGameTime(); + + for (int author = 1; author <= MaxClients; author++) + { + if (g_iTextRef[author] == INVALID_ENT_REFERENCE) + continue; + + if (LiveEntRef(g_iTextRef[author]) == -1 || LiveEntRef(g_iHelperRef[author], HELPER_CLASS) == -1 + || now >= g_flExpireAt[author] || !IsClientInGame(author) || !IsPlayerAlive(author)) + { + // also catches entities the round restart removed + KillBubble(author); + continue; + } + + UpdateBubblePos(author); + AnimateBubble(author, now); + } +} + +// Typing out and backspacing: sets the shown text whenever the typed character count changes. +void AnimateBubble(int author, float now) +{ + int typed = TypedChars(author, now); + if (typed == g_iTypedChars[author]) + return; + g_iTypedChars[author] = typed; + + char text[MAX_TEXT_LENGTH]; + int ents[2]; + ents[0] = LiveEntRef(g_iTextRef[author]); + ents[1] = LiveEntRef(g_iCensoredRef[author]); + + for (int e = 0; e < 2; e++) + { + if (ents[e] == -1) + continue; + + BuildTypedText(e == 0 ? g_sBubbleText[author] : g_sBubbleCensored[author], typed, text, sizeof(text)); + SetVariantString(text); + AcceptEntityInput(ents[e], "SetText"); + } +} + +// Non-space characters to show, or -1 for all of them. The text types out over +// sm_overheadchat_type_time after it is shown and backspaces over the same time before it expires. +int TypedChars(int author, float now) +{ + float typeTime = g_cvTypeTime.FloatValue; + float t = now - g_flShownAt[author]; + float left = g_flExpireAt[author] - now; + if (left < t) + t = left; + + if (typeTime <= 0.0 || t >= typeTime) + return -1; + + int total = 0; + for (int i = 0; g_sBubbleText[author][i]; i++) + { + if (g_sBubbleText[author][i] > ' ') + total++; + } + + return RoundToFloor(total * t / typeTime); +} + +// The helper only matters to viewers who can get the text (a subset of these), so skip the rest. +public Action Hook_HelperTransmit(int ent, int client) +{ + int author = g_iEntAuthor[ent]; + return (client == author || !g_bEnabled[client]) ? Plugin_Handled : Plugin_Continue; +} + +public Action Hook_BubbleTransmit(int ent, int client) +{ + return BubbleHiddenReason(ent, client) == HIDDEN_NOT ? Plugin_Continue : Plugin_Handled; +} + +// Why a viewer doesn't get a text entity; shared by the transmit hook and sm_overheadchat_debug, +// which skips the setting check so bots (no cookies) can stand in as viewers. +int BubbleHiddenReason(int ent, int client, bool ignoreSetting = false) +{ + int author = g_iEntAuthor[ent]; + + if (client == author) + return HIDDEN_AUTHOR; + + if (!g_bEnabled[client] && !ignoreSetting) + return HIDDEN_SETTING_OFF; + + if (g_iBubbleTeam[author] != -1 && GetClientTeam(client) != g_iBubbleTeam[author]) + return HIDDEN_TEAM_CHAT; + + // the viewer can't see the author (sm_hide), so the text would float on its own + if (g_bTransmitManager && !TransmitManager_GetEntityState(author, client)) + return HIDDEN_HIDE; + + if (g_bIgnored[author][client]) + return HIDDEN_SELFMUTE; + + int kind = g_iEntKind[ent]; + if ((kind == TEXT_RAW_PAIRED && g_bSafeChat[client]) || (kind == TEXT_CENSORED && !g_bSafeChat[client])) + return HIDDEN_SAFE_CHAT_COPY; + + // spectating the author in first person: the text would sit in their view + if (!IsPlayerAlive(client) + && GetEntProp(client, Prop_Send, "m_iObserverMode") == OBS_MODE_IN_EYE + && GetEntPropEnt(client, Prop_Send, "m_hObserverTarget") == author) + return HIDDEN_FIRST_PERSON; + + float eye[3]; + GetClientEyePosition(client, eye); + float range = g_cvRange.FloatValue; + if (GetVectorDistance(eye, g_vecBubblePos[author], true) > range * range) + return HIDDEN_RANGE; + + return HIDDEN_NOT; +} + +public Action Cmd_Debug(int client, int args) +{ + static const char reasons[][] = {"visible", "author", "setting off", "team chat", "author hidden (sm_hide)", "selfmute", "other safe chat copy", "first person", "out of range"}; + static const char kinds[][] = {"raw", "raw (has censored copy)", "censored"}; + + int shown = 0; + for (int author = 1; author <= MaxClients; author++) + { + int ents[2]; + ents[0] = LiveEntRef(g_iTextRef[author]); + ents[1] = LiveEntRef(g_iCensoredRef[author]); + + for (int e = 0; e < 2; e++) + { + int ent = ents[e]; + if (ent == -1) + continue; + + char text[MAX_TEXT_LENGTH]; + GetEntPropString(ent, Prop_Send, "m_szText", text, sizeof(text)); + ReplaceString(text, sizeof(text), "\n", "|"); + + ReplyToCommand(client, "[OverheadChat] %N (team %d), %s, %s, %.1fs left: \"%s\"", author, GetClientTeam(author), + g_iBubbleTeam[author] == -1 ? "all chat" : "team chat", kinds[g_iEntKind[ent]], g_flExpireAt[author] - GetGameTime(), text); + + for (int viewer = 1; viewer <= MaxClients; viewer++) + { + if (IsClientInGame(viewer)) + ReplyToCommand(client, " %N (team %d): %s%s", viewer, GetClientTeam(viewer), + reasons[BubbleHiddenReason(ent, viewer, true)], g_bEnabled[viewer] ? "" : " [setting off]"); + } + shown++; + } + } + + if (!shown) + ReplyToCommand(client, "[OverheadChat] No live bubbles."); + + return Plugin_Handled; +} + +void KillEntRef(int ref, const char[] expectedClass = "point_worldtext") +{ + int ent = LiveEntRef(ref, expectedClass); + if (ent != -1) + AcceptEntityInput(ent, "Kill"); +} + +// Resolves an entity reference, returning -1 unless it is still a live edict of the expected class. +int LiveEntRef(int ref, const char[] expectedClass = "point_worldtext") +{ + if (ref == INVALID_ENT_REFERENCE) + return -1; + + int ent = EntRefToEntIndex(ref); + if (ent == INVALID_ENT_REFERENCE || !IsValidEdict(ent)) + return -1; + + char classname[32]; + GetEdictClassname(ent, classname, sizeof(classname)); + return StrEqual(classname, expectedClass) ? ent : -1; +} + +//---------------------------------------------------------------------------------------------------- +// Text: point_worldtext only draws printable ASCII, so lennies and other unsupported text are +// removed as whole space-separated tokens, along with symbol-only tokens next to them (the +// brackets around "( ͡° ͜ʖ ͡°)"). Returns false unless enough letters/digits remain. +//---------------------------------------------------------------------------------------------------- +bool StripLennies(const char[] input, char[] output, int maxlen) +{ + int starts[MAX_TOKENS], ends[MAX_TOKENS]; + bool dropped[MAX_TOKENS], hasAlnum[MAX_TOKENS]; + int count = 0; + + int len = strlen(input); + int i = 0; + while (i < len && count < MAX_TOKENS) + { + // spaces and control bytes (typed colour codes) separate tokens + if (input[i] <= ' ') + { + i++; + continue; + } + + starts[count] = i; + dropped[count] = false; + hasAlnum[count] = false; + + while (i < len && input[i] > ' ') + { + if (input[i] > '~') // DEL or any UTF-8 byte + dropped[count] = true; + else if (IsCharAlpha(input[i]) || IsCharNumeric(input[i])) + hasAlnum[count] = true; + i++; + } + + ends[count++] = i; + } + + // symbol-only neighbours of dropped tokens are lenny residue; repeat so chains collapse + bool changed = true; + while (changed) + { + changed = false; + for (int t = 0; t < count; t++) + { + if (dropped[t] || hasAlnum[t]) + continue; + + if ((t > 0 && dropped[t - 1]) || (t + 1 < count && dropped[t + 1])) + { + dropped[t] = true; + changed = true; + } + } + } + + output[0] = '\0'; + int pos = 0; + int alnum = 0; + for (int t = 0; t < count; t++) + { + if (dropped[t]) + continue; + + int tokenLen = ends[t] - starts[t]; + if (pos + tokenLen + 2 > maxlen) + break; + + if (pos > 0) + output[pos++] = ' '; + + for (int c = starts[t]; c < ends[t]; c++) + { + if (IsCharAlpha(input[c]) || IsCharNumeric(input[c])) + alnum++; + output[pos++] = input[c]; + } + } + output[pos] = '\0'; + + return alnum >= g_cvMinAlnum.IntValue; +} + +// Word-wraps single-spaced ASCII text into at most sm_overheadchat_max_lines lines of +// sm_overheadchat_line_chars. Overflow cuts the last line and ends it in "...". Returns the line count. +int WrapText(const char[] text, char lines[MAX_LINES][MAX_LINE_LENGTH]) +{ + int width = g_cvLineChars.IntValue; + int maxLines = g_cvMaxLines.IntValue; + + int len = strlen(text); + int pos = 0; + int count = 0; + + while (pos < len && count < maxLines) + { + int remaining = len - pos; + int take, next; + + if (remaining <= width) + { + take = remaining; + next = len; + } + else if (count == maxLines - 1) + { + // leave room for "...", cutting at a word boundary when there is one + take = width - 3; + for (int c = pos + width - 3; c > pos; c--) + { + if (text[c] == ' ') + { + take = c - pos; + break; + } + } + next = len; + } + else + { + // last space that still lets the line fit; the space itself is dropped + int brk = -1; + for (int c = pos + width; c > pos; c--) + { + if (text[c] == ' ') + { + brk = c; + break; + } + } + + if (brk != -1) + { + take = brk - pos; + next = brk + 1; + } + else + { + // a word longer than a line + take = width; + next = pos + width; + } + } + + strcopy(lines[count], take + 1, text[pos]); + if (next == len && take < remaining) + { + TrimString(lines[count]); + StrCat(lines[count], MAX_LINE_LENGTH, "..."); + } + + pos = next; + count++; + } + + return count; +} + +// Lays out the bubble text showing only its first `typed` non-space characters (-1 for all). +// The renderer centres the block on its widest line but starts every line at the block's left +// edge, so each line gets left padding of half the width it lacks, in spaces (to within half a +// space). Widths come from the font's glyph advances, so this works in proportional fonts and +// keeps a partly typed message centred as it grows. +void BuildTypedText(const char[] text, int typed, char[] output, int maxlen) +{ + int font = g_iFontTable[g_cvFont.IntValue]; + char lines[MAX_LINES][MAX_LINE_LENGTH]; + int widths[MAX_LINES]; + int count = 0; + int widest = 0; + + int start = 0; + while (count < MAX_LINES) + { + int end = start; + while (text[end] && text[end] != '\n') + end++; + + // typed part of the line, ending on its last typed character + int partEnd = start; + for (int i = start; i < end && typed != 0; i++) + { + if (text[i] > ' ') + { + typed--; + partEnd = i + 1; + } + } + + int len = partEnd - start; + if (len > MAX_LINE_LENGTH - 1) + len = MAX_LINE_LENGTH - 1; + strcopy(lines[count], len + 1, text[start]); + widths[count] = TextWidth(font, lines[count]); + if (widths[count] > widest) + widest = widths[count]; + count++; + + if (!text[end]) + break; + start = end + 1; + } + + int space = g_iFontAdvance[font][0]; + output[0] = '\0'; + for (int i = 0; i < count; i++) + { + if (i > 0) + StrCat(output, maxlen, "\n"); + + int left = RoundToNearest(float(widest - widths[i]) / (2.0 * space)); + for (int c = 0; c < left; c++) + StrCat(output, maxlen, " "); + StrCat(output, maxlen, lines[i]); + } +} + +// Wraps text and joins the lines with \n, unpadded; BuildTypedText lays them out. Returns the line count. +int WrapBubbleText(const char[] text, char[] output, int maxlen) +{ + char lines[MAX_LINES][MAX_LINE_LENGTH]; + int count = WrapText(text, lines); + + output[0] = '\0'; + for (int i = 0; i < count; i++) + { + if (i > 0) + StrCat(output, maxlen, "\n"); + StrCat(output, maxlen, lines[i]); + } + + return count; +} + +// Width in font units, as C_PointWorldText::CalcTextTotalSize adds it up (text spacing 0). +int TextWidth(int font, const char[] text) +{ + int width = 0; + for (int i = 0; text[i]; i++) + { + int idx = text[i] - ' '; + if (idx < 0) + idx = 0; + else if (idx > 94) + idx = 94; + width += g_iFontAdvance[font][idx]; + } + return width; +} + +//---------------------------------------------------------------------------------------------------- +// Font metrics: glyph advances for printable ASCII (' ' to '~') from the client's point_worldtext +// font tables (hl2sdk c_point_worldtext.cpp, identical in the CS:S client.dll). +//---------------------------------------------------------------------------------------------------- +// sm_overheadchat_font -> table below, as the client's g_mapfonts maps fonts to glyph sets +int g_iFontTable[13] = {0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 4, 4, 0}; + +int g_iFontAdvance[5][95] = +{ + // TF2 Build + { + 25, 16, 15, 42, 25, 36, 39, 10, 25, 25, 25, 27, 12, 23, 14, 27, 43, 25, 37, 37, 41, 34, 30, 36, + 36, 32, 14, 13, 30, 29, 30, 38, 44, 45, 38, 42, 46, 39, 39, 43, 48, 18, 30, 37, 32, 49, 42, 50, + 38, 50, 38, 38, 43, 48, 49, 61, 46, 47, 38, 16, 27, 16, 34, 35, 10, 45, 38, 42, 46, 39, 39, 43, + 48, 21, 30, 37, 30, 49, 42, 50, 38, 50, 38, 38, 43, 48, 49, 61, 46, 47, 38, 18, 16, 18, 34 + }, + // TF2 + { + 22, 11, 8, 20, 49, 24, 30, 8, 19, 18, 17, 19, 8, 18, 9, 22, 34, 16, 32, 30, 31, 26, 27, 27, + 31, 24, 10, 9, 12, 19, 13, 34, 30, 32, 31, 33, 36, 32, 32, 35, 33, 14, 23, 32, 31, 39, 34, 41, + 31, 40, 38, 24, 35, 34, 34, 43, 36, 35, 32, 11, 18, 12, 14, 23, 9, 32, 31, 33, 36, 32, 32, 35, + 33, 14, 23, 32, 31, 39, 34, 41, 31, 40, 38, 24, 35, 34, 34, 43, 36, 35, 32, 16, 9, 16, 17 + }, + // Liberation Sans + { + 18, 18, 22, 35, 35, 57, 42, 12, 21, 21, 25, 37, 18, 21, 18, 18, 35, 35, 35, 35, 35, 35, 35, 35, + 35, 35, 18, 18, 37, 37, 37, 35, 65, 42, 42, 46, 46, 42, 39, 50, 46, 18, 32, 42, 35, 53, 46, 50, + 42, 50, 46, 42, 39, 46, 42, 60, 42, 42, 39, 18, 18, 18, 30, 35, 21, 35, 35, 32, 35, 35, 18, 35, + 35, 14, 14, 32, 14, 53, 35, 35, 35, 35, 21, 32, 18, 35, 32, 46, 32, 32, 32, 21, 16, 21, 37 + }, + // TF2 Professor + { + 27, 14, 24, 58, 40, 66, 46, 20, 32, 34, 32, 56, 22, 34, 16, 30, 50, 38, 46, 32, 40, 42, 34, 44, + 34, 38, 18, 24, 34, 42, 38, 40, 54, 43, 44, 40, 44, 42, 36, 42, 50, 18, 38, 48, 44, 58, 48, 44, + 36, 54, 51, 34, 56, 41, 44, 64, 44, 46, 52, 30, 56, 40, 24, 72, 22, 34, 31, 26, 32, 32, 28, 33, + 37, 14, 26, 39, 34, 46, 40, 35, 31, 35, 33, 24, 38, 27, 26, 45, 35, 38, 32, 44, 18, 34, 36 + }, + // Roboto Mono + { + 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, + 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, + 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, + 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77 + } +}; diff --git a/PlayerRankings/scripting/PlayerRankings_nohlstats.sp b/PlayerRankings/scripting/PlayerRankings_nohlstats.sp index 5cdbc4e..5501798 100644 --- a/PlayerRankings/scripting/PlayerRankings_nohlstats.sp +++ b/PlayerRankings/scripting/PlayerRankings_nohlstats.sp @@ -14,6 +14,7 @@ bool g_bEngineCSGO; bool g_bHideCrown[MAXPLAYERS+1]; bool g_bHideDialog[MAXPLAYERS+1]; bool g_bProtection[MAXPLAYERS+1]; +bool g_bTitleSet[MAXPLAYERS+1]; /* COOKIES */ Handle g_hCookie_HideCrown; @@ -26,6 +27,18 @@ ConVar g_hCVar_ProtectionMinimal1; ConVar g_hCVar_ProtectionMinimal2; ConVar g_hCVar_ProtectionMinimal3; ConVar g_hCVar_Grenade; +ConVar g_hCVar_Display; +ConVar g_hCVar_HudChannel; +ConVar g_hCVar_HudX; +ConVar g_hCVar_HudY; +ConVar g_hCVar_Hostname; +ConVar g_hCVar_HostIP; +ConVar g_hCVar_HostPort; +ConVar g_hCVar_Password; + +/* STRINGS */ +char g_sRankTitle[MAXPLAYERS+1][128]; +char g_sTitleSent[MAXPLAYERS+1][128]; /* INTERGERS */ int g_iDialogLevel = 100000; @@ -72,8 +85,17 @@ public void OnPluginStart() g_hCVar_ProtectionMinimal2 = CreateConVar("sm_topdefenders_minimal_2", "30", "", FCVAR_NONE, true, 1.0, true, 64.0); g_hCVar_ProtectionMinimal3 = CreateConVar("sm_topdefenders_minimal_3", "45", "", FCVAR_NONE, true, 1.0, true, 64.0); g_hCVar_Grenade = CreateConVar("sm_topdefenders_grenade", "1", "", FCVAR_NONE, true, 0.0, true, 1.0); + g_hCVar_Display = CreateConVar("sm_topdefenders_display", "2", "Rank display: 0 off, 1 dialog, 2 hudtext, 3 scoreboard title (set sm_hostname_send_to_clients 0 so HostnameManager doesn't overwrite it)", FCVAR_NONE, true, 0.0, true, 3.0); + g_hCVar_HudChannel = CreateConVar("sm_topdefenders_hud_channel", "5", "Hudtext channel for the rank display (0-5)", FCVAR_NONE, true, 0.0, true, 5.0); + g_hCVar_HudX = CreateConVar("sm_topdefenders_hud_x", "0.01", "Hudtext x position for the rank display (-1 centres)", FCVAR_NONE, true, -1.0, true, 1.0); + g_hCVar_HudY = CreateConVar("sm_topdefenders_hud_y", "0.01", "Hudtext y position for the rank display (-1 centres)", FCVAR_NONE, true, -1.0, true, 1.0); AutoExecConfig(true); + g_hCVar_Hostname = FindConVar("hostname"); + g_hCVar_HostIP = FindConVar("hostip"); + g_hCVar_HostPort = FindConVar("hostport"); + g_hCVar_Password = FindConVar("sv_password"); + g_hCookie_HideCrown = RegClientCookie("topdefenders_hidecrown", "", CookieAccess_Private); g_hCookie_HideDialog = RegClientCookie("topdefenders_hidedialog", "", CookieAccess_Private); g_hCookie_Protection = RegClientCookie("topdefenders_protection", "", CookieAccess_Private); @@ -95,6 +117,14 @@ public void OnPluginStart() SetCookieMenuItem(MenuHandler_CookieMenu, 0, "Player Rankings"); } +//---------------------------------------------------------------------------------------------------- +// Purpose: Hand everyone showing a rank title the real hostname back. +//---------------------------------------------------------------------------------------------------- +public void OnPluginEnd() +{ + ResetAllTitles(); +} + //---------------------------------------------------------------------------------------------------- // Purpose: //---------------------------------------------------------------------------------------------------- @@ -288,11 +318,21 @@ public void OnClientCookiesCached(int client) g_bProtection[client] = false; } +//---------------------------------------------------------------------------------------------------- +// Purpose: +//---------------------------------------------------------------------------------------------------- +public void OnClientPutInServer(int client) +{ + g_bTitleSet[client] = false; +} + //---------------------------------------------------------------------------------------------------- // Purpose: //---------------------------------------------------------------------------------------------------- public void OnClientDisconnect(int client) { + g_bTitleSet[client] = false; + g_iPlayerDamage[client] = 0; g_iPlayerDamageHits[client] = 0; g_iPlayerDamageFrom1K[client] = 0; @@ -350,9 +390,25 @@ public Action UpdateScoreboard(Handle timer) //---------------------------------------------------------------------------------------------------- public Action UpdateDialog(Handle timer) { - if (g_bEngineCSGO || g_iDialogLevel <= 0) + int iDisplay = g_hCVar_Display.IntValue; + + if (iDisplay != 3 || g_iDialogLevel <= 0) + ResetAllTitles(); + + if (g_bEngineCSGO || g_iDialogLevel <= 0 || iDisplay <= 0) return; + // Hudtext (held for 1s) and the scoreboard title only need a refresh every 0.5s, the dialog keeps the 0.1s rate. + static int iHudTick; + if (iDisplay >= 2 && (iHudTick++ % 5) != 0) + return; + + if (iDisplay == 3) + { + for (int client = 1; client <= MaxClients; client++) + g_sRankTitle[client][0] = '\0'; + } + int iSortedList[MAXPLAYERS+1][2]; int iSortedCount; @@ -368,16 +424,28 @@ public Action UpdateDialog(Handle timer) SortCustom2D(iSortedList, iSortedCount, SortRankingsList); + char sBuffer[128]; + for (int rank = 0; rank < iSortedCount; rank++) { switch(rank) { - case(0): SendDialog(iSortedList[rank][0], "#%d (D: %d | P: -%d)", g_iDialogLevel, 1, rank + 1, iSortedList[rank][1], iSortedList[rank][1] - iSortedList[rank + 1][1]); - case(1): SendDialog(iSortedList[rank][0], "#%d (D: %d | N: +%d)", g_iDialogLevel, 1, rank + 1, iSortedList[rank][1], iSortedList[rank - 1][1] - iSortedList[rank][1]); - default: SendDialog(iSortedList[rank][0], "#%d (D: %d | N: +%d | F: +%d)", g_iDialogLevel, 1, rank + 1, iSortedList[rank][1], iSortedList[rank - 1][1] - iSortedList[rank][1], iSortedList[0][1] - iSortedList[rank][1]); + case(0): Format(sBuffer, sizeof(sBuffer), "#%d (D: %d | P: -%d)", rank + 1, iSortedList[rank][1], iSortedList[rank][1] - iSortedList[rank + 1][1]); + case(1): Format(sBuffer, sizeof(sBuffer), "#%d (D: %d | N: +%d)", rank + 1, iSortedList[rank][1], iSortedList[rank - 1][1] - iSortedList[rank][1]); + default: Format(sBuffer, sizeof(sBuffer), "#%d (D: %d | N: +%d | F: +%d)", rank + 1, iSortedList[rank][1], iSortedList[rank - 1][1] - iSortedList[rank][1], iSortedList[0][1] - iSortedList[rank][1]); } + + if (iDisplay == 1) + SendDialog(iSortedList[rank][0], "%s", g_iDialogLevel, 1, sBuffer); + else if (iDisplay == 2) + SendRankHud(iSortedList[rank][0], sBuffer); + else + Format(g_sRankTitle[iSortedList[rank][0]], sizeof(g_sRankTitle[]), "[UNLOZE] Pos. %s", sBuffer); } + if (iDisplay == 3) + UpdateTitles(); + g_iDialogLevel--; } @@ -1035,6 +1103,151 @@ void SendDialog(int client, const char[] text, const int level, const int time, delete kv; } +//---------------------------------------------------------------------------------------------------- +// Purpose: Rank line as hudtext. ShowHudText on a fixed channel keeps SourceMod's auto channel +// picking (sync huds, channel -1) off it while it refreshes. +//---------------------------------------------------------------------------------------------------- +void SendRankHud(int client, const char[] text) +{ + int channel = g_hCVar_HudChannel.IntValue; + + SetHudTextParams(g_hCVar_HudX.FloatValue, g_hCVar_HudY.FloatValue, 1.0, 255, 255, 255, 255, 0, 0.0, 0.0, 0.0); + + if (!g_bHideDialog[client]) + { + ShowHudText(client, channel, "%s", text); + } + + for (int spec = 1; spec <= MaxClients; spec++) + { + if (!IsClientInGame(spec) || !IsClientObserver(spec) || g_bHideDialog[spec]) + continue; + + int specMode = GetClientSpectatorMode(spec); + int specTarget = GetClientSpectatorTarget(spec); + + if ((specMode == SPECMODE_FIRSTPERSON || specMode == SPECMODE_THIRDPERSON) && specTarget == client) + { + ShowHudText(spec, channel, "%s", text); + } + } +} + +//---------------------------------------------------------------------------------------------------- +// Purpose: Rank line as the scoreboard title. Unranked spectators see the title of the player they +// watch in first or third person, everyone else gets the real hostname back. +//---------------------------------------------------------------------------------------------------- +void UpdateTitles() +{ + for (int client = 1; client <= MaxClients; client++) + { + if (!IsClientInGame(client) || IsFakeClient(client)) + continue; + + int source = client; + + if (!g_sRankTitle[client][0] && IsClientObserver(client)) + { + int specMode = GetClientSpectatorMode(client); + int specTarget = GetClientSpectatorTarget(client); + + if ((specMode == SPECMODE_FIRSTPERSON || specMode == SPECMODE_THIRDPERSON) && specTarget >= 1 && specTarget <= MaxClients) + source = specTarget; + } + + if (g_bHideDialog[client] || !g_sRankTitle[source][0]) + ResetTitle(client); + else + SetTitle(client, g_sRankTitle[source]); + } +} + +//---------------------------------------------------------------------------------------------------- +// Purpose: Only sends when the title changes. +//---------------------------------------------------------------------------------------------------- +void SetTitle(int client, const char[] title) +{ + if (g_bTitleSet[client] && strcmp(g_sTitleSent[client], title, true) == 0) + return; + + SendClientHostname(client, title); + + strcopy(g_sTitleSent[client], sizeof(g_sTitleSent[]), title); + g_bTitleSet[client] = true; +} + +//---------------------------------------------------------------------------------------------------- +// Purpose: +//---------------------------------------------------------------------------------------------------- +void ResetTitle(int client) +{ + if (!g_bTitleSet[client]) + return; + + g_bTitleSet[client] = false; + + if (!IsClientInGame(client)) + return; + + char sHostname[128]; + g_hCVar_Hostname.GetString(sHostname, sizeof(sHostname)); + + SendClientHostname(client, sHostname); +} + +//---------------------------------------------------------------------------------------------------- +// Purpose: +//---------------------------------------------------------------------------------------------------- +void ResetAllTitles() +{ + for (int client = 1; client <= MaxClients; client++) + ResetTitle(client); +} + +//---------------------------------------------------------------------------------------------------- +// Purpose: Copied from HostnameManager. The scoreboard only reads the hostname from server_spawn, +// which the client's engine fires locally from svc_ServerInfo on connect. Send a copy +// straight to the client so it never reaches server-side listeners, and fill every field so +// other client listeners (mumble, abuse report, steam share) see the values they got on connect. +//---------------------------------------------------------------------------------------------------- +void SendClientHostname(int client, const char[] hostname) +{ + Event hEvent = CreateEvent("server_spawn", true); + if (hEvent == null) + return; + + int iIP = g_hCVar_HostIP.IntValue; + int iPort = g_hCVar_HostPort.IntValue; + + char sAddress[32]; + Format(sAddress, sizeof(sAddress), "%d.%d.%d.%d:%d", (iIP >>> 24) & 0xFF, (iIP >>> 16) & 0xFF, (iIP >>> 8) & 0xFF, iIP & 0xFF, iPort); + + char sGame[32]; + GetGameFolderName(sGame, sizeof(sGame)); + + char sMap[PLATFORM_MAX_PATH]; + GetCurrentMap(sMap, sizeof(sMap)); + + char sPassword[64]; + g_hCVar_Password.GetString(sPassword, sizeof(sPassword)); + + hEvent.SetString("hostname", hostname); + hEvent.SetString("address", sAddress); + hEvent.SetInt("ip", iIP); + hEvent.SetInt("port", iPort); + hEvent.SetString("game", sGame); + hEvent.SetString("mapname", sMap); + hEvent.SetInt("maxplayers", MaxClients); + hEvent.SetString("os", "LINUX"); + hEvent.SetBool("dedicated", IsDedicatedServer()); + hEvent.SetBool("password", sPassword[0] != '\0'); + + hEvent.FireToClient(client); + + // FireToClient does not free the event. + hEvent.Cancel(); +} + //---------------------------------------------------------------------------------------------------- // Purpose: //---------------------------------------------------------------------------------------------------- diff --git a/custom-chatcolors/scripting/custom-chatcolors.sp b/custom-chatcolors/scripting/custom-chatcolors.sp index f69f2da..7a8b02c 100644 --- a/custom-chatcolors/scripting/custom-chatcolors.sp +++ b/custom-chatcolors/scripting/custom-chatcolors.sp @@ -25,6 +25,7 @@ public Plugin myinfo = //Handle tagForward; //Handle applicationForward; Handle messageForward; +Handle rewriteForward; Handle preLoadedForward; Handle loadedForward; Handle configReloadedForward; @@ -64,6 +65,11 @@ char g_msgName[128]; char g_msgSender[128]; char g_msgText[MAX_CHAT_LENGTH]; char g_msgFinal[255]; +char g_msgTextRaw[MAX_CHAT_LENGTH]; // g_msgText before coloring, for CCC_OnChatMessageRewrite +char g_msgFinalRewritten[255]; +bool g_msgIsAction; +int g_msgChatColor; +bool g_msgChatAlpha; bool g_msgIsTeammate; bool g_Ignored[(MAXPLAYERS + 1) * (MAXPLAYERS + 1)] = {false, ...}; @@ -140,6 +146,7 @@ public void OnPluginStart() //tagForward = CreateGlobalForward("CCC_OnTagApplied", ET_Event, Param_Cell); //applicationForward = CreateGlobalForward("CCC_OnColor", ET_Event, Param_Cell, Param_String, Param_Cell); messageForward = CreateGlobalForward("CCC_OnChatMessage", ET_Event, Param_Cell, Param_Cell, Param_String); + rewriteForward = CreateGlobalForward("CCC_OnChatMessageRewrite", ET_Event, Param_Cell, Param_String, Param_Cell); preLoadedForward = CreateGlobalForward("CCC_OnUserConfigPreLoaded", ET_Event, Param_Cell); loadedForward = CreateGlobalForward("CCC_OnUserConfigLoaded", ET_Ignore, Param_Cell); configReloadedForward = CreateGlobalForward("CCC_OnConfigReloaded", ET_Ignore); @@ -2603,10 +2610,12 @@ public Action Hook_UserMessage(UserMsg msg_id, Handle bf, const int[] players, i } } - if (!g_msgAuthor || HasFlag(g_msgAuthor, Admin_Custom1)) - { - CFormatColor(g_msgText, sizeof(g_msgText), g_msgAuthor); - } + strcopy(g_msgTextRaw, sizeof(g_msgTextRaw), g_msgText); + g_msgIsAction = bIsAction; + g_msgChatColor = xiChatColor; + g_msgChatAlpha = bChatAlpha; + + ColorChatText(g_msgText, sizeof(g_msgText)); if (!bIsAction) { @@ -2662,34 +2671,6 @@ public Action Hook_UserMessage(UserMsg msg_id, Handle bf, const int[] players, i Format(g_msgSender, sizeof(g_msgSender), "\x08%08X%s%s", xiTagColor, sAuthorTag, g_msgSender); } } - - if (g_msgText[0] == '>' && (GetConVarInt(g_hGreenText) == 1 || (GetConVarInt(g_hGreenText) == 2 && CheckCommandAccess(g_msgAuthor, "sm_tag", ADMFLAG_CUSTOM1)))) - { - Format(g_msgText, sizeof(g_msgText), "\x0714C800%s", g_msgText); - } - else if (xiChatColor == COLOR_NONE || g_bTagToggled[g_msgAuthor]) - { - } - else if (xiChatColor == COLOR_TEAM) - { - Format(g_msgText, sizeof(g_msgText), "\x03%s", g_msgText); - } - else if (xiChatColor == COLOR_CGREEN) - { - Format(g_msgText, sizeof(g_msgText), "\x04%s", g_msgText); - } - else if (xiChatColor == COLOR_OLIVE) - { - Format(g_msgText, sizeof(g_msgText), "\x05%s", g_msgText); - } - else if (!bChatAlpha) - { - Format(g_msgText, sizeof(g_msgText), "\x07%06X%s", xiChatColor, g_msgText); - } - else - { - Format(g_msgText, sizeof(g_msgText), "\x08%08X%s", xiChatColor, g_msgText); - } } Format(g_msgFinal, sizeof(g_msgFinal), "%t", g_msgName, g_msgSender, g_msgText); @@ -2697,6 +2678,94 @@ public Action Hook_UserMessage(UserMsg msg_id, Handle bf, const int[] players, i return Plugin_Handled; } +// Applies the author's chat text coloring, using the state Hook_UserMessage stored for this message +void ColorChatText(char[] text, int maxlen) +{ + if (!g_msgAuthor || HasFlag(g_msgAuthor, Admin_Custom1)) + { + CFormatColor(text, maxlen, g_msgAuthor); + } + + if (g_msgIsAction) + return; + + if (text[0] == '>' && (GetConVarInt(g_hGreenText) == 1 || (GetConVarInt(g_hGreenText) == 2 && CheckCommandAccess(g_msgAuthor, "sm_tag", ADMFLAG_CUSTOM1)))) + { + Format(text, maxlen, "\x0714C800%s", text); + } + else if (g_msgChatColor == COLOR_NONE || g_bTagToggled[g_msgAuthor]) + { + } + else if (g_msgChatColor == COLOR_TEAM) + { + Format(text, maxlen, "\x03%s", text); + } + else if (g_msgChatColor == COLOR_CGREEN) + { + Format(text, maxlen, "\x04%s", text); + } + else if (g_msgChatColor == COLOR_OLIVE) + { + Format(text, maxlen, "\x05%s", text); + } + else if (!g_msgChatAlpha) + { + Format(text, maxlen, "\x07%06X%s", g_msgChatColor, text); + } + else + { + Format(text, maxlen, "\x08%08X%s", g_msgChatColor, text); + } +} + +// Lets plugins rewrite the raw message once; on success g_msgFinalRewritten holds the formatted line +bool BuildRewrittenMessage() +{ + char sText[MAX_CHAT_LENGTH]; + strcopy(sText, sizeof(sText), g_msgTextRaw); + + Action result = Plugin_Continue; + + Call_StartForward(rewriteForward); + Call_PushCell(g_msgAuthor); + Call_PushStringEx(sText, sizeof(sText), SM_PARAM_STRING_UTF8 | SM_PARAM_STRING_COPY, SM_PARAM_COPYBACK); + Call_PushCell(sizeof(sText)); + Call_Finish(result); + + if (result != Plugin_Changed || StrEqual(sText, g_msgTextRaw)) + return false; + + TrimString(sText); + + if (strlen(sText) == 0) + return false; + + ColorChatText(sText, sizeof(sText)); + Format(g_msgFinalRewritten, sizeof(g_msgFinalRewritten), "%t", g_msgName, g_msgSender, sText); + + return true; +} + +void SendSayText2(const int[] players, int playersNum, const char[] text) +{ + Handle SayText2 = StartMessage("SayText2", players, playersNum, USERMSG_RELIABLE | USERMSG_BLOCKHOOKS); + + if (GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available && GetUserMessageType() == UM_Protobuf) + { + PbSetInt(SayText2, "ent_idx", g_msgAuthor); + PbSetBool(SayText2, "chat", g_msgIsChat); + PbSetString(SayText2, "text", text); + EndMessage(); + } + else + { + BfWriteByte(SayText2, g_msgAuthor); + BfWriteByte(SayText2, g_msgIsChat); + BfWriteString(SayText2, text); + EndMessage(); + } +} + public Action Event_PlayerSay(Handle event, const char[] name, bool dontBroadcast) { if (g_msgAuthor == -1 || GetClientOfUserId(GetEventInt(event, "userid")) != g_msgAuthor) @@ -2709,54 +2778,40 @@ public Action Event_PlayerSay(Handle event, const char[] name, bool dontBroadcas int[] players = new int[MaxClients + 1]; int playersNum = 0; + int[] rewritePlayers = new int[MaxClients + 1]; + int rewritePlayersNum = 0; + int team = (g_msgIsTeammate && g_msgAuthor > 0) ? GetClientTeam(g_msgAuthor) : -1; - if (g_msgIsTeammate && g_msgAuthor > 0) + for (int client = 1; client <= MaxClients; client++) { - int team = GetClientTeam(g_msgAuthor); + if (!IsClientInGame(client) || (team != -1 && GetClientTeam(client) != team)) + continue; - for (int client = 1; client <= MaxClients; client++) - { - if (IsClientInGame(client) && GetClientTeam(client) == team) - { - if(!g_Ignored[client * (MAXPLAYERS + 1) + g_msgAuthor] && MessageForward(client, g_msgAuthor, g_msgText) ) - players[playersNum++] = client; - } - } - } - else - { - for (int client = 1; client <= MaxClients; client++) - { - if (IsClientInGame(client)) - { - if(!g_Ignored[client * (MAXPLAYERS + 1) + g_msgAuthor] && MessageForward(client, g_msgAuthor, g_msgText) ) - players[playersNum++] = client; - } - } + if (g_Ignored[client * (MAXPLAYERS + 1) + g_msgAuthor]) + continue; + + Action result = MessageForward(client, g_msgAuthor, g_msgText); + + if (result == Plugin_Changed) + rewritePlayers[rewritePlayersNum++] = client; + else if (result < Plugin_Handled) + players[playersNum++] = client; } - if (!playersNum) + // viewers who asked for a rewrite see the normal line when no plugin rewrote it + if (rewritePlayersNum && !BuildRewrittenMessage()) { - g_msgAuthor = -1; - return Plugin_Handled; + for (int i = 0; i < rewritePlayersNum; i++) + players[playersNum++] = rewritePlayers[i]; + + rewritePlayersNum = 0; } - Handle SayText2 = StartMessage("SayText2", players, playersNum, USERMSG_RELIABLE | USERMSG_BLOCKHOOKS); + if (playersNum) + SendSayText2(players, playersNum, g_msgFinal); - if (GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available && GetUserMessageType() == UM_Protobuf) - { - PbSetInt(SayText2, "ent_idx", g_msgAuthor); - PbSetBool(SayText2, "chat", g_msgIsChat); - PbSetString(SayText2, "text", g_msgFinal); - EndMessage(); - } - else - { - BfWriteByte(SayText2, g_msgAuthor); - BfWriteByte(SayText2, g_msgIsChat); - BfWriteString(SayText2, g_msgFinal); - EndMessage(); - } + if (rewritePlayersNum) + SendSayText2(rewritePlayers, rewritePlayersNum, g_msgFinalRewritten); g_msgAuthor = -1; return Plugin_Handled; @@ -2851,7 +2906,7 @@ stock bool ConfigForward(int client) return true; } -stock bool MessageForward(int client, int author, char[] message) +stock Action MessageForward(int client, int author, char[] message) { Action result = Plugin_Continue; @@ -2861,10 +2916,7 @@ stock bool MessageForward(int client, int author, char[] message) Call_PushString(message); Call_Finish(result); - if (result >= Plugin_Handled) - return false; - - return true; + return result; } public int Native_GetColor(Handle plugin, int numParams) diff --git a/custom-chatcolors/scripting/include/ccc.inc b/custom-chatcolors/scripting/include/ccc.inc index e59c653..49c10ae 100644 --- a/custom-chatcolors/scripting/include/ccc.inc +++ b/custom-chatcolors/scripting/include/ccc.inc @@ -137,10 +137,24 @@ native int CCC_ResetTag(int client); * @param client Recieving client index * @param author Author client index * @param message Message - * @return Plugin_Handled to block message, Plugin_Continue to allow message + * @return Plugin_Handled to block message, Plugin_Changed to send this client the + * copy rewritten by CCC_OnChatMessageRewrite (or the normal message if + * nothing rewrote it), Plugin_Continue to allow message */ forward Action CCC_OnChatMessage(int client, int author, const char[] message); +/** + * Called at most once per chat message, and only if a recipient's CCC_OnChatMessage returned Plugin_Changed. + * The message is the raw text, after /me and auto-replace but before coloring. + * DO NOT START A NEW USERMESSAGE (i.e. PrintToChat, PrintToChatAll) WITHIN THIS FORWARD + * + * @param author Author client index + * @param message Message buffer to rewrite in place + * @param maxlen Size of the message buffer + * @return Plugin_Changed if the message was rewritten, Plugin_Continue otherwise + */ +forward Action CCC_OnChatMessageRewrite(int author, char[] message, int maxlen); + /** * Called when a client's colors and tag are about to be loaded from the config file * At this point, the client has NO COLORS diff --git a/includes/Break.inc b/includes/Break.inc new file mode 100644 index 0000000..ffc35fc --- /dev/null +++ b/includes/Break.inc @@ -0,0 +1,51 @@ +#if defined _Break_include + #endinput +#endif +#define _Break_include + +/** + * Called when a break is started + * + * @return None + */ +forward void Break_OnBreakStarted(); + +/** + * Called when a break is finished + * + * @return None + */ +forward void Break_OnBreakFinished(); + +/** + * Called when a break is cancelled + * + * @return None + */ +forward void Break_OnBreakCancelled(); + +/** + * Returns if a break is active + * + * @return True when in break, false otherwise + */ +native bool Break_IsBreakActive(); + +public SharedPlugin __pl_Break = +{ + name = "Break", + file = "Break.smx", + +#if defined REQUIRE_PLUGIN + required = 1 +#else + required = 0 +#endif +}; + +#if !defined REQUIRE_PLUGIN + public void __pl_Break_SetNTVOptional() + { + MarkNativeAsOptional("Break_IsBreakActive"); + } +#endif diff --git a/includes/ChatFilter2.inc b/includes/ChatFilter2.inc new file mode 100644 index 0000000..88c3b35 --- /dev/null +++ b/includes/ChatFilter2.inc @@ -0,0 +1,50 @@ +#if defined _ChatFilter2_included_ + #endinput +#endif +#define _ChatFilter2_included_ + +/** + * Censors bad words in a string the same way safe chat does, with every category. + * + * @param text String to censor in place + * @param maxlen Size of text + * @return True if anything was censored + */ +native bool ChatFilter2_CensorText(char[] text, int maxlen); + +/** + * Checks if a client has safe chat enabled. + * + * @param client Client index + * @return True if safe chat is enabled + */ +native bool ChatFilter2_IsSafeChatEnabled(int client); + +/** + * Called when a client toggles safe chat, and when their cookies load with safe chat enabled. + * + * @param client Client index + * @param enabled True if safe chat is now enabled + */ +forward void ChatFilter2_OnSafeChatChanged(int client, bool enabled); + +#if !defined CHATFILTER2_CORE +public SharedPlugin __pl_ChatFilter2 = +{ + name = "ChatFilter2", + file = "ChatFilter2.smx", +#if defined REQUIRE_PLUGIN + required = 1, +#else + required = 0, +#endif +}; + +#if !defined REQUIRE_PLUGIN +public void __pl_ChatFilter2_SetNTVOptional() +{ + MarkNativeAsOptional("ChatFilter2_CensorText"); + MarkNativeAsOptional("ChatFilter2_IsSafeChatEnabled"); +} +#endif +#endif // CHATFILTER2_CORE diff --git a/includes/Couch.inc b/includes/Couch.inc new file mode 120000 index 0000000..69f366d --- /dev/null +++ b/includes/Couch.inc @@ -0,0 +1 @@ +../Couch/scripting/include/Couch.inc \ No newline at end of file diff --git a/includes/EventNotifier.inc b/includes/EventNotifier.inc new file mode 100644 index 0000000..36ac238 --- /dev/null +++ b/includes/EventNotifier.inc @@ -0,0 +1,159 @@ +#if defined _EventNotifier_included + #endinput +#endif + +#define _EventNotifier_included + +#define EVENT_STR_LEN 128 +#define EVENT_URL_LEN 192 +#define EVENT_MAPS_LEN 1024 + +enum struct EventInfo +{ + int number; + int start; // unix timestamp (UTC), 0 if unknown + int end; // unix timestamp (UTC), 0 if unknown + char url[EVENT_URL_LEN]; // forum thread URL, empty if unknown + char name[EVENT_STR_LEN]; + char server[EVENT_STR_LEN]; + char rewards[EVENT_STR_LEN]; + char leader[EVENT_STR_LEN]; + char kickers[EVENT_STR_LEN]; + char maps[EVENT_MAPS_LEN]; // ", "-joined list +} + +#if !defined EVENTNOTIFIER_CORE + +/** + * Number of events in the last successful fetch (0 before the first fetch). + * + * @return Event count. + */ +native int EventNotifier_GetEventCount(); + +/** + * Whether at least one fetch has succeeded since the plugin loaded. + * + * @return True once the event list has been fetched. + */ +native bool EventNotifier_HasFetched(); + +/** + * Finds an event by its event number. + * + * @param number Event number. + * @return Index into the event list, or -1 if not found. + */ +native int EventNotifier_FindEventByNumber(int number); + +/** + * Copies an event into the caller's EventInfo. + * + * @param index Index into the event list. + * @param ev EventInfo to fill. + * @param size Size of ev, must be sizeof(EventInfo). + * @return True on success, false if index is out of range. + * @error Buffer smaller than sizeof(EventInfo). + */ +native bool EventNotifier_GetEvent(int index, any[] ev, int size = sizeof(EventInfo)); + +/** + * Starts a fetch of the event list now. No-op if a fetch is already running. + */ +native void EventNotifier_Refresh(); + +/** + * Formats a timestamp in the client's own timezone (looked up via GeoIP), + * e.g. "Thu 01 Oct 2026, 20:00 BST". Clients whose timezone is unknown get + * sm_event_fallback_timezone. + * + * @param client Client index, 0 for the fallback timezone. + * @param timestamp Unix timestamp (UTC). + * @param buffer Destination buffer. + * @param maxlen Size of buffer. + * @param withYear Whether to include the year. + * @error Invalid client index. + */ +native void EventNotifier_FormatClientTime(int client, int timestamp, char[] buffer, int maxlen, bool withYear = true); + +/** + * Called after every successful fetch, once the event list has been replaced. + */ +forward void EventNotifier_OnEventsUpdated(); + +#endif // EVENTNOTIFIER_CORE + +// --------------------------------------------------------------------------- +// Display helpers +// --------------------------------------------------------------------------- + +/** + * Formats a duration in seconds as "1d 2h 3m", "2h 3m" or "3m". + */ +stock void EventNotifier_FormatDuration(int seconds, char[] buffer, int maxlen) +{ + int days = seconds / 86400; + int hours = (seconds % 86400) / 3600; + int minutes = (seconds % 3600) / 60; + + if (days > 0) + Format(buffer, maxlen, "%dd %dh %dm", days, hours, minutes); + else if (hours > 0) + Format(buffer, maxlen, "%dh %dm", hours, minutes); + else + Format(buffer, maxlen, "%dm", minutes); +} + +/** + * Formats an event's status relative to now as a "Status: ..." line. + */ +stock void EventNotifier_FormatRelativeTime(int start, int end, char[] buffer, int maxlen) +{ + int now = GetTime(); + + if (end > 0 && now >= start && now < end) + { + strcopy(buffer, maxlen, "Status: In progress now!"); + return; + } + + char span[32]; + if (now >= start) + { + EventNotifier_FormatDuration(now - start, span, sizeof(span)); + Format(buffer, maxlen, "Status: Started %s ago", span); + } + else + { + EventNotifier_FormatDuration(start - now, span, sizeof(span)); + Format(buffer, maxlen, "Status: Starts in %s", span); + } +} + +#if !defined EVENTNOTIFIER_CORE + +public SharedPlugin __pl_EventNotifier = +{ + name = "EventNotifier", + file = "EventNotifier.smx", + + #if defined REQUIRE_PLUGIN + required = 1 + #else + required = 0 + #endif +}; + +#if !defined REQUIRE_PLUGIN + public void __pl_EventNotifier_SetNTVOptional() + { + MarkNativeAsOptional("EventNotifier_GetEventCount"); + MarkNativeAsOptional("EventNotifier_HasFetched"); + MarkNativeAsOptional("EventNotifier_FindEventByNumber"); + MarkNativeAsOptional("EventNotifier_GetEvent"); + MarkNativeAsOptional("EventNotifier_Refresh"); + MarkNativeAsOptional("EventNotifier_FormatClientTime"); + } +#endif + +#endif // EVENTNOTIFIER_CORE diff --git a/includes/TransmitManager.inc b/includes/TransmitManager.inc new file mode 100644 index 0000000..f2e7fb2 --- /dev/null +++ b/includes/TransmitManager.inc @@ -0,0 +1,30 @@ +#if defined _TransmitManager_included + #endinput +#endif +#define _TransmitManager_included + +native void TransmitManager_AddEntityHooks(int entity); +native bool TransmitManager_SetEntityOwner(int entity, int target); +native bool TransmitManager_SetEntityState(int entity, int client, bool can); +native bool TransmitManager_GetEntityState(int entity, int client); +native bool TransmitManager_IsEntityHooked(int entity); + +/** + * _________________Do not edit below this line!_______________________ + */ +public Extension __ext_transmit = +{ + name = "TransmitManager", + file = "TransmitManager.ext", +#if defined AUTOLOAD_EXTENSIONS + autoload = 1, +#else + autoload = 0, +#endif +#if defined REQUIRE_EXTENSIONS + required = 1, +#else + required = 0, +#endif +}; + diff --git a/includes/leader.inc b/includes/leader.inc new file mode 100644 index 0000000..df9f9a3 --- /dev/null +++ b/includes/leader.inc @@ -0,0 +1,90 @@ +#if defined _leader_included_ + #endinput +#endif +#define _leader_included_ + +/** + * Returns the current PRIMARY leader. + * + * @return Client index of the primary leader (-1 = no leader) + */ +native int Leader_CurrentLeader(); + +/** + * Makes a client the PRIMARY leader. If another primary exists, they are + * demoted to sub-leader. If the client is already a sub-leader, they are + * promoted. + * + * @param client Client index to be set as primary leader + */ +native void Leader_SetLeader(int client); + +/** + * Checks if a client is currently a leader (primary or sub-leader). + * + * @param client Client index to check + * @return True if the client is a leader + */ +native bool Leader_Is(int client); + +/** + * Returns the number of current leaders (primary + sub-leaders). + * + * @return Leader count + */ +native int Leader_GetLeaderCount(); + +/** + * Returns the leader at the given roster index. + * + * @param index Roster index (0 = primary) + * @return Client index, or -1 if no leader at that index + */ +native int Leader_GetLeader(int index); + +/** + * Called after a client becomes a leader. + * + * @param client The new leader + * @param primary True if they became the primary leader + */ +forward void Leader_OnLeaderAdded(int client, bool primary); + +/** + * Called after a client stops being a leader. + * + * @param client The removed leader + */ +forward void Leader_OnLeaderRemoved(int client); + +/** + * Called when the primary leader changes. + * + * @param oldLeader Previous primary (-1 = none) + * @param newLeader New primary (-1 = none) + */ +forward void Leader_OnPrimaryChanged(int oldLeader, int newLeader); + +#if !defined LEADER3_CORE +public SharedPlugin __pl_leader = +{ + name = "leader", + file = "Leader3.smx", +#if defined REQUIRE_PLUGIN + required = 1, +#else + required = 0, +#endif +}; + +#if !defined REQUIRE_PLUGIN +public void __pl_leader_SetNTVOptional() +{ + MarkNativeAsOptional("Leader_CurrentLeader"); + MarkNativeAsOptional("Leader_SetLeader"); + MarkNativeAsOptional("Leader_Is"); + MarkNativeAsOptional("Leader_GetLeaderCount"); + MarkNativeAsOptional("Leader_GetLeader"); +} +#endif +#endif // LEADER3_CORE diff --git a/includes/ripext.inc b/includes/ripext.inc new file mode 100644 index 0000000..9fc02e3 --- /dev/null +++ b/includes/ripext.inc @@ -0,0 +1,26 @@ +#if defined _ripext_included_ + #endinput +#endif +#define _ripext_included_ + +#include +#include + +/** + * Do not edit below this line! + */ +public Extension __ext_rip = +{ + name = "REST in Pawn", + file = "rip.ext", +#if defined AUTOLOAD_EXTENSIONS + autoload = 1, +#else + autoload = 0, +#endif +#if defined REQUIRE_EXTENSIONS + required = 1, +#else + required = 0, +#endif +}; diff --git a/includes/ripext/http.inc b/includes/ripext/http.inc new file mode 100644 index 0000000..3122f22 --- /dev/null +++ b/includes/ripext/http.inc @@ -0,0 +1,359 @@ +enum HTTPStatus +{ + HTTPStatus_Invalid = 0, + + // 1xx Informational + HTTPStatus_Continue = 100, + HTTPStatus_SwitchingProtocols = 101, + + // 2xx Success + HTTPStatus_OK = 200, + HTTPStatus_Created = 201, + HTTPStatus_Accepted = 202, + HTTPStatus_NonAuthoritativeInformation = 203, + HTTPStatus_NoContent = 204, + HTTPStatus_ResetContent = 205, + HTTPStatus_PartialContent = 206, + + // 3xx Redirection + HTTPStatus_MultipleChoices = 300, + HTTPStatus_MovedPermanently = 301, + HTTPStatus_Found = 302, + HTTPStatus_SeeOther = 303, + HTTPStatus_NotModified = 304, + HTTPStatus_UseProxy = 305, + HTTPStatus_TemporaryRedirect = 307, + HTTPStatus_PermanentRedirect = 308, + + // 4xx Client Error + HTTPStatus_BadRequest = 400, + HTTPStatus_Unauthorized = 401, + HTTPStatus_PaymentRequired = 402, + HTTPStatus_Forbidden = 403, + HTTPStatus_NotFound = 404, + HTTPStatus_MethodNotAllowed = 405, + HTTPStatus_NotAcceptable = 406, + HTTPStatus_ProxyAuthenticationRequired = 407, + HTTPStatus_RequestTimeout = 408, + HTTPStatus_Conflict = 409, + HTTPStatus_Gone = 410, + HTTPStatus_LengthRequired = 411, + HTTPStatus_PreconditionFailed = 412, + HTTPStatus_RequestEntityTooLarge = 413, + HTTPStatus_RequestURITooLong = 414, + HTTPStatus_UnsupportedMediaType = 415, + HTTPStatus_RequestedRangeNotSatisfiable = 416, + HTTPStatus_ExpectationFailed = 417, + HTTPStatus_MisdirectedRequest = 421, + HTTPStatus_TooEarly = 425, + HTTPStatus_UpgradeRequired = 426, + HTTPStatus_PreconditionRequired = 428, + HTTPStatus_TooManyRequests = 429, + HTTPStatus_RequestHeaderFieldsTooLarge = 431, + HTTPStatus_UnavailableForLegalReasons = 451, + + // 5xx Server Error + HTTPStatus_InternalServerError = 500, + HTTPStatus_NotImplemented = 501, + HTTPStatus_BadGateway = 502, + HTTPStatus_ServiceUnavailable = 503, + HTTPStatus_GatewayTimeout = 504, + HTTPStatus_HTTPVersionNotSupported = 505, + HTTPStatus_VariantAlsoNegotiates = 506, + HTTPStatus_NotExtended = 510, + HTTPStatus_NetworkAuthenticationRequired = 511, +}; + +typeset HTTPRequestCallback +{ + function void (HTTPResponse response, any value); + function void (HTTPResponse response, any value, const char[] error); +}; + +typeset HTTPFileCallback +{ + function void (HTTPStatus status, any value); + function void (HTTPStatus status, any value, const char[] error); +}; + +methodmap HTTPRequest < Handle +{ + // Creates an HTTP request. + // + // The Handle is automatically freed when the request is performed. + // Otherwise, the Handle must be freed via delete or CloseHandle(). + // + // @param url URL to the REST API endpoint. + public native HTTPRequest(const char[] url); + + // Appends a parameter to the form data. + // + // The parameter name and value are encoded according to RFC 3986. + // + // @param name Parameter name. + // @param format Formatting rules. + // @param ... Variable number of format parameters. + public native void AppendFormParam(const char[] name, const char[] format, any ...); + + // Appends a query parameter to the URL. + // + // The parameter name and value are encoded according to RFC 3986. + // + // @param name Parameter name. + // @param format Formatting rules. + // @param ... Variable number of format parameters. + public native void AppendQueryParam(const char[] name, const char[] format, any ...); + + // Sets the credentials for HTTP Basic authentication. + // + // @param username Username to use. + // @param password Password to use. + public native void SetBasicAuth(const char[] username, const char[] password); + + // Sets an HTTP header. + // + // @param name Header name. + // @param format Formatting rules. + // @param ... Variable number of format parameters. + public native void SetHeader(const char[] name, const char[] format, any ...); + + // Performs an HTTP GET request. + // + // This function closes the request Handle after completing. + // + // @param callback A function to use as a callback when the request has finished. + // @param value Optional value to pass to the callback function. + public native void Get(HTTPRequestCallback callback, any value = 0); + + // Performs an HTTP POST request. + // + // This function closes the request Handle after completing. + // + // @param data JSON data to send. + // @param callback A function to use as a callback when the request has finished. + // @param value Optional value to pass to the callback function. + public native void Post(JSON data, HTTPRequestCallback callback, any value = 0); + + // Performs an HTTP PUT request. + // + // This function closes the request Handle after completing. + // + // @param data JSON data to send. + // @param callback A function to use as a callback when the request has finished. + // @param value Optional value to pass to the callback function. + public native void Put(JSON data, HTTPRequestCallback callback, any value = 0); + + // Performs an HTTP PATCH request. + // + // This function closes the request Handle after completing. + // + // @param data JSON data to send. + // @param callback A function to use as a callback when the request has finished. + // @param value Optional value to pass to the callback function. + public native void Patch(JSON data, HTTPRequestCallback callback, any value = 0); + + // Performs an HTTP DELETE request. + // + // This function closes the request Handle after completing. + // + // @param callback A function to use as a callback when the request has finished. + // @param value Optional value to pass to the callback function. + public native void Delete(HTTPRequestCallback callback, any value = 0); + + // Downloads a file. + // + // This function closes the request Handle after completing. + // + // @param path File path to write to. + // @param callback A function to use as a callback when the download has finished. + // @param value Optional value to pass to the callback function. + public native void DownloadFile(const char[] path, HTTPFileCallback callback, any value = 0); + + // Uploads a file. + // + // This function performs an HTTP PUT request. The file contents are sent in the request body. + // This function closes the request Handle after completing. + // + // @param path File path to read from. + // @param callback A function to use as a callback when the upload has finished. + // @param value Optional value to pass to the callback function. + public native void UploadFile(const char[] path, HTTPFileCallback callback, any value = 0); + + // Performs an HTTP POST request with form data. + // + // This function closes the request Handle after completing. + // + // @param callback A function to use as a callback when the request has finished. + // @param value Optional value to pass to the callback function. + public native void PostForm(HTTPRequestCallback callback, any value = 0); + + // Connect timeout in seconds. Defaults to 10. + property int ConnectTimeout { + public native get(); + public native set(int connectTimeout); + } + + // Maximum number of redirects to follow. Defaults to 5. + property int MaxRedirects { + public native get(); + public native set(int maxRedirects); + } + + // Maximum download speed in bytes per second. Defaults to unlimited speed. + property int MaxRecvSpeed { + public native get(); + public native set(int maxSpeed); + } + + // Maximum upload speed in bytes per second. Defaults to unlimited speed. + property int MaxSendSpeed { + public native get(); + public native set(int maxSpeed); + } + + // Timeout in seconds. Defaults to 30. + property int Timeout { + public native get(); + public native set(int timeout); + } +} + +methodmap HTTPResponse +{ + // Retrieves an HTTP header from the response. + // + // @param name Header name. + // @param buffer String buffer to store value. + // @param maxlength Maximum length of the string buffer. + // @return True on success, false if the header was not found. + public native bool GetHeader(const char[] name, char[] buffer, int maxlength); + + // Retrieves the JSON data of the response. + // + // @error Invalid JSON response. + property JSON Data { + public native get(); + } + + // Retrieves the HTTP status of the response. + property HTTPStatus Status { + public native get(); + } +}; + +// Deprecated. Use HTTPRequest instead. +methodmap HTTPClient < Handle +{ + // Creates an HTTP client. + // + // The HTTPClient must be freed via delete or CloseHandle(). + // + // @param baseURL Base URL to the REST API. + #pragma deprecated Use HTTPRequest instead. + public native HTTPClient(const char[] baseURL); + + // Sets an HTTP header to be used for all requests. + // + // @param name Header name. + // @param value String value to set. + #pragma deprecated Use HTTPRequest.SetHeader() instead. + public native void SetHeader(const char[] name, const char[] value); + + // Performs an HTTP GET request. + // + // @param endpoint API endpoint to request. + // @param callback A function to use as a callback when the request has finished. + // @param value Optional value to pass to the callback function. + #pragma deprecated Use HTTPRequest.Get() instead. + public native void Get(const char[] endpoint, HTTPRequestCallback callback, any value = 0); + + // Performs an HTTP POST request. + // + // @param endpoint API endpoint to request. + // @param data JSON data to send. + // @param callback A function to use as a callback when the request has finished. + // @param value Optional value to pass to the callback function. + #pragma deprecated Use HTTPRequest.Post() instead. + public native void Post(const char[] endpoint, JSON data, HTTPRequestCallback callback, any value = 0); + + // Performs an HTTP PUT request. + // + // @param endpoint API endpoint to request. + // @param data JSON data to send. + // @param callback A function to use as a callback when the request has finished. + // @param value Optional value to pass to the callback function. + #pragma deprecated Use HTTPRequest.Put() instead. + public native void Put(const char[] endpoint, JSON data, HTTPRequestCallback callback, any value = 0); + + // Performs an HTTP PATCH request. + // + // @param endpoint API endpoint to request. + // @param data JSON data to send. + // @param callback A function to use as a callback when the request has finished. + // @param value Optional value to pass to the callback function. + #pragma deprecated Use HTTPRequest.Patch() instead. + public native void Patch(const char[] endpoint, JSON data, HTTPRequestCallback callback, any value = 0); + + // Performs an HTTP DELETE request. + // + // @param endpoint API endpoint to request. + // @param callback A function to use as a callback when the request has finished. + // @param value Optional value to pass to the callback function. + #pragma deprecated Use HTTPRequest.Delete() instead. + public native void Delete(const char[] endpoint, HTTPRequestCallback callback, any value = 0); + + // Downloads a file. + // + // @param endpoint API endpoint to download from. + // @param path File path to write to. + // @param callback A function to use as a callback when the download has finished. + // @param value Optional value to pass to the callback function. + #pragma deprecated Use HTTPRequest.DownloadFile() instead. + public native void DownloadFile(const char[] endpoint, const char[] path, HTTPFileCallback callback, any value = 0); + + // Uploads a file. + // + // This function performs an HTTP PUT request. The file contents are sent in the request body. + // + // @param endpoint API endpoint to upload to. + // @param path File path to read from. + // @param callback A function to use as a callback when the upload has finished. + // @param value Optional value to pass to the callback function. + #pragma deprecated Use HTTPRequest.UploadFile() instead. + public native void UploadFile(const char[] endpoint, const char[] path, HTTPFileCallback callback, any value = 0); + + // Connect timeout in seconds. Defaults to 10. + #pragma deprecated Use HTTPRequest.ConnectTimeout instead. + property int ConnectTimeout { + public native get(); + public native set(int connectTimeout); + } + + // Follow HTTP 3xx redirects. Defaults to true. + #pragma deprecated Use HTTPRequest.MaxRedirects instead. + property bool FollowLocation { + public native get(); + public native set(bool followLocation); + } + + // Timeout in seconds. Defaults to 30. + #pragma deprecated Use HTTPRequest.Timeout instead. + property int Timeout { + public native get(); + public native set(int timeout); + } + + // Maximum upload speed in bytes per second. Defaults to unlimited speed. + #pragma deprecated Use HTTPRequest.MaxSendSpeed instead. + property int MaxSendSpeed { + public native get(); + public native set(int speed); + } + + // Maximum download speed in bytes per second. Defaults to unlimited speed. + #pragma deprecated Use HTTPRequest.MaxRecvSpeed instead. + property int MaxRecvSpeed { + public native get(); + public native set(int speed); + } +}; diff --git a/includes/ripext/json.inc b/includes/ripext/json.inc new file mode 100644 index 0000000..9d13ef9 --- /dev/null +++ b/includes/ripext/json.inc @@ -0,0 +1,400 @@ +// Decoding flags +enum +{ + JSON_REJECT_DUPLICATES = 0x1, /**< Error if any JSON object contains duplicate keys */ + JSON_DISABLE_EOF_CHECK = 0x2, /**< Allow extra data after a valid JSON array or object */ + JSON_DECODE_ANY = 0x4, /**< Decode any value */ + JSON_DECODE_INT_AS_REAL = 0x8, /**< Interpret all numbers as floats */ + JSON_ALLOW_NUL = 0x10 /**< Allow \u0000 escape inside string values */ +}; + +// Encoding flags +enum +{ + JSON_COMPACT = 0x20, /**< Compact representation */ + JSON_ENSURE_ASCII = 0x40, /**< Escape all Unicode characters outside the ASCII range */ + JSON_SORT_KEYS = 0x80, /**< Sort object keys */ + JSON_ENCODE_ANY = 0x200, /**< Encode any value */ + JSON_ESCAPE_SLASH = 0x400, /**< Escape / with \/ */ + JSON_EMBED = 0x10000 /**< Omit opening and closing braces of the top-level object */ +}; + +// Maximum indentation +static const int JSON_MAX_INDENT = 0x1F; + +// Pretty-print the result, indenting with n spaces +stock int JSON_INDENT(int n) +{ + return n & JSON_MAX_INDENT; +} + +// Output floats with at most n digits of precision +stock int JSON_REAL_PRECISION(int n) +{ + return (n & 0x1F) << 11; +} + +// Generic type for encoding JSON. +methodmap JSON < Handle +{ + // Writes the JSON string representation to a file. + // + // @param file File to write to. + // @param flags Encoding flags. + // @return True on success, false on failure. + public native bool ToFile(const char[] file, int flags = 0); + + // Retrieves the JSON string representation. + // + // @param buffer String buffer to write to. + // @param maxlength Maximum length of the string buffer. + // @param flags Encoding flags. + // @return True on success, false on failure. + public native bool ToString(char[] buffer, int maxlength, int flags = 0); +}; + +methodmap JSONObject < JSON +{ + // Creates a JSON object. A JSON object maps strings (called "keys") to values. Keys in a + // JSON object are unique. That is, there is at most one entry in the map for a given key. + // + // The JSONObject must be freed via delete or CloseHandle(). + public native JSONObject(); + + // Loads a JSON object from a file. + // + // @param file File to read from. + // @param flags Decoding flags. + // @return Object handle, or null on failure. + // @error Invalid JSON. + public static native JSONObject FromFile(const char[] file, int flags = 0); + + // Loads a JSON object from a string. + // + // @param buffer String buffer to load into the JSON object. + // @param flags Decoding flags. + // @return Object handle, or null on failure. + // @error Invalid JSON. + public static native JSONObject FromString(const char[] buffer, int flags = 0); + + // Retrieves an array or object value from the object. + // + // The JSON must be freed via delete or CloseHandle(). + // + // @param key Key string. + // @return Value read. + // @error Invalid key. + public native JSON Get(const char[] key); + + // Retrieves a boolean value from the object. + // + // @param key Key string. + // @return Value read. + // @error Invalid key. + public native bool GetBool(const char[] key); + + // Retrieves a float value from the object. + // + // @param key Key string. + // @return Value read. + // @error Invalid key. + public native float GetFloat(const char[] key); + + // Retrieves an integer value from the object. + // + // @param key Key string. + // @return Value read. + // @error Invalid key. + public native int GetInt(const char[] key); + + // Retrieves a 64-bit integer value from the object. + // + // @param key Key string. + // @param buffer String buffer to store value. + // @param maxlength Maximum length of the string buffer. + // @return True on success, false if the key was not found. + public native bool GetInt64(const char[] key, char[] buffer, int maxlength); + + // Retrieves a string value from the object. + // + // @param key Key string. + // @param buffer String buffer to store value. + // @param maxlength Maximum length of the string buffer. + // @return True on success. False if the key was not found, or the value is not a string. + public native bool GetString(const char[] key, char[] buffer, int maxlength); + + // Returns whether or not a value in the object is null. + // + // @param key Key string. + // @return True if the value is null, false otherwise. + // @error Invalid key. + public native bool IsNull(const char[] key); + + // Returns whether or not a key exists in the object. + // + // @param key Key string. + // @return True if the key exists, false otherwise. + public native bool HasKey(const char[] key); + + // Sets an array or object value in the object, either inserting a new entry or replacing an old one. + // + // @param key Key string. + // @param value Value to store at this key. + // @return True on success, false on failure. + public native bool Set(const char[] key, JSON value); + + // Sets a boolean value in the object, either inserting a new entry or replacing an old one. + // + // @param key Key string. + // @param value Value to store at this key. + // @return True on success, false on failure. + public native bool SetBool(const char[] key, bool value); + + // Sets a float value in the object, either inserting a new entry or replacing an old one. + // + // @param key Key string. + // @param value Value to store at this key. + // @return True on success, false on failure. + public native bool SetFloat(const char[] key, float value); + + // Sets an integer value in the object, either inserting a new entry or replacing an old one. + // + // @param key Key string. + // @param value Value to store at this key. + // @return True on success, false on failure. + public native bool SetInt(const char[] key, int value); + + // Sets a 64-bit integer value in the object, either inserting a new entry or replacing an old one. + // + // @param key Key string. + // @param value Value to store at this key. + // @return True on success, false on failure. + public native bool SetInt64(const char[] key, const char[] value); + + // Sets a null value in the object, either inserting a new entry or replacing an old one. + // + // @param key Key string. + // @return True on success, false on failure. + public native bool SetNull(const char[] key); + + // Sets a string value in the object, either inserting a new entry or replacing an old one. + // + // @param key Key string. + // @param value Value to store at this key. + // @return True on success, false on failure. + public native bool SetString(const char[] key, const char[] value); + + // Removes an entry from the object. + // + // @param key Key string. + // @return True on success, false if the key was not found. + public native bool Remove(const char[] key); + + // Clears the object of all entries. + // @return True on success, false on failure. + public native bool Clear(); + + // Returns an iterator for the object's keys. See JSONObjectKeys. + public native JSONObjectKeys Keys(); + + // Retrieves the size of the object. + property int Size { + public native get(); + } +}; + +/** + * A JSONObjectKeys is created via JSONObject.Keys(). It allows the keys of an + * object to be iterated. The JSONObjectKeys must be freed with delete or + * CloseHandle(). + */ +methodmap JSONObjectKeys < Handle +{ + // Reads an object key, then advances to the next key if any. + // + // @param buffer String buffer to store key. + // @param maxlength Maximum length of the string buffer. + // @return True on success, false if there are no more keys. + public native bool ReadKey(char[] buffer, int maxlength); +}; + +methodmap JSONArray < JSON +{ + // Creates a JSON array. + // + // The JSONArray must be freed via delete or CloseHandle(). + public native JSONArray(); + + // Loads a JSON array from a file. + // + // @param file File to read from. + // @param flags Decoding flags. + // @return Array handle, or null on failure. + // @error Invalid JSON. + public static native JSONArray FromFile(const char[] file, int flags = 0); + + // Loads a JSON array from a string. + // + // @param buffer String buffer to load into the JSON array. + // @param flags Decoding flags. + // @return Array handle, or null on failure. + // @error Invalid JSON. + public static native JSONArray FromString(const char[] buffer, int flags = 0); + + // Retrieves an array or object value from the array. + // + // The JSON must be freed via delete or CloseHandle(). + // + // @param index Index in the array. + // @return Value read. + // @error Invalid index. + public native JSON Get(int index); + + // Retrieves a boolean value from the array. + // + // @param index Index in the array. + // @return Value read. + // @error Invalid index. + public native bool GetBool(int index); + + // Retrieves a float value from the array. + // + // @param index Index in the array. + // @return Value read. + // @error Invalid index. + public native float GetFloat(int index); + + // Retrieves an integer value from the array. + // + // @param index Index in the array. + // @return Value read. + // @error Invalid index. + public native int GetInt(int index); + + // Retrieves an 64-bit integer value from the array. + // + // @param index Index in the array. + // @param buffer Buffer to copy to. + // @param maxlength Maximum size of the buffer. + // @error Invalid index. + public native void GetInt64(int index, char[] buffer, int maxlength); + + // Retrieves a string value from the array. + // + // @param index Index in the array. + // @param buffer Buffer to copy to. + // @param maxlength Maximum size of the buffer. + // @return True on success, false if the value is not a string. + // @error Invalid index. + public native bool GetString(int index, char[] buffer, int maxlength); + + // Returns whether or not a value in the array is null. + // + // @param index Index in the array. + // @return True if the value is null, false otherwise. + // @error Invalid index. + public native bool IsNull(int index); + + // Sets an array or object value in the array. + // + // @param index Index in the array. + // @param value Value to set. + // @return True on success, false on failure. + public native bool Set(int index, JSON value); + + // Sets a boolean value in the array. + // + // @param index Index in the array. + // @param value Value to set. + // @return True on success, false on failure. + public native bool SetBool(int index, bool value); + + // Sets a float value in the array. + // + // @param index Index in the array. + // @param value Value to set. + // @return True on success, false on failure. + public native bool SetFloat(int index, float value); + + // Sets an integer value in the array. + // + // @param index Index in the array. + // @param value Value to set. + // @return True on success, false on failure. + public native bool SetInt(int index, int value); + + // Sets a 64 bit integer value in the array. + // + // @param index Index in the array. + // @param value 64-bit integer value to set. + // @return True on success, false on failure. + public native bool SetInt64(int index, const char[] value); + + // Sets a null value in the array. + // + // @param index Index in the array. + // @return True on success, false on failure. + public native bool SetNull(int index); + + // Sets a string value in the array. + // + // @param index Index in the array. + // @param value String value to set. + // @return True on success, false on failure. + public native bool SetString(int index, const char[] value); + + // Pushes an array or object value onto the end of the array, adding a new index. + // + // @param value Value to push. + // @return True on success, false on failure. + public native bool Push(JSON value); + + // Pushes a boolean value onto the end of the array, adding a new index. + // + // @param value Value to push. + // @return True on success, false on failure. + public native bool PushBool(bool value); + + // Pushes a float value onto the end of the array, adding a new index. + // + // @param value Value to push. + // @return True on success, false on failure. + public native bool PushFloat(float value); + + // Pushes an integer value onto the end of the array, adding a new index. + // + // @param value Value to push. + // @return True on success, false on failure. + public native bool PushInt(int value); + + // Pushes a 64-bit integer value onto the end of the array, adding a new index. + // + // @param value 64-bit integer value to push. + // @return True on success, false on failure. + public native bool PushInt64(const char[] value); + + // Pushes a null value onto the end of the array, adding a new index. + // @return True on success, false on failure. + public native bool PushNull(); + + // Pushes a string value onto the end of the array, adding a new index. + // + // @param value String value to push. + // @return True on success, false on failure. + public native bool PushString(const char[] value); + + // Removes an entry from the array. + // + // @param index Index in the array to remove. + // @return True on success, false on invalid index. + public native bool Remove(int index); + + // Clears the array of all entries. + // @return True on success, false on failure. + public native bool Clear(); + + // Retrieves the size of the array. + property int Length { + public native get(); + } +}; diff --git a/includes/unloze_playtime.inc b/includes/unloze_playtime.inc new file mode 100644 index 0000000..2bebf1a --- /dev/null +++ b/includes/unloze_playtime.inc @@ -0,0 +1,26 @@ +#if defined _unloze_playtime_included_ + #endinput +#endif +#define _unloze_playtime_included_ + +/** +* @returns the average playtime of all connected players excluding autism bots, fakeclients, AFKS and nosteamers +*/ +native int GetAveragePlayerTimeOnServer(); + +/** +* @returns the players rtv amount boost +*/ +native int GetPlayerWorthRTV_boost_(int client); + +/** + * returns a players hours for a specific server + * + * @int the actual client + * @int Game time hours that the client has on the server. + * @int Game time minutes the client has on the server. + */ + +native int GetPlayerTier_native(int client); //just the clients tier +forward void GetPlayerHoursServer(int client, int hours, int minutes); +forward void GetPlayerTier(int client, int tier);