Merge commit 'origin/master' into 310
[AHbot.git] / src / game / CharacterHandler.cpp
blobaac2fdcfa2a70da9d57655ee53dfc4b10d047d5d
1 /*
2 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "Database/DatabaseEnv.h"
21 #include "WorldPacket.h"
22 #include "SharedDefines.h"
23 #include "WorldSession.h"
24 #include "Opcodes.h"
25 #include "Log.h"
26 #include "World.h"
27 #include "ObjectMgr.h"
28 #include "Player.h"
29 #include "Guild.h"
30 #include "UpdateMask.h"
31 #include "Auth/md5.h"
32 #include "ObjectAccessor.h"
33 #include "Group.h"
34 #include "Database/DatabaseImpl.h"
35 #include "PlayerDump.h"
36 #include "SocialMgr.h"
37 #include "Util.h"
38 #include "ArenaTeam.h"
39 #include "Language.h"
41 class LoginQueryHolder : public SqlQueryHolder
43 private:
44 uint32 m_accountId;
45 uint64 m_guid;
46 public:
47 LoginQueryHolder(uint32 accountId, uint64 guid)
48 : m_accountId(accountId), m_guid(guid) { }
49 uint64 GetGuid() const { return m_guid; }
50 uint32 GetAccountId() const { return m_accountId; }
51 bool Initialize();
54 bool LoginQueryHolder::Initialize()
56 SetSize(MAX_PLAYER_LOGIN_QUERY);
58 bool res = true;
60 // NOTE: all fields in `characters` must be read to prevent lost character data at next save in case wrong DB structure.
61 // !!! NOTE: including unused `zone`,`online`
62 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADFROM, "SELECT guid, account, data, name, race, class, position_x, position_y, position_z, map, orientation, taximask, cinematic, totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, online, death_expire_time, taxi_path, dungeon_difficulty, arena_pending_points,bgid,bgteam,bgmap,bgx,bgy,bgz,bgo FROM characters WHERE guid = '%u'", GUID_LOPART(m_guid));
63 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADGROUP, "SELECT leaderGuid FROM group_member WHERE memberGuid ='%u'", GUID_LOPART(m_guid));
64 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES, "SELECT id, permanent, map, difficulty, resettime FROM character_instance LEFT JOIN instance ON instance = id WHERE guid = '%u'", GUID_LOPART(m_guid));
65 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADAURAS, "SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'", GUID_LOPART(m_guid));
66 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADSPELLS, "SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'", GUID_LOPART(m_guid));
67 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS, "SELECT quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4 FROM character_queststatus WHERE guid = '%u'", GUID_LOPART(m_guid));
68 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS,"SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GUID_LOPART(m_guid));
69 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADREPUTATION, "SELECT faction,standing,flags FROM character_reputation WHERE guid = '%u'", GUID_LOPART(m_guid));
70 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADINVENTORY, "SELECT data,bag,slot,item,item_template FROM character_inventory JOIN item_instance ON character_inventory.item = item_instance.guid WHERE character_inventory.guid = '%u' ORDER BY bag,slot", GUID_LOPART(m_guid));
71 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADACTIONS, "SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button", GUID_LOPART(m_guid));
72 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADMAILCOUNT, "SELECT COUNT(id) FROM mail WHERE receiver = '%u' AND (checked & 1)=0 AND deliver_time <= '" I64FMTD "'", GUID_LOPART(m_guid),(uint64)time(NULL));
73 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADMAILDATE, "SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(m_guid));
74 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADSOCIALLIST, "SELECT friend,flags,note FROM character_social WHERE guid = '%u' LIMIT 255", GUID_LOPART(m_guid));
75 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADHOMEBIND, "SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(m_guid));
76 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS, "SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'", GUID_LOPART(m_guid));
77 if(sWorld.getConfig(CONFIG_DECLINED_NAMES_USED))
78 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES, "SELECT genitive, dative, accusative, instrumental, prepositional FROM character_declinedname WHERE guid = '%u'",GUID_LOPART(m_guid));
79 // in other case still be dummy query
80 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADGUILD, "SELECT guildid,rank FROM guild_member WHERE guid = '%u'", GUID_LOPART(m_guid));
81 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADARENAINFO, "SELECT arenateamid, played_week, played_season, personal_rating FROM arena_team_member WHERE guid='%u'", GUID_LOPART(m_guid));
82 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS, "SELECT achievement, date FROM character_achievement WHERE guid = '%u'", GUID_LOPART(m_guid));
83 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS,"SELECT criteria, counter, date FROM character_achievement_progress WHERE guid = '%u'", GUID_LOPART(m_guid));
84 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS, "SELECT setguid, setindex, name, iconname, item0, item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11, item12, item13, item14, item15, item16, item17, item18 FROM character_equipmentsets WHERE guid = '%u' ORDER BY setindex", GUID_LOPART(m_guid));
86 return res;
89 // don't call WorldSession directly
90 // it may get deleted before the query callbacks get executed
91 // instead pass an account id to this handler
92 class CharacterHandler
94 public:
95 void HandleCharEnumCallback(QueryResult * result, uint32 account)
97 WorldSession * session = sWorld.FindSession(account);
98 if(!session)
100 delete result;
101 return;
103 session->HandleCharEnum(result);
105 void HandlePlayerLoginCallback(QueryResult * /*dummy*/, SqlQueryHolder * holder)
107 if (!holder) return;
108 WorldSession *session = sWorld.FindSession(((LoginQueryHolder*)holder)->GetAccountId());
109 if(!session)
111 delete holder;
112 return;
114 session->HandlePlayerLogin((LoginQueryHolder*)holder);
116 } chrHandler;
118 void WorldSession::HandleCharEnum(QueryResult * result)
120 // keys can be non cleared if player open realm list and close it by 'cancel'
121 loginDatabase.PExecute("UPDATE account SET v = '0', s = '0' WHERE id = '%u'", GetAccountId());
123 WorldPacket data(SMSG_CHAR_ENUM, 100); // we guess size
125 uint8 num = 0;
127 data << num;
129 if( result )
131 Player *plr = new Player(this);
134 uint32 guidlow = (*result)[0].GetUInt32();
135 sLog.outDetail("Loading char guid %u from account %u.",guidlow,GetAccountId());
137 if(plr->MinimalLoadFromDB( result, guidlow ))
139 plr->BuildEnumData( result, &data );
140 ++num;
143 while( result->NextRow() );
145 delete plr;
146 delete result;
149 data.put<uint8>(0, num);
151 SendPacket( &data );
154 void WorldSession::HandleCharEnumOpcode( WorldPacket & /*recv_data*/ )
156 /// get all the data necessary for loading all characters (along with their pets) on the account
157 CharacterDatabase.AsyncPQuery(&chrHandler, &CharacterHandler::HandleCharEnumCallback, GetAccountId(),
158 !sWorld.getConfig(CONFIG_DECLINED_NAMES_USED) ?
159 // ------- Query Without Declined Names --------
160 // 0 1 2 3 4 5 6 7 8
161 "SELECT characters.guid, characters.data, characters.name, characters.position_x, characters.position_y, characters.position_z, characters.map, characters.totaltime, characters.leveltime, "
162 // 9 10 11 12 13
163 "characters.at_login, character_pet.entry, character_pet.modelid, character_pet.level, guild_member.guildid "
164 "FROM characters LEFT JOIN character_pet ON characters.guid=character_pet.owner AND character_pet.slot='%u' "
165 "LEFT JOIN guild_member ON characters.guid = guild_member.guid "
166 "WHERE characters.account = '%u' ORDER BY characters.guid"
168 // --------- Query With Declined Names ---------
169 // 0 1 2 3 4 5 6 7 8
170 "SELECT characters.guid, characters.data, characters.name, characters.position_x, characters.position_y, characters.position_z, characters.map, characters.totaltime, characters.leveltime, "
171 // 9 10 11 12 13 14
172 "characters.at_login, character_pet.entry, character_pet.modelid, character_pet.level, guild_member.guildid, genitive "
173 "FROM characters LEFT JOIN character_pet ON characters.guid = character_pet.owner AND character_pet.slot='%u' "
174 "LEFT JOIN character_declinedname ON characters.guid = character_declinedname.guid "
175 "LEFT JOIN guild_member ON characters.guid = guild_member.guid "
176 "WHERE characters.account = '%u' ORDER BY characters.guid",
177 PET_SAVE_AS_CURRENT,GetAccountId());
180 void WorldSession::HandleCharCreateOpcode( WorldPacket & recv_data )
182 CHECK_PACKET_SIZE(recv_data,1+1+1+1+1+1+1+1+1+1);
184 std::string name;
185 uint8 race_,class_;
187 recv_data >> name;
189 // recheck with known string size
190 CHECK_PACKET_SIZE(recv_data,(name.size()+1)+1+1+1+1+1+1+1+1+1);
192 recv_data >> race_;
193 recv_data >> class_;
195 WorldPacket data(SMSG_CHAR_CREATE, 1); // returned with diff.values in all cases
197 if(GetSecurity() == SEC_PLAYER)
199 if(uint32 mask = sWorld.getConfig(CONFIG_CHARACTERS_CREATING_DISABLED))
201 bool disabled = false;
203 uint32 team = Player::TeamForRace(race_);
204 switch(team)
206 case ALLIANCE: disabled = mask & (1<<0); break;
207 case HORDE: disabled = mask & (1<<1); break;
210 if(disabled)
212 data << (uint8)CHAR_CREATE_DISABLED;
213 SendPacket( &data );
214 return;
219 ChrClassesEntry const* classEntry = sChrClassesStore.LookupEntry(class_);
220 ChrRacesEntry const* raceEntry = sChrRacesStore.LookupEntry(race_);
222 if( !classEntry || !raceEntry )
224 data << (uint8)CHAR_CREATE_FAILED;
225 SendPacket( &data );
226 sLog.outError("Class: %u or Race %u not found in DBC (Wrong DBC files?) or Cheater?", class_, race_);
227 return;
230 // prevent character creating Expansion race without Expansion account
231 if (raceEntry->addon > Expansion())
233 data << (uint8)CHAR_CREATE_EXPANSION;
234 sLog.outError("Expansion %u account:[%d] tried to Create character with expansion %u race (%u)",Expansion(),GetAccountId(),raceEntry->addon,race_);
235 SendPacket( &data );
236 return;
239 // prevent character creating Expansion class without Expansion account
240 if (classEntry->addon > Expansion())
242 data << (uint8)CHAR_CREATE_EXPANSION_CLASS;
243 sLog.outError("Expansion %u account:[%d] tried to Create character with expansion %u class (%u)",Expansion(),GetAccountId(),classEntry->addon,class_);
244 SendPacket( &data );
245 return;
248 // prevent character creating with invalid name
249 if(!normalizePlayerName(name))
251 data << (uint8)CHAR_NAME_INVALID_CHARACTER;
252 SendPacket( &data );
253 sLog.outError("Account:[%d] but tried to Create character with empty [name] ",GetAccountId());
254 return;
257 // check name limitations
258 if(!ObjectMgr::IsValidName(name,true))
260 data << (uint8)CHAR_NAME_INVALID_CHARACTER;
261 SendPacket( &data );
262 return;
265 if(GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(name))
267 data << (uint8)CHAR_NAME_RESERVED;
268 SendPacket( &data );
269 return;
272 if(objmgr.GetPlayerGUIDByName(name))
274 data << (uint8)CHAR_CREATE_NAME_IN_USE;
275 SendPacket( &data );
276 return;
279 QueryResult *resultacct = loginDatabase.PQuery("SELECT SUM(numchars) FROM realmcharacters WHERE acctid = '%d'", GetAccountId());
280 if ( resultacct )
282 Field *fields=resultacct->Fetch();
283 uint32 acctcharcount = fields[0].GetUInt32();
284 delete resultacct;
286 if (acctcharcount >= sWorld.getConfig(CONFIG_CHARACTERS_PER_ACCOUNT))
288 data << (uint8)CHAR_CREATE_ACCOUNT_LIMIT;
289 SendPacket( &data );
290 return;
294 QueryResult *result = CharacterDatabase.PQuery("SELECT COUNT(guid) FROM characters WHERE account = '%d'", GetAccountId());
295 uint8 charcount = 0;
296 if ( result )
298 Field *fields=result->Fetch();
299 charcount = fields[0].GetUInt8();
300 delete result;
302 if (charcount >= sWorld.getConfig(CONFIG_CHARACTERS_PER_REALM))
304 data << (uint8)CHAR_CREATE_SERVER_LIMIT;
305 SendPacket( &data );
306 return;
310 // speedup check for heroic class disabled case
311 uint32 heroic_free_slots = sWorld.getConfig(CONFIG_HEROIC_CHARACTERS_PER_REALM);
312 if(heroic_free_slots==0 && GetSecurity()==SEC_PLAYER && class_ == CLASS_DEATH_KNIGHT)
314 data << (uint8)CHAR_CREATE_UNIQUE_CLASS_LIMIT;
315 SendPacket( &data );
316 return;
319 // speedup check for heroic class disabled case
320 uint32 req_level_for_heroic = sWorld.getConfig(CONFIG_MIN_LEVEL_FOR_HEROIC_CHARACTER_CREATING);
321 if(GetSecurity()==SEC_PLAYER && class_ == CLASS_DEATH_KNIGHT && req_level_for_heroic > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
323 data << (uint8)CHAR_CREATE_LEVEL_REQUIREMENT;
324 SendPacket( &data );
325 return;
328 bool AllowTwoSideAccounts = !sWorld.IsPvPRealm() || sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_ACCOUNTS) || GetSecurity() > SEC_PLAYER;
329 uint32 skipCinematics = sWorld.getConfig(CONFIG_SKIP_CINEMATICS);
331 bool have_same_race = false;
333 // if 0 then allowed creating without any characters
334 bool have_req_level_for_heroic = (req_level_for_heroic==0);
336 if(!AllowTwoSideAccounts || skipCinematics == 1 || class_ == CLASS_DEATH_KNIGHT)
338 QueryResult *result2 = CharacterDatabase.PQuery("SELECT guid,race,class FROM characters WHERE account = '%u' %s",
339 GetAccountId(), (skipCinematics == 1 || class_ == CLASS_DEATH_KNIGHT) ? "" : "LIMIT 1");
340 if(result2)
342 uint32 team_= Player::TeamForRace(race_);
344 Field* field = result2->Fetch();
345 uint8 acc_race = field[1].GetUInt32();
347 if(GetSecurity()==SEC_PLAYER && class_ == CLASS_DEATH_KNIGHT)
349 uint8 acc_class = field[2].GetUInt32();
350 if(acc_class == CLASS_DEATH_KNIGHT)
352 if(heroic_free_slots > 0)
353 --heroic_free_slots;
355 if(heroic_free_slots==0)
357 data << (uint8)CHAR_CREATE_UNIQUE_CLASS_LIMIT;
358 SendPacket( &data );
359 return;
363 if(!have_req_level_for_heroic)
365 uint32 acc_guid = field[0].GetUInt32();
366 uint32 acc_level = Player::GetUInt32ValueFromDB(UNIT_FIELD_LEVEL,acc_guid);
367 if(acc_level >= req_level_for_heroic)
368 have_req_level_for_heroic = true;
372 // need to check team only for first character
373 // TODO: what to if account already has characters of both races?
374 if (!AllowTwoSideAccounts)
376 uint32 acc_team=0;
377 if(acc_race > 0)
378 acc_team = Player::TeamForRace(acc_race);
380 if(acc_team != team_)
382 data << (uint8)CHAR_CREATE_PVP_TEAMS_VIOLATION;
383 SendPacket( &data );
384 delete result2;
385 return;
389 // search same race for cinematic or same class if need
390 // TODO: check if cinematic already shown? (already logged in?; cinematic field)
391 while ((skipCinematics == 1 && !have_same_race) || class_ == CLASS_DEATH_KNIGHT)
393 if(!result2->NextRow())
394 break;
396 field = result2->Fetch();
397 acc_race = field[1].GetUInt32();
399 if(!have_same_race)
400 have_same_race = race_ == acc_race;
402 if(GetSecurity()==SEC_PLAYER && class_ == CLASS_DEATH_KNIGHT)
404 uint8 acc_class = field[2].GetUInt32();
405 if(acc_class == CLASS_DEATH_KNIGHT)
407 if(heroic_free_slots > 0)
408 --heroic_free_slots;
410 if(heroic_free_slots==0)
412 data << (uint8)CHAR_CREATE_UNIQUE_CLASS_LIMIT;
413 SendPacket( &data );
414 return;
418 if(!have_req_level_for_heroic)
420 uint32 acc_guid = field[0].GetUInt32();
421 uint32 acc_level = Player::GetUInt32ValueFromDB(UNIT_FIELD_LEVEL,acc_guid);
422 if(acc_level >= req_level_for_heroic)
423 have_req_level_for_heroic = true;
427 delete result2;
431 if(GetSecurity()==SEC_PLAYER && class_ == CLASS_DEATH_KNIGHT && !have_req_level_for_heroic)
433 data << (uint8)CHAR_CREATE_LEVEL_REQUIREMENT;
434 SendPacket( &data );
435 return;
438 // extract other data required for player creating
439 uint8 gender, skin, face, hairStyle, hairColor, facialHair, outfitId;
440 recv_data >> gender >> skin >> face;
441 recv_data >> hairStyle >> hairColor >> facialHair >> outfitId;
443 Player * pNewChar = new Player(this);
444 if(!pNewChar->Create( objmgr.GenerateLowGuid(HIGHGUID_PLAYER), name, race_, class_, gender, skin, face, hairStyle, hairColor, facialHair, outfitId ))
446 // Player not create (race/class problem?)
447 delete pNewChar;
449 data << (uint8)CHAR_CREATE_ERROR;
450 SendPacket( &data );
452 return;
455 if ((have_same_race && skipCinematics == 1) || skipCinematics == 2)
456 pNewChar->setCinematic(1); // not show intro
458 // Player created, save it now
459 pNewChar->SaveToDB();
460 charcount+=1;
462 loginDatabase.PExecute("DELETE FROM realmcharacters WHERE acctid= '%d' AND realmid = '%d'", GetAccountId(), realmID);
463 loginDatabase.PExecute("INSERT INTO realmcharacters (numchars, acctid, realmid) VALUES (%u, %u, %u)", charcount, GetAccountId(), realmID);
465 delete pNewChar; // created only to call SaveToDB()
467 data << (uint8)CHAR_CREATE_SUCCESS;
468 SendPacket( &data );
470 std::string IP_str = GetRemoteAddress();
471 sLog.outBasic("Account: %d (IP: %s) Create Character:[%s]",GetAccountId(),IP_str.c_str(),name.c_str());
472 sLog.outChar("Account: %d (IP: %s) Create Character:[%s]",GetAccountId(),IP_str.c_str(),name.c_str());
475 void WorldSession::HandleCharDeleteOpcode( WorldPacket & recv_data )
477 CHECK_PACKET_SIZE(recv_data,8);
479 uint64 guid;
480 recv_data >> guid;
482 // can't delete loaded character
483 if(objmgr.GetPlayer(guid))
484 return;
486 uint32 accountId = 0;
487 std::string name;
489 // is guild leader
490 if(objmgr.GetGuildByLeader(guid))
492 WorldPacket data(SMSG_CHAR_DELETE, 1);
493 data << (uint8)CHAR_DELETE_FAILED_GUILD_LEADER;
494 SendPacket( &data );
495 return;
498 // is arena team captain
499 if(objmgr.GetArenaTeamByCaptain(guid))
501 WorldPacket data(SMSG_CHAR_DELETE, 1);
502 data << (uint8)CHAR_DELETE_FAILED_ARENA_CAPTAIN;
503 SendPacket( &data );
504 return;
507 QueryResult *result = CharacterDatabase.PQuery("SELECT account,name FROM characters WHERE guid='%u'", GUID_LOPART(guid));
508 if(result)
510 Field *fields = result->Fetch();
511 accountId = fields[0].GetUInt32();
512 name = fields[1].GetCppString();
513 delete result;
516 // prevent deleting other players' characters using cheating tools
517 if(accountId != GetAccountId())
518 return;
520 std::string IP_str = GetRemoteAddress();
521 sLog.outBasic("Account: %d (IP: %s) Delete Character:[%s] (guid: %u)",GetAccountId(),IP_str.c_str(),name.c_str(),GUID_LOPART(guid));
522 sLog.outChar("Account: %d (IP: %s) Delete Character:[%s] (guid: %u)",GetAccountId(),IP_str.c_str(),name.c_str(),GUID_LOPART(guid));
524 if(sLog.IsOutCharDump()) // optimize GetPlayerDump call
526 std::string dump = PlayerDumpWriter().GetDump(GUID_LOPART(guid));
527 sLog.outCharDump(dump.c_str(),GetAccountId(),GUID_LOPART(guid),name.c_str());
530 Player::DeleteFromDB(guid, GetAccountId());
532 WorldPacket data(SMSG_CHAR_DELETE, 1);
533 data << (uint8)CHAR_DELETE_SUCCESS;
534 SendPacket( &data );
537 void WorldSession::HandlePlayerLoginOpcode( WorldPacket & recv_data )
539 CHECK_PACKET_SIZE(recv_data,8);
541 if(PlayerLoading() || GetPlayer() != NULL)
543 sLog.outError("Player tryes to login again, AccountId = %d",GetAccountId());
544 return;
547 m_playerLoading = true;
548 uint64 playerGuid = 0;
550 DEBUG_LOG( "WORLD: Recvd Player Logon Message" );
552 recv_data >> playerGuid;
554 LoginQueryHolder *holder = new LoginQueryHolder(GetAccountId(), playerGuid);
555 if(!holder->Initialize())
557 delete holder; // delete all unprocessed queries
558 m_playerLoading = false;
559 return;
562 CharacterDatabase.DelayQueryHolder(&chrHandler, &CharacterHandler::HandlePlayerLoginCallback, holder);
565 void WorldSession::HandlePlayerLogin(LoginQueryHolder * holder)
567 uint64 playerGuid = holder->GetGuid();
569 Player* pCurrChar = new Player(this);
570 pCurrChar->GetMotionMaster()->Initialize();
572 // "GetAccountId()==db stored account id" checked in LoadFromDB (prevent login not own character using cheating tools)
573 if(!pCurrChar->LoadFromDB(GUID_LOPART(playerGuid), holder))
575 KickPlayer(); // disconnect client, player no set to session and it will not deleted or saved at kick
576 delete pCurrChar; // delete it manually
577 delete holder; // delete all unprocessed queries
578 m_playerLoading = false;
579 return;
582 SetPlayer(pCurrChar);
584 pCurrChar->SendDungeonDifficulty(false);
586 WorldPacket data( SMSG_LOGIN_VERIFY_WORLD, 20 );
587 data << pCurrChar->GetMapId();
588 data << pCurrChar->GetPositionX();
589 data << pCurrChar->GetPositionY();
590 data << pCurrChar->GetPositionZ();
591 data << pCurrChar->GetOrientation();
592 SendPacket(&data);
594 data.Initialize( SMSG_ACCOUNT_DATA_TIMES, 4+1+8*4 ); // changed in WotLK
595 data << uint32(time(NULL)); // unix time of something
596 data << uint8(1);
597 for(int i = 0; i < NUM_ACCOUNT_DATA_TYPES; ++i)
598 data << uint32(GetAccountData(i)->Time); // also unix time
599 SendPacket(&data);
601 data.Initialize(SMSG_FEATURE_SYSTEM_STATUS, 2); // added in 2.2.0
602 data << uint8(2); // unknown value
603 data << uint8(0); // enable(1)/disable(0) voice chat interface in client
604 SendPacket(&data);
606 // Send MOTD
608 data.Initialize(SMSG_MOTD, 50); // new in 2.0.1
609 data << (uint32)0;
611 uint32 linecount=0;
612 std::string str_motd = sWorld.GetMotd();
613 std::string::size_type pos, nextpos;
615 pos = 0;
616 while ( (nextpos= str_motd.find('@',pos)) != std::string::npos )
618 if (nextpos != pos)
620 data << str_motd.substr(pos,nextpos-pos);
621 ++linecount;
623 pos = nextpos+1;
626 if (pos<str_motd.length())
628 data << str_motd.substr(pos);
629 ++linecount;
632 data.put(0, linecount);
634 SendPacket( &data );
635 DEBUG_LOG( "WORLD: Sent motd (SMSG_MOTD)" );
638 data.Initialize(SMSG_LEARNED_DANCE_MOVES, 4+4);
639 data << uint32(0);
640 data << uint32(0);
641 SendPacket(&data);
643 //QueryResult *result = CharacterDatabase.PQuery("SELECT guildid,rank FROM guild_member WHERE guid = '%u'",pCurrChar->GetGUIDLow());
644 QueryResult *resultGuild = holder->GetResult(PLAYER_LOGIN_QUERY_LOADGUILD);
646 if(resultGuild)
648 Field *fields = resultGuild->Fetch();
649 pCurrChar->SetInGuild(fields[0].GetUInt32());
650 pCurrChar->SetRank(fields[1].GetUInt32());
651 delete resultGuild;
653 else if(pCurrChar->GetGuildId()) // clear guild related fields in case wrong data about non existed membership
655 pCurrChar->SetInGuild(0);
656 pCurrChar->SetRank(0);
659 if(pCurrChar->GetGuildId() != 0)
661 Guild* guild = objmgr.GetGuildById(pCurrChar->GetGuildId());
662 if(guild)
664 data.Initialize(SMSG_GUILD_EVENT, (2+guild->GetMOTD().size()+1));
665 data << (uint8)GE_MOTD;
666 data << (uint8)1;
667 data << guild->GetMOTD();
668 SendPacket(&data);
669 DEBUG_LOG( "WORLD: Sent guild-motd (SMSG_GUILD_EVENT)" );
671 data.Initialize(SMSG_GUILD_EVENT, (5+10)); // we guess size
672 data<<(uint8)GE_SIGNED_ON;
673 data<<(uint8)1;
674 data<<pCurrChar->GetName();
675 data<<pCurrChar->GetGUID();
676 guild->BroadcastPacket(&data);
677 DEBUG_LOG( "WORLD: Sent guild-signed-on (SMSG_GUILD_EVENT)" );
679 // Increment online members of the guild
680 guild->IncOnlineMemberCount();
682 else
684 // remove wrong guild data
685 sLog.outError("Player %s (GUID: %u) marked as member not existed guild (id: %u), removing guild membership for player.",pCurrChar->GetName(),pCurrChar->GetGUIDLow(),pCurrChar->GetGuildId());
686 pCurrChar->SetInGuild(0);
690 if(!pCurrChar->isAlive())
691 pCurrChar->SendCorpseReclaimDelay(true);
693 pCurrChar->SendInitialPacketsBeforeAddToMap();
695 //Show cinematic at the first time that player login
696 if( !pCurrChar->getCinematic() )
698 pCurrChar->setCinematic(1);
700 if(ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(pCurrChar->getClass()))
702 if (cEntry->CinematicSequence)
703 pCurrChar->SendCinematicStart(cEntry->CinematicSequence);
704 else if (ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(pCurrChar->getRace()))
705 pCurrChar->SendCinematicStart(rEntry->CinematicSequence);
709 if (!pCurrChar->GetMap()->Add(pCurrChar))
711 AreaTrigger const* at = objmgr.GetGoBackTrigger(pCurrChar->GetMapId());
712 if(at)
713 pCurrChar->TeleportTo(at->target_mapId, at->target_X, at->target_Y, at->target_Z, pCurrChar->GetOrientation());
714 else
715 pCurrChar->TeleportTo(pCurrChar->m_homebindMapId, pCurrChar->m_homebindX, pCurrChar->m_homebindY, pCurrChar->m_homebindZ, pCurrChar->GetOrientation());
718 ObjectAccessor::Instance().AddObject(pCurrChar);
719 //sLog.outDebug("Player %s added to Map.",pCurrChar->GetName());
721 pCurrChar->SendInitialPacketsAfterAddToMap();
723 CharacterDatabase.PExecute("UPDATE characters SET online = 1 WHERE guid = '%u'", pCurrChar->GetGUIDLow());
724 loginDatabase.PExecute("UPDATE account SET online = 1 WHERE id = '%u'", GetAccountId());
725 pCurrChar->SetInGameTime( getMSTime() );
727 // announce group about member online (must be after add to player list to receive announce to self)
728 if(Group *group = pCurrChar->GetGroup())
730 //pCurrChar->groupInfo.group->SendInit(this); // useless
731 group->SendUpdate();
734 // friend status
735 sSocialMgr.SendFriendStatus(pCurrChar, FRIEND_ONLINE, pCurrChar->GetGUIDLow(), true);
737 // Place character in world (and load zone) before some object loading
738 pCurrChar->LoadCorpse();
740 // setting Ghost+speed if dead
741 if (pCurrChar->m_deathState != ALIVE)
743 // not blizz like, we must correctly save and load player instead...
744 if(pCurrChar->getRace() == RACE_NIGHTELF)
745 pCurrChar->CastSpell(pCurrChar, 20584, true, 0);// auras SPELL_AURA_INCREASE_SPEED(+speed in wisp form), SPELL_AURA_INCREASE_SWIM_SPEED(+swim speed in wisp form), SPELL_AURA_TRANSFORM (to wisp form)
746 pCurrChar->CastSpell(pCurrChar, 8326, true, 0); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
748 pCurrChar->SetMovement(MOVE_WATER_WALK);
751 if(uint32 sourceNode = pCurrChar->m_taxi.GetTaxiSource())
753 sLog.outDebug( "WORLD: Restart character %u taxi flight", pCurrChar->GetGUIDLow() );
755 uint32 MountId = objmgr.GetTaxiMount(sourceNode, pCurrChar->GetTeam(),true);
756 uint32 path = pCurrChar->m_taxi.GetCurrentTaxiPath();
758 // search appropriate start path node
759 uint32 startNode = 0;
761 TaxiPathNodeList const& nodeList = sTaxiPathNodesByPath[path];
763 float distPrev = MAP_SIZE*MAP_SIZE;
764 float distNext =
765 (nodeList[0].x-pCurrChar->GetPositionX())*(nodeList[0].x-pCurrChar->GetPositionX())+
766 (nodeList[0].y-pCurrChar->GetPositionY())*(nodeList[0].y-pCurrChar->GetPositionY())+
767 (nodeList[0].z-pCurrChar->GetPositionZ())*(nodeList[0].z-pCurrChar->GetPositionZ());
769 for(uint32 i = 1; i < nodeList.size(); ++i)
771 TaxiPathNode const& node = nodeList[i];
772 TaxiPathNode const& prevNode = nodeList[i-1];
774 // skip nodes at another map
775 if(node.mapid != pCurrChar->GetMapId())
776 continue;
778 distPrev = distNext;
780 distNext =
781 (node.x-pCurrChar->GetPositionX())*(node.x-pCurrChar->GetPositionX())+
782 (node.y-pCurrChar->GetPositionY())*(node.y-pCurrChar->GetPositionY())+
783 (node.z-pCurrChar->GetPositionZ())*(node.z-pCurrChar->GetPositionZ());
785 float distNodes =
786 (node.x-prevNode.x)*(node.x-prevNode.x)+
787 (node.y-prevNode.y)*(node.y-prevNode.y)+
788 (node.z-prevNode.z)*(node.z-prevNode.z);
790 if(distNext + distPrev < distNodes)
792 startNode = i;
793 break;
797 SendDoFlight( MountId, path, startNode );
800 // Load pet if any (if player not alive and in taxi flight or another then pet will remember as temporary unsummoned)
801 pCurrChar->LoadPet();
803 // Set FFA PvP for non GM in non-rest mode
804 if(sWorld.IsFFAPvPRealm() && !pCurrChar->isGameMaster() && !pCurrChar->HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_RESTING) )
805 pCurrChar->SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
807 if(pCurrChar->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP))
808 pCurrChar->SetContestedPvP();
810 // Apply at_login requests
811 if(pCurrChar->HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
813 pCurrChar->resetSpells();
814 SendNotification(LANG_RESET_SPELLS);
817 if(pCurrChar->HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
819 pCurrChar->resetTalents(true);
820 SendNotification(LANG_RESET_TALENTS);
823 // show time before shutdown if shutdown planned.
824 if(sWorld.IsShutdowning())
825 sWorld.ShutdownMsg(true,pCurrChar);
827 if(sWorld.getConfig(CONFIG_ALL_TAXI_PATHS))
828 pCurrChar->SetTaxiCheater(true);
830 if(pCurrChar->isGameMaster())
831 SendNotification(LANG_GM_ON);
833 std::string IP_str = GetRemoteAddress();
834 sLog.outChar("Account: %d (IP: %s) Login Character:[%s] (guid:%u)",
835 GetAccountId(),IP_str.c_str(),pCurrChar->GetName() ,pCurrChar->GetGUIDLow());
837 m_playerLoading = false;
838 delete holder;
841 void WorldSession::HandleSetFactionAtWar( WorldPacket & recv_data )
843 CHECK_PACKET_SIZE(recv_data,4+1);
845 DEBUG_LOG( "WORLD: Received CMSG_SET_FACTION_ATWAR" );
847 uint32 repListID;
848 uint8 flag;
850 recv_data >> repListID;
851 recv_data >> flag;
853 GetPlayer()->GetReputationMgr().SetAtWar(repListID,flag);
856 //I think this function is never used :/ I dunno, but i guess this opcode not exists
857 void WorldSession::HandleSetFactionCheat( WorldPacket & /*recv_data*/ )
859 //CHECK_PACKET_SIZE(recv_data,4+4);
861 sLog.outError("WORLD SESSION: HandleSetFactionCheat, not expected call, please report.");
863 uint32 FactionID;
864 uint32 Standing;
866 recv_data >> FactionID;
867 recv_data >> Standing;
869 std::list<struct Factions>::iterator itr;
871 for(itr = GetPlayer()->factions.begin(); itr != GetPlayer()->factions.end(); ++itr)
873 if(itr->ReputationListID == FactionID)
875 itr->Standing += Standing;
876 itr->Flags = (itr->Flags | 1);
877 break;
881 GetPlayer()->GetReputationMgr().SendStates();
884 void WorldSession::HandleMeetingStoneInfo( WorldPacket & /*recv_data*/ )
886 DEBUG_LOG( "WORLD: Received CMSG_MEETING_STONE_INFO" );
888 WorldPacket data(SMSG_MEETINGSTONE_SETQUEUE, 5);
889 data << uint32(0) << uint8(6);
890 SendPacket(&data);
893 void WorldSession::HandleTutorialFlag( WorldPacket & recv_data )
895 CHECK_PACKET_SIZE(recv_data,4);
897 uint32 iFlag;
898 recv_data >> iFlag;
900 uint32 wInt = (iFlag / 32);
901 if (wInt >= 8)
903 //sLog.outError("CHEATER? Account:[%d] Guid[%u] tried to send wrong CMSG_TUTORIAL_FLAG", GetAccountId(),GetGUID());
904 return;
906 uint32 rInt = (iFlag % 32);
908 uint32 tutflag = GetTutorialInt( wInt );
909 tutflag |= (1 << rInt);
910 SetTutorialInt( wInt, tutflag );
912 //sLog.outDebug("Received Tutorial Flag Set {%u}.", iFlag);
915 void WorldSession::HandleTutorialClear( WorldPacket & /*recv_data*/ )
917 for (int i = 0; i < 8; ++i)
918 SetTutorialInt( i, 0xFFFFFFFF );
921 void WorldSession::HandleTutorialReset( WorldPacket & /*recv_data*/ )
923 for (int i = 0; i < 8; ++i)
924 SetTutorialInt( i, 0x00000000 );
927 void WorldSession::HandleSetWatchedFactionIndexOpcode(WorldPacket & recv_data)
929 CHECK_PACKET_SIZE(recv_data,4);
931 DEBUG_LOG("WORLD: Received CMSG_SET_WATCHED_FACTION");
932 uint32 fact;
933 recv_data >> fact;
934 GetPlayer()->SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, fact);
937 void WorldSession::HandleSetWatchedFactionInactiveOpcode(WorldPacket & recv_data)
939 CHECK_PACKET_SIZE(recv_data,4+1);
941 DEBUG_LOG("WORLD: Received CMSG_SET_FACTION_INACTIVE");
942 uint32 replistid;
943 uint8 inactive;
944 recv_data >> replistid >> inactive;
946 _player->GetReputationMgr().SetInactive(replistid, inactive);
949 void WorldSession::HandleToggleHelmOpcode( WorldPacket & /*recv_data*/ )
951 DEBUG_LOG("CMSG_TOGGLE_HELM for %s", _player->GetName());
952 _player->ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM);
955 void WorldSession::HandleToggleCloakOpcode( WorldPacket & /*recv_data*/ )
957 DEBUG_LOG("CMSG_TOGGLE_CLOAK for %s", _player->GetName());
958 _player->ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK);
961 void WorldSession::HandleChangePlayerNameOpcode(WorldPacket& recv_data)
963 CHECK_PACKET_SIZE(recv_data, 8+1);
965 uint64 guid;
966 std::string newname;
968 recv_data >> guid;
969 recv_data >> newname;
971 // prevent character rename to invalid name
972 if(!normalizePlayerName(newname))
974 WorldPacket data(SMSG_CHAR_RENAME, 1);
975 data << uint8(CHAR_NAME_NO_NAME);
976 SendPacket( &data );
977 return;
980 if(!ObjectMgr::IsValidName(newname, true))
982 WorldPacket data(SMSG_CHAR_RENAME, 1);
983 data << uint8(CHAR_NAME_INVALID_CHARACTER);
984 SendPacket( &data );
985 return;
988 // check name limitations
989 if(GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(newname))
991 WorldPacket data(SMSG_CHAR_RENAME, 1);
992 data << uint8(CHAR_NAME_RESERVED);
993 SendPacket( &data );
994 return;
997 std::string escaped_newname = newname;
998 CharacterDatabase.escape_string(escaped_newname);
1000 // make sure that the character belongs to the current account, that rename at login is enabled
1001 // and that there is no character with the desired new name
1002 CharacterDatabase.AsyncPQuery(&WorldSession::HandleChangePlayerNameOpcodeCallBack,
1003 GetAccountId(), newname,
1004 "SELECT guid, name FROM characters WHERE guid = %d AND account = %d AND (at_login & %d) = %d AND NOT EXISTS (SELECT NULL FROM characters WHERE name = '%s')",
1005 GUID_LOPART(guid), GetAccountId(), AT_LOGIN_RENAME, AT_LOGIN_RENAME, escaped_newname.c_str()
1009 void WorldSession::HandleChangePlayerNameOpcodeCallBack(QueryResult *result, uint32 accountId, std::string newname)
1011 WorldSession * session = sWorld.FindSession(accountId);
1012 if(!session)
1014 if(result) delete result;
1015 return;
1018 if (!result)
1020 WorldPacket data(SMSG_CHAR_RENAME, 1);
1021 data << uint8(CHAR_CREATE_ERROR);
1022 session->SendPacket( &data );
1023 return;
1026 uint32 guidLow = result->Fetch()[0].GetUInt32();
1027 uint64 guid = MAKE_NEW_GUID(guidLow, 0, HIGHGUID_PLAYER);
1028 std::string oldname = result->Fetch()[1].GetCppString();
1030 delete result;
1032 CharacterDatabase.PExecute("UPDATE characters set name = '%s', at_login = at_login & ~ %u WHERE guid ='%u'", newname.c_str(), uint32(AT_LOGIN_RENAME), guidLow);
1033 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid ='%u'", guidLow);
1035 sLog.outChar("Account: %d (IP: %s) Character:[%s] (guid:%u) Changed name to: %s", session->GetAccountId(), session->GetRemoteAddress().c_str(), oldname.c_str(), guidLow, newname.c_str());
1037 WorldPacket data(SMSG_CHAR_RENAME, 1+8+(newname.size()+1));
1038 data << uint8(RESPONSE_SUCCESS);
1039 data << uint64(guid);
1040 data << newname;
1041 session->SendPacket(&data);
1044 void WorldSession::HandleDeclinedPlayerNameOpcode(WorldPacket& recv_data)
1046 uint64 guid;
1048 CHECK_PACKET_SIZE(recv_data, 8);
1049 recv_data >> guid;
1051 // not accept declined names for unsupported languages
1052 std::string name;
1053 if(!objmgr.GetPlayerNameByGUID(guid, name))
1055 WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8);
1056 data << uint32(1);
1057 data << uint64(guid);
1058 SendPacket(&data);
1059 return;
1062 std::wstring wname;
1063 if(!Utf8toWStr(name, wname))
1065 WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8);
1066 data << uint32(1);
1067 data << uint64(guid);
1068 SendPacket(&data);
1069 return;
1072 if(!isCyrillicCharacter(wname[0])) // name already stored as only single alphabet using
1074 WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8);
1075 data << uint32(1);
1076 data << uint64(guid);
1077 SendPacket(&data);
1078 return;
1081 std::string name2;
1082 DeclinedName declinedname;
1084 CHECK_PACKET_SIZE(recv_data, recv_data.rpos() + 1);
1085 recv_data >> name2;
1087 if(name2 != name) // character have different name
1089 WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8);
1090 data << uint32(1);
1091 data << uint64(guid);
1092 SendPacket(&data);
1093 return;
1096 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
1098 CHECK_PACKET_SIZE(recv_data, recv_data.rpos() + 1);
1099 recv_data >> declinedname.name[i];
1100 if(!normalizePlayerName(declinedname.name[i]))
1102 WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8);
1103 data << uint32(1);
1104 data << uint64(guid);
1105 SendPacket(&data);
1106 return;
1110 if(!ObjectMgr::CheckDeclinedNames(GetMainPartOfName(wname, 0), declinedname))
1112 WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8);
1113 data << uint32(1);
1114 data << uint64(guid);
1115 SendPacket(&data);
1116 return;
1119 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
1120 CharacterDatabase.escape_string(declinedname.name[i]);
1122 CharacterDatabase.BeginTransaction();
1123 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'", GUID_LOPART(guid));
1124 CharacterDatabase.PExecute("INSERT INTO character_declinedname (guid, genitive, dative, accusative, instrumental, prepositional) VALUES ('%u','%s','%s','%s','%s','%s')",
1125 GUID_LOPART(guid), declinedname.name[0].c_str(), declinedname.name[1].c_str(), declinedname.name[2].c_str(), declinedname.name[3].c_str(), declinedname.name[4].c_str());
1126 CharacterDatabase.CommitTransaction();
1128 WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8);
1129 data << uint32(0); // OK
1130 data << uint64(guid);
1131 SendPacket(&data);
1134 void WorldSession::HandleAlterAppearance( WorldPacket & recv_data )
1136 sLog.outDebug("CMSG_ALTER_APPEARANCE");
1138 CHECK_PACKET_SIZE(recv_data, 4+4+4);
1140 uint32 Hair, Color, FacialHair;
1141 recv_data >> Hair >> Color >> FacialHair;
1143 BarberShopStyleEntry const* bs_hair = sBarberShopStyleStore.LookupEntry(Hair);
1145 if(!bs_hair || bs_hair->type != 0 || bs_hair->race != _player->getRace() || bs_hair->gender != _player->getGender())
1146 return;
1148 BarberShopStyleEntry const* bs_facialHair = sBarberShopStyleStore.LookupEntry(FacialHair);
1150 if(!bs_facialHair || bs_facialHair->type != 2 || bs_facialHair->race != _player->getRace() || bs_facialHair->gender != _player->getGender())
1151 return;
1153 uint32 Cost = _player->GetBarberShopCost(bs_hair->hair_id, Color, bs_facialHair->hair_id);
1155 // 0 - ok
1156 // 1,3 - not enough money
1157 // 2 - you have to seat on barber chair
1158 if(_player->GetMoney() < Cost)
1160 WorldPacket data(SMSG_BARBER_SHOP_RESULT, 4);
1161 data << uint32(1); // no money
1162 SendPacket(&data);
1163 return;
1165 else
1167 WorldPacket data(SMSG_BARBER_SHOP_RESULT, 4);
1168 data << uint32(0); // ok
1169 SendPacket(&data);
1172 _player->ModifyMoney(-int32(Cost)); // it isn't free
1173 _player->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_AT_BARBER, Cost);
1175 _player->SetByteValue(PLAYER_BYTES, 2, uint8(bs_hair->hair_id));
1176 _player->SetByteValue(PLAYER_BYTES, 3, uint8(Color));
1177 _player->SetByteValue(PLAYER_BYTES_2, 0, uint8(bs_facialHair->hair_id));
1179 _player->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_VISIT_BARBER_SHOP, 1);
1181 _player->SetStandState(0); // stand up
1184 void WorldSession::HandleRemoveGlyph( WorldPacket & recv_data )
1186 CHECK_PACKET_SIZE(recv_data, 4);
1188 uint32 slot;
1189 recv_data >> slot;
1191 if(slot >= MAX_GLYPH_SLOT_INDEX)
1193 sLog.outDebug("Client sent wrong glyph slot number in opcode CMSG_REMOVE_GLYPH %u", slot);
1194 return;
1197 if(uint32 glyph = _player->GetGlyph(slot))
1199 if(GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph))
1201 _player->RemoveAurasDueToSpell(gp->SpellId);
1202 _player->SetGlyph(slot, 0);
1203 _player->SendTalentsInfoData(false);
1208 void WorldSession::HandleCharCustomize(WorldPacket& recv_data)
1210 CHECK_PACKET_SIZE(recv_data, 8+1);
1212 uint64 guid;
1213 std::string newname;
1215 recv_data >> guid;
1216 recv_data >> newname;
1218 CHECK_PACKET_SIZE(recv_data, recv_data.rpos()+1+1+1+1+1+1);
1220 uint8 gender, skin, face, hairStyle, hairColor, facialHair;
1221 recv_data >> gender >> skin >> hairColor >> hairStyle >> facialHair >> face;
1223 QueryResult *result = CharacterDatabase.PQuery("SELECT at_login FROM characters WHERE guid ='%u'", GUID_LOPART(guid));
1224 if (!result)
1226 WorldPacket data(SMSG_CHAR_CUSTOMIZE, 1);
1227 data << uint8(CHAR_CREATE_ERROR);
1228 SendPacket( &data );
1229 return;
1232 Field *fields = result->Fetch();
1233 uint32 at_loginFlags = fields[0].GetUInt32();
1234 delete result;
1236 if (!(at_loginFlags & AT_LOGIN_CUSTOMIZE))
1238 WorldPacket data(SMSG_CHAR_CUSTOMIZE, 1);
1239 data << uint8(CHAR_CREATE_ERROR);
1240 SendPacket( &data );
1241 return;
1244 // prevent character rename to invalid name
1245 if(!normalizePlayerName(newname))
1247 WorldPacket data(SMSG_CHAR_CUSTOMIZE, 1);
1248 data << uint8(CHAR_NAME_NO_NAME);
1249 SendPacket( &data );
1250 return;
1253 if(!ObjectMgr::IsValidName(newname,true))
1255 WorldPacket data(SMSG_CHAR_CUSTOMIZE, 1);
1256 data << uint8(CHAR_NAME_INVALID_CHARACTER);
1257 SendPacket( &data );
1258 return;
1261 // check name limitations
1262 if(GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(newname))
1264 WorldPacket data(SMSG_CHAR_CUSTOMIZE, 1);
1265 data << uint8(CHAR_NAME_RESERVED);
1266 SendPacket( &data );
1267 return;
1270 // character with this name already exist
1271 if(uint64 newguid = objmgr.GetPlayerGUIDByName(newname))
1273 if(newguid != guid)
1275 WorldPacket data(SMSG_CHAR_CUSTOMIZE, 1);
1276 data << uint8(CHAR_CREATE_NAME_IN_USE);
1277 SendPacket( &data );
1278 return;
1282 CharacterDatabase.escape_string(newname);
1283 Player::Customize(guid, gender, skin, face, hairStyle, hairColor, facialHair);
1284 CharacterDatabase.PExecute("UPDATE characters set name = '%s', at_login = at_login & ~ %u WHERE guid ='%u'", newname.c_str(), uint32(AT_LOGIN_CUSTOMIZE), GUID_LOPART(guid));
1285 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid ='%u'", GUID_LOPART(guid));
1287 std::string IP_str = GetRemoteAddress();
1288 sLog.outChar("Account: %d (IP: %s), Character guid: %u Customized to: %s", GetAccountId(), IP_str.c_str(), GUID_LOPART(guid), newname.c_str());
1290 WorldPacket data(SMSG_CHAR_CUSTOMIZE, 1+8+(newname.size()+1)+6);
1291 data << uint8(RESPONSE_SUCCESS);
1292 data << uint64(guid);
1293 data << newname;
1294 data << uint8(gender);
1295 data << uint8(skin);
1296 data << uint8(face);
1297 data << uint8(hairStyle);
1298 data << uint8(hairColor);
1299 data << uint8(facialHair);
1300 SendPacket(&data);
1303 void WorldSession::HandleEquipmentSetSave(WorldPacket &recv_data)
1305 sLog.outDebug("CMSG_EQUIPMENT_SET_SAVE");
1307 uint64 setGuid;
1308 if(!recv_data.readPackGUID(setGuid))
1309 return;
1311 CHECK_PACKET_SIZE(recv_data, recv_data.rpos() + 4);
1313 uint32 index;
1314 recv_data >> index;
1315 if(index >= MAX_EQUIPMENT_SET_INDEX) // client set slots amount
1316 return;
1318 CHECK_PACKET_SIZE(recv_data, recv_data.rpos() + 1);
1319 std::string name;
1320 recv_data >> name;
1322 CHECK_PACKET_SIZE(recv_data, recv_data.rpos() + 1);
1323 std::string iconName;
1324 recv_data >> iconName;
1326 EquipmentSet eqSet;
1328 eqSet.Guid = setGuid;
1329 eqSet.Name = name;
1330 eqSet.IconName = iconName;
1331 eqSet.state = EQUIPMENT_SET_NEW;
1333 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
1335 uint64 itemGuid;
1336 if(!recv_data.readPackGUID(itemGuid))
1337 return;
1339 Item *item = _player->GetItemByPos(INVENTORY_SLOT_BAG_0, i);
1341 if(!item && itemGuid) // cheating check 1
1342 return;
1344 if(item && item->GetGUID() != itemGuid) // cheating check 2
1345 return;
1347 eqSet.Items[i] = GUID_LOPART(itemGuid);
1350 _player->SetEquipmentSet(index, eqSet);
1353 void WorldSession::HandleEquipmentSetDelete(WorldPacket &recv_data)
1355 sLog.outDebug("CMSG_EQUIPMENT_SET_DELETE");
1357 uint64 setGuid;
1358 if(!recv_data.readPackGUID(setGuid))
1359 return;
1361 _player->DeleteEquipmentSet(setGuid);
1364 void WorldSession::HandleEquipmentSetUse(WorldPacket &recv_data)
1366 sLog.outDebug("CMSG_EQUIPMENT_SET_USE");
1367 recv_data.hexlike();
1369 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
1371 uint64 itemGuid;
1372 if(!recv_data.readPackGUID(itemGuid))
1373 return;
1375 CHECK_PACKET_SIZE(recv_data, recv_data.rpos()+1+1);
1377 uint8 srcbag, srcslot;
1378 recv_data >> srcbag >> srcslot;
1380 sLog.outDebug("Item " I64FMT ": srcbag %u, srcslot %u", itemGuid, srcbag, srcslot);
1382 Item *item = _player->GetItemByGuid(itemGuid);
1384 uint16 dstpos = i | (INVENTORY_SLOT_BAG_0 << 8);
1386 if(!item)
1388 Item *uItem = _player->GetItemByPos(INVENTORY_SLOT_BAG_0, i);
1389 if(!uItem)
1390 continue;
1392 ItemPosCountVec sDest;
1393 uint8 msg = _player->CanStoreItem( NULL_BAG, NULL_SLOT, sDest, uItem, false );
1394 if(msg == EQUIP_ERR_OK)
1396 _player->RemoveItem(INVENTORY_SLOT_BAG_0, i, true);
1397 _player->StoreItem( sDest, uItem, true );
1399 else
1400 _player->SendEquipError(msg, uItem, NULL);
1402 continue;
1405 if(item->GetPos() == dstpos)
1406 continue;
1408 _player->SwapItem(item->GetPos(), dstpos);
1411 WorldPacket data(SMSG_EQUIPMENT_SET_USE_RESULT, 1);
1412 data << uint8(0); // 4 - equipment swap failed - inventory is full
1413 SendPacket(&data);