port over some changes from Trinity version including one possible memory leak fix
[AHbot.git] / src / game / CharacterHandler.cpp
blob4fc9508332d64d9f1f75f801c157e8fda0be3959
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 SendLfgUpdate(0, 0, 0);
891 void WorldSession::HandleTutorialFlag( WorldPacket & recv_data )
893 CHECK_PACKET_SIZE(recv_data,4);
895 uint32 iFlag;
896 recv_data >> iFlag;
898 uint32 wInt = (iFlag / 32);
899 if (wInt >= 8)
901 //sLog.outError("CHEATER? Account:[%d] Guid[%u] tried to send wrong CMSG_TUTORIAL_FLAG", GetAccountId(),GetGUID());
902 return;
904 uint32 rInt = (iFlag % 32);
906 uint32 tutflag = GetTutorialInt( wInt );
907 tutflag |= (1 << rInt);
908 SetTutorialInt( wInt, tutflag );
910 //sLog.outDebug("Received Tutorial Flag Set {%u}.", iFlag);
913 void WorldSession::HandleTutorialClear( WorldPacket & /*recv_data*/ )
915 for (int i = 0; i < 8; ++i)
916 SetTutorialInt( i, 0xFFFFFFFF );
919 void WorldSession::HandleTutorialReset( WorldPacket & /*recv_data*/ )
921 for (int i = 0; i < 8; ++i)
922 SetTutorialInt( i, 0x00000000 );
925 void WorldSession::HandleSetWatchedFactionOpcode(WorldPacket & recv_data)
927 CHECK_PACKET_SIZE(recv_data,4);
929 DEBUG_LOG("WORLD: Received CMSG_SET_WATCHED_FACTION");
930 uint32 fact;
931 recv_data >> fact;
932 GetPlayer()->SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, fact);
935 void WorldSession::HandleSetFactionInactiveOpcode(WorldPacket & recv_data)
937 CHECK_PACKET_SIZE(recv_data,4+1);
939 DEBUG_LOG("WORLD: Received CMSG_SET_FACTION_INACTIVE");
940 uint32 replistid;
941 uint8 inactive;
942 recv_data >> replistid >> inactive;
944 _player->GetReputationMgr().SetInactive(replistid, inactive);
947 void WorldSession::HandleShowingHelmOpcode( WorldPacket & /*recv_data*/ )
949 DEBUG_LOG("CMSG_SHOWING_HELM for %s", _player->GetName());
950 _player->ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM);
953 void WorldSession::HandleShowingCloakOpcode( WorldPacket & /*recv_data*/ )
955 DEBUG_LOG("CMSG_SHOWING_CLOAK for %s", _player->GetName());
956 _player->ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK);
959 void WorldSession::HandleCharRenameOpcode(WorldPacket& recv_data)
961 CHECK_PACKET_SIZE(recv_data, 8+1);
963 uint64 guid;
964 std::string newname;
966 recv_data >> guid;
967 recv_data >> newname;
969 // prevent character rename to invalid name
970 if(!normalizePlayerName(newname))
972 WorldPacket data(SMSG_CHAR_RENAME, 1);
973 data << uint8(CHAR_NAME_NO_NAME);
974 SendPacket( &data );
975 return;
978 if(!ObjectMgr::IsValidName(newname, true))
980 WorldPacket data(SMSG_CHAR_RENAME, 1);
981 data << uint8(CHAR_NAME_INVALID_CHARACTER);
982 SendPacket( &data );
983 return;
986 // check name limitations
987 if(GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(newname))
989 WorldPacket data(SMSG_CHAR_RENAME, 1);
990 data << uint8(CHAR_NAME_RESERVED);
991 SendPacket( &data );
992 return;
995 std::string escaped_newname = newname;
996 CharacterDatabase.escape_string(escaped_newname);
998 // make sure that the character belongs to the current account, that rename at login is enabled
999 // and that there is no character with the desired new name
1000 CharacterDatabase.AsyncPQuery(&WorldSession::HandleChangePlayerNameOpcodeCallBack,
1001 GetAccountId(), newname,
1002 "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')",
1003 GUID_LOPART(guid), GetAccountId(), AT_LOGIN_RENAME, AT_LOGIN_RENAME, escaped_newname.c_str()
1007 void WorldSession::HandleChangePlayerNameOpcodeCallBack(QueryResult *result, uint32 accountId, std::string newname)
1009 WorldSession * session = sWorld.FindSession(accountId);
1010 if(!session)
1012 if(result) delete result;
1013 return;
1016 if (!result)
1018 WorldPacket data(SMSG_CHAR_RENAME, 1);
1019 data << uint8(CHAR_CREATE_ERROR);
1020 session->SendPacket( &data );
1021 return;
1024 uint32 guidLow = result->Fetch()[0].GetUInt32();
1025 uint64 guid = MAKE_NEW_GUID(guidLow, 0, HIGHGUID_PLAYER);
1026 std::string oldname = result->Fetch()[1].GetCppString();
1028 delete result;
1030 CharacterDatabase.PExecute("UPDATE characters set name = '%s', at_login = at_login & ~ %u WHERE guid ='%u'", newname.c_str(), uint32(AT_LOGIN_RENAME), guidLow);
1031 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid ='%u'", guidLow);
1033 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());
1035 WorldPacket data(SMSG_CHAR_RENAME, 1+8+(newname.size()+1));
1036 data << uint8(RESPONSE_SUCCESS);
1037 data << uint64(guid);
1038 data << newname;
1039 session->SendPacket(&data);
1042 void WorldSession::HandleSetPlayerDeclinedNames(WorldPacket& recv_data)
1044 uint64 guid;
1046 CHECK_PACKET_SIZE(recv_data, 8);
1047 recv_data >> guid;
1049 // not accept declined names for unsupported languages
1050 std::string name;
1051 if(!objmgr.GetPlayerNameByGUID(guid, name))
1053 WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8);
1054 data << uint32(1);
1055 data << uint64(guid);
1056 SendPacket(&data);
1057 return;
1060 std::wstring wname;
1061 if(!Utf8toWStr(name, wname))
1063 WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8);
1064 data << uint32(1);
1065 data << uint64(guid);
1066 SendPacket(&data);
1067 return;
1070 if(!isCyrillicCharacter(wname[0])) // name already stored as only single alphabet using
1072 WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8);
1073 data << uint32(1);
1074 data << uint64(guid);
1075 SendPacket(&data);
1076 return;
1079 std::string name2;
1080 DeclinedName declinedname;
1082 CHECK_PACKET_SIZE(recv_data, recv_data.rpos() + 1);
1083 recv_data >> name2;
1085 if(name2 != name) // character have different name
1087 WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8);
1088 data << uint32(1);
1089 data << uint64(guid);
1090 SendPacket(&data);
1091 return;
1094 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
1096 CHECK_PACKET_SIZE(recv_data, recv_data.rpos() + 1);
1097 recv_data >> declinedname.name[i];
1098 if(!normalizePlayerName(declinedname.name[i]))
1100 WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8);
1101 data << uint32(1);
1102 data << uint64(guid);
1103 SendPacket(&data);
1104 return;
1108 if(!ObjectMgr::CheckDeclinedNames(GetMainPartOfName(wname, 0), declinedname))
1110 WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8);
1111 data << uint32(1);
1112 data << uint64(guid);
1113 SendPacket(&data);
1114 return;
1117 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
1118 CharacterDatabase.escape_string(declinedname.name[i]);
1120 CharacterDatabase.BeginTransaction();
1121 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'", GUID_LOPART(guid));
1122 CharacterDatabase.PExecute("INSERT INTO character_declinedname (guid, genitive, dative, accusative, instrumental, prepositional) VALUES ('%u','%s','%s','%s','%s','%s')",
1123 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());
1124 CharacterDatabase.CommitTransaction();
1126 WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8);
1127 data << uint32(0); // OK
1128 data << uint64(guid);
1129 SendPacket(&data);
1132 void WorldSession::HandleAlterAppearance( WorldPacket & recv_data )
1134 sLog.outDebug("CMSG_ALTER_APPEARANCE");
1136 CHECK_PACKET_SIZE(recv_data, 4+4+4);
1138 uint32 Hair, Color, FacialHair;
1139 recv_data >> Hair >> Color >> FacialHair;
1141 BarberShopStyleEntry const* bs_hair = sBarberShopStyleStore.LookupEntry(Hair);
1143 if(!bs_hair || bs_hair->type != 0 || bs_hair->race != _player->getRace() || bs_hair->gender != _player->getGender())
1144 return;
1146 BarberShopStyleEntry const* bs_facialHair = sBarberShopStyleStore.LookupEntry(FacialHair);
1148 if(!bs_facialHair || bs_facialHair->type != 2 || bs_facialHair->race != _player->getRace() || bs_facialHair->gender != _player->getGender())
1149 return;
1151 uint32 Cost = _player->GetBarberShopCost(bs_hair->hair_id, Color, bs_facialHair->hair_id);
1153 // 0 - ok
1154 // 1,3 - not enough money
1155 // 2 - you have to seat on barber chair
1156 if(_player->GetMoney() < Cost)
1158 WorldPacket data(SMSG_BARBER_SHOP_RESULT, 4);
1159 data << uint32(1); // no money
1160 SendPacket(&data);
1161 return;
1163 else
1165 WorldPacket data(SMSG_BARBER_SHOP_RESULT, 4);
1166 data << uint32(0); // ok
1167 SendPacket(&data);
1170 _player->ModifyMoney(-int32(Cost)); // it isn't free
1171 _player->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_AT_BARBER, Cost);
1173 _player->SetByteValue(PLAYER_BYTES, 2, uint8(bs_hair->hair_id));
1174 _player->SetByteValue(PLAYER_BYTES, 3, uint8(Color));
1175 _player->SetByteValue(PLAYER_BYTES_2, 0, uint8(bs_facialHair->hair_id));
1177 _player->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_VISIT_BARBER_SHOP, 1);
1179 _player->SetStandState(0); // stand up
1182 void WorldSession::HandleRemoveGlyph( WorldPacket & recv_data )
1184 CHECK_PACKET_SIZE(recv_data, 4);
1186 uint32 slot;
1187 recv_data >> slot;
1189 if(slot >= MAX_GLYPH_SLOT_INDEX)
1191 sLog.outDebug("Client sent wrong glyph slot number in opcode CMSG_REMOVE_GLYPH %u", slot);
1192 return;
1195 if(uint32 glyph = _player->GetGlyph(slot))
1197 if(GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph))
1199 _player->RemoveAurasDueToSpell(gp->SpellId);
1200 _player->SetGlyph(slot, 0);
1201 _player->SendTalentsInfoData(false);
1206 void WorldSession::HandleCharCustomize(WorldPacket& recv_data)
1208 CHECK_PACKET_SIZE(recv_data, 8+1);
1210 uint64 guid;
1211 std::string newname;
1213 recv_data >> guid;
1214 recv_data >> newname;
1216 CHECK_PACKET_SIZE(recv_data, recv_data.rpos()+1+1+1+1+1+1);
1218 uint8 gender, skin, face, hairStyle, hairColor, facialHair;
1219 recv_data >> gender >> skin >> hairColor >> hairStyle >> facialHair >> face;
1221 QueryResult *result = CharacterDatabase.PQuery("SELECT at_login FROM characters WHERE guid ='%u'", GUID_LOPART(guid));
1222 if (!result)
1224 WorldPacket data(SMSG_CHAR_CUSTOMIZE, 1);
1225 data << uint8(CHAR_CREATE_ERROR);
1226 SendPacket( &data );
1227 return;
1230 Field *fields = result->Fetch();
1231 uint32 at_loginFlags = fields[0].GetUInt32();
1232 delete result;
1234 if (!(at_loginFlags & AT_LOGIN_CUSTOMIZE))
1236 WorldPacket data(SMSG_CHAR_CUSTOMIZE, 1);
1237 data << uint8(CHAR_CREATE_ERROR);
1238 SendPacket( &data );
1239 return;
1242 // prevent character rename to invalid name
1243 if(!normalizePlayerName(newname))
1245 WorldPacket data(SMSG_CHAR_CUSTOMIZE, 1);
1246 data << uint8(CHAR_NAME_NO_NAME);
1247 SendPacket( &data );
1248 return;
1251 if(!ObjectMgr::IsValidName(newname,true))
1253 WorldPacket data(SMSG_CHAR_CUSTOMIZE, 1);
1254 data << uint8(CHAR_NAME_INVALID_CHARACTER);
1255 SendPacket( &data );
1256 return;
1259 // check name limitations
1260 if(GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(newname))
1262 WorldPacket data(SMSG_CHAR_CUSTOMIZE, 1);
1263 data << uint8(CHAR_NAME_RESERVED);
1264 SendPacket( &data );
1265 return;
1268 // character with this name already exist
1269 if(uint64 newguid = objmgr.GetPlayerGUIDByName(newname))
1271 if(newguid != guid)
1273 WorldPacket data(SMSG_CHAR_CUSTOMIZE, 1);
1274 data << uint8(CHAR_CREATE_NAME_IN_USE);
1275 SendPacket( &data );
1276 return;
1280 CharacterDatabase.escape_string(newname);
1281 Player::Customize(guid, gender, skin, face, hairStyle, hairColor, facialHair);
1282 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));
1283 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid ='%u'", GUID_LOPART(guid));
1285 std::string IP_str = GetRemoteAddress();
1286 sLog.outChar("Account: %d (IP: %s), Character guid: %u Customized to: %s", GetAccountId(), IP_str.c_str(), GUID_LOPART(guid), newname.c_str());
1288 WorldPacket data(SMSG_CHAR_CUSTOMIZE, 1+8+(newname.size()+1)+6);
1289 data << uint8(RESPONSE_SUCCESS);
1290 data << uint64(guid);
1291 data << newname;
1292 data << uint8(gender);
1293 data << uint8(skin);
1294 data << uint8(face);
1295 data << uint8(hairStyle);
1296 data << uint8(hairColor);
1297 data << uint8(facialHair);
1298 SendPacket(&data);
1301 void WorldSession::HandleEquipmentSetSave(WorldPacket &recv_data)
1303 sLog.outDebug("CMSG_EQUIPMENT_SET_SAVE");
1305 uint64 setGuid;
1306 if(!recv_data.readPackGUID(setGuid))
1307 return;
1309 CHECK_PACKET_SIZE(recv_data, recv_data.rpos() + 4);
1311 uint32 index;
1312 recv_data >> index;
1313 if(index >= MAX_EQUIPMENT_SET_INDEX) // client set slots amount
1314 return;
1316 CHECK_PACKET_SIZE(recv_data, recv_data.rpos() + 1);
1317 std::string name;
1318 recv_data >> name;
1320 CHECK_PACKET_SIZE(recv_data, recv_data.rpos() + 1);
1321 std::string iconName;
1322 recv_data >> iconName;
1324 EquipmentSet eqSet;
1326 eqSet.Guid = setGuid;
1327 eqSet.Name = name;
1328 eqSet.IconName = iconName;
1329 eqSet.state = EQUIPMENT_SET_NEW;
1331 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
1333 uint64 itemGuid;
1334 if(!recv_data.readPackGUID(itemGuid))
1335 return;
1337 Item *item = _player->GetItemByPos(INVENTORY_SLOT_BAG_0, i);
1339 if(!item && itemGuid) // cheating check 1
1340 return;
1342 if(item && item->GetGUID() != itemGuid) // cheating check 2
1343 return;
1345 eqSet.Items[i] = GUID_LOPART(itemGuid);
1348 _player->SetEquipmentSet(index, eqSet);
1351 void WorldSession::HandleEquipmentSetDelete(WorldPacket &recv_data)
1353 sLog.outDebug("CMSG_EQUIPMENT_SET_DELETE");
1355 uint64 setGuid;
1356 if(!recv_data.readPackGUID(setGuid))
1357 return;
1359 _player->DeleteEquipmentSet(setGuid);
1362 void WorldSession::HandleEquipmentSetUse(WorldPacket &recv_data)
1364 sLog.outDebug("CMSG_EQUIPMENT_SET_USE");
1365 recv_data.hexlike();
1367 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
1369 uint64 itemGuid;
1370 if(!recv_data.readPackGUID(itemGuid))
1371 return;
1373 CHECK_PACKET_SIZE(recv_data, recv_data.rpos()+1+1);
1375 uint8 srcbag, srcslot;
1376 recv_data >> srcbag >> srcslot;
1378 sLog.outDebug("Item " I64FMT ": srcbag %u, srcslot %u", itemGuid, srcbag, srcslot);
1380 Item *item = _player->GetItemByGuid(itemGuid);
1382 uint16 dstpos = i | (INVENTORY_SLOT_BAG_0 << 8);
1384 if(!item)
1386 Item *uItem = _player->GetItemByPos(INVENTORY_SLOT_BAG_0, i);
1387 if(!uItem)
1388 continue;
1390 ItemPosCountVec sDest;
1391 uint8 msg = _player->CanStoreItem( NULL_BAG, NULL_SLOT, sDest, uItem, false );
1392 if(msg == EQUIP_ERR_OK)
1394 _player->RemoveItem(INVENTORY_SLOT_BAG_0, i, true);
1395 _player->StoreItem( sDest, uItem, true );
1397 else
1398 _player->SendEquipError(msg, uItem, NULL);
1400 continue;
1403 if(item->GetPos() == dstpos)
1404 continue;
1406 _player->SwapItem(item->GetPos(), dstpos);
1409 WorldPacket data(SMSG_EQUIPMENT_SET_USE_RESULT, 1);
1410 data << uint8(0); // 4 - equipment swap failed - inventory is full
1411 SendPacket(&data);