CharMail.php 7.4 KB

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