#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; }