CharMail.php 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. <?php
  2. namespace App\Models\Char;
  3. use Illuminate\Database\Eloquent\Model;
  4. class CharMail extends Model
  5. {
  6. protected $connection = 'Char';
  7. protected $table = 'Table_CharMail';
  8. protected $primaryKey = 'MailDBKey';
  9. protected $dates = ['CreateDate', 'ReadDate'];
  10. protected $fillable = [
  11. 'RecverDBKey',
  12. 'Slot',
  13. 'Deleted',
  14. 'MailDBKey',
  15. 'SentMailDBKey',
  16. 'SenderDBKeyAccount',
  17. 'SenderDBKey',
  18. 'SendName',
  19. 'RecvName',
  20. 'bRead',
  21. 'Title',
  22. 'MailType',
  23. 'CreateDate',
  24. 'ReadDate',
  25. 'Money',
  26. 'AlreadyMoney',
  27. 'Letter',
  28. 'ItemCount',
  29. 'ItemSlot0',
  30. 'ItemSlot1',
  31. 'ItemSlot2',
  32. 'ItemSlot3',
  33. 'ItemSlot4',
  34. 'AlreadyItem0',
  35. 'AlreadyItem1',
  36. 'AlreadyItem2',
  37. 'AlreadyItem3',
  38. 'AlreadyItem4',
  39. 'AlreadyItem5',
  40. 'AlreadyItem6',
  41. 'AlreadyItem7',
  42. 'AlreadyItem8',
  43. 'AlreadyItem9',
  44. 'Confirm',
  45. 'binLetter',
  46. 'MailSerial',
  47. 'binTitle',
  48. ];
  49. public $timestamps = false;
  50. public function getBinLetterAttribute($value)
  51. {
  52. return $this->decodeBinaryValue($value);
  53. }
  54. public function setBinLetterAttribute($value)
  55. {
  56. $this->attributes['binLetter'] = $this->encodeBinaryValue($value);
  57. }
  58. public function getBinTitleAttribute($value)
  59. {
  60. return $this->decodeBinaryValue($value);
  61. }
  62. public function setBinTitleAttribute($value)
  63. {
  64. $this->attributes['binTitle'] = $this->encodeBinaryValue($value);
  65. }
  66. private function decodeBinaryValue(?string $value): ?string
  67. {
  68. // Удаляем завершающие нули – они часто встречаются в char( n ) столбцах
  69. $value = $this->stripNulls($value);
  70. if ($value === null || $value === '') {
  71. return $value;
  72. }
  73. // Пробуем декодировать максимум два раза (схема хранения – двойной base64)
  74. $decoded = $value;
  75. for ($i = 0; $i < 2; $i++) {
  76. $tmp = base64_decode($decoded, true);
  77. if ($tmp === false) {
  78. // Строка не похожа на base64 – прекращаем попытки
  79. break;
  80. }
  81. $decoded = $this->stripNulls($tmp);
  82. }
  83. return $decoded === null ? null : $this->ensureUtf8($decoded);
  84. }
  85. private function encodeBinaryValue(?string $value): ?string
  86. {
  87. $value = $this->stripNulls($value);
  88. if ($value === null || $value === '') {
  89. return $value;
  90. }
  91. // Если строка уже дважды закодирована – ничего не делаем
  92. if ($this->isBase64($value)) {
  93. $inner = base64_decode($value, true);
  94. if ($inner !== false && $this->isBase64($inner)) {
  95. return $value; // уже двойной base64
  96. }
  97. // Если только один слой – добавляем ещё один
  98. return base64_encode($value);
  99. }
  100. // Конвертируем в CP1251 (игровой клиент ожидает именно эту кодировку)
  101. $prepared = @iconv('UTF-8', 'CP1251//IGNORE', $value);
  102. if ($prepared === false) {
  103. $prepared = $value; // если iconv не смог – используем как есть
  104. }
  105. // Двойное кодирование base64
  106. return base64_encode(base64_encode($prepared));
  107. }
  108. private function stripNulls(?string $value): ?string
  109. {
  110. return $value === null ? null : rtrim($value, "\0");
  111. }
  112. // Более лояльная проверка base64 (без строгого ===, учитываем отсутствие отступов и символы \r\n)
  113. private function isBase64(string $value): bool
  114. {
  115. if ($value === '') {
  116. return false;
  117. }
  118. // Проверяем набор допустимых символов и кратность 4
  119. if (preg_match('/^[A-Za-z0-9+\/\r\n]+=*$/', $value) !== 1) {
  120. return false;
  121. }
  122. return (strlen($value) % 4 === 0);
  123. }
  124. private function ensureUtf8(string $value): string
  125. {
  126. if ($value === '') {
  127. return '';
  128. }
  129. if (mb_check_encoding($value, 'UTF-8')) {
  130. return $this->removeControlChars($value);
  131. }
  132. $candidates = [];
  133. if (function_exists('iconv')) {
  134. $candidates[] = fn () => @iconv('CP1251', 'UTF-8//IGNORE', $value);
  135. }
  136. if (function_exists('mb_convert_encoding')) {
  137. $candidates[] = fn () => @mb_convert_encoding($value, 'UTF-8', 'CP1251');
  138. $candidates[] = fn () => @mb_convert_encoding($value, 'UTF-8', 'ISO-8859-1');
  139. }
  140. $candidates[] = fn () => utf8_encode($value);
  141. foreach ($candidates as $candidate) {
  142. $converted = $candidate();
  143. if (is_string($converted) && mb_check_encoding($converted, 'UTF-8')) {
  144. return $this->removeControlChars($converted);
  145. }
  146. }
  147. if (function_exists('iconv')) {
  148. $sanitized = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
  149. if (is_string($sanitized) && mb_check_encoding($sanitized, 'UTF-8')) {
  150. return $this->removeControlChars($sanitized);
  151. }
  152. }
  153. return '';
  154. }
  155. private function removeControlChars(string $value): string
  156. {
  157. $clean = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/u', '', $value);
  158. return is_string($clean) ? $clean : '';
  159. }
  160. public function toArray()
  161. {
  162. $array = parent::toArray();
  163. // Явно декодируем бинарные поля, на случай если accessor не сработал при сериализации
  164. if (array_key_exists('binTitle', $this->attributes)) {
  165. $array['binTitle'] = $this->decodeBinaryValue($this->attributes['binTitle']);
  166. } elseif (array_key_exists('binTitle', $array)) {
  167. $array['binTitle'] = $this->decodeBinaryValue($array['binTitle']);
  168. }
  169. if (array_key_exists('binLetter', $this->attributes)) {
  170. $array['binLetter'] = $this->decodeBinaryValue($this->attributes['binLetter']);
  171. } elseif (array_key_exists('binLetter', $array)) {
  172. $array['binLetter'] = $this->decodeBinaryValue($array['binLetter']);
  173. }
  174. array_walk_recursive($array, function (&$v) {
  175. if (is_string($v)) {
  176. $v = $this->ensureUtf8($v);
  177. }
  178. });
  179. return $array;
  180. }
  181. }