ProfanityFilter.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. /*
  2. * Copyright (c) 2014, Oculus VR, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under the BSD-style license found in the
  6. * LICENSE file in the root directory of this source tree. An additional grant
  7. * of patent rights can be found in the PATENTS file in the same directory.
  8. *
  9. */
  10. #include "ProfanityFilter.h"
  11. #include "Rand.h"
  12. #include "RakAssert.h"
  13. #include "LinuxStrings.h"
  14. #if defined(_WIN32)
  15. #include <malloc.h> // alloca
  16. #elif (defined(__GNUC__) || defined(__GCCXML__))
  17. #include <alloca.h>
  18. #else
  19. #endif
  20. using namespace RakNet;
  21. char ProfanityFilter::BANCHARS[] = "!@#$%^&*()";
  22. char ProfanityFilter::WORDCHARS[] = "abcdefghijklmnopqrstuvwxyz0123456789";
  23. ProfanityFilter::ProfanityFilter()
  24. {
  25. }
  26. ProfanityFilter::~ProfanityFilter()
  27. {
  28. }
  29. char ProfanityFilter::RandomBanChar()
  30. {
  31. return BANCHARS[randomMT() % (sizeof(BANCHARS) - 1)];
  32. }
  33. bool ProfanityFilter::HasProfanity(const char *str)
  34. {
  35. return FilterProfanity(str, 0,false) > 0;
  36. }
  37. int ProfanityFilter::FilterProfanity(const char *input, char *output, bool filter)
  38. {
  39. if (input==0 || input[0]==0)
  40. return 0;
  41. int count = 0;
  42. char* b = (char *) alloca(strlen(input) + 1);
  43. strcpy(b, input);
  44. _strlwr(b);
  45. char *start = b;
  46. if (output)
  47. strcpy(output,input);
  48. start = strpbrk(start, WORDCHARS);
  49. while (start != 0)
  50. {
  51. size_t len = strspn(start, WORDCHARS);
  52. if (len > 0)
  53. {
  54. // we a have a word - let's check if it's a BAAAD one
  55. char saveChar = start[len];
  56. start[len] = '\0';
  57. // loop through profanity list
  58. for (unsigned int i = 0, size = words.Size(); i < size; i++)
  59. {
  60. if (_stricmp(start, words[i].C_String()) == 0)
  61. {
  62. count++;
  63. // size_t len = words[i].size();
  64. if (filter && output)
  65. {
  66. for (unsigned int j = 0; j < len; j++)
  67. {
  68. output[start + j - b] = RandomBanChar();
  69. }
  70. }
  71. break;
  72. }
  73. }
  74. start[len] = saveChar;
  75. }
  76. start += len;
  77. start = strpbrk(start, WORDCHARS);
  78. }
  79. return count;
  80. }
  81. int ProfanityFilter::Count()
  82. {
  83. return words.Size();
  84. }
  85. void ProfanityFilter::AddWord(RakNet::RakString newWord)
  86. {
  87. words.Insert(newWord, _FILE_AND_LINE_ );
  88. }
粤ICP备19079148号