[7645] Fixed problems wit temporary unsummoned pets and cleanup code.
[AHbot.git] / src / game / CharacterHandler.cpp
blob79cb46ee96fc39d6f55bca4e88bcb2d8df7d23ee
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_LOADTUTORIALS, "SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetAccountId(), realmID);
70 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADREPUTATION, "SELECT faction,standing,flags FROM character_reputation WHERE guid = '%u'", GUID_LOPART(m_guid));
71 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));
72 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADACTIONS, "SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button", GUID_LOPART(m_guid));
73 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));
74 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADMAILDATE, "SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(m_guid));
75 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADSOCIALLIST, "SELECT friend,flags,note FROM character_social WHERE guid = '%u' LIMIT 255", GUID_LOPART(m_guid));
76 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));
77 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS, "SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'", GUID_LOPART(m_guid));
78 if(sWorld.getConfig(CONFIG_DECLINED_NAMES_USED))
79 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES, "SELECT genitive, dative, accusative, instrumental, prepositional FROM character_declinedname WHERE guid = '%u'",GUID_LOPART(m_guid));
80 // in other case still be dummy query
81 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADGUILD, "SELECT guildid,rank FROM guild_member WHERE guid = '%u'", GUID_LOPART(m_guid));
82 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));
83 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS, "SELECT achievement, date FROM character_achievement WHERE guid = '%u'", GUID_LOPART(m_guid));
84 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS,"SELECT criteria, counter, date FROM character_achievement_progress WHERE guid = '%u'", 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());
720 pCurrChar->GetSocial()->SendSocialList();
722 pCurrChar->SendInitialPacketsAfterAddToMap();
724 CharacterDatabase.PExecute("UPDATE characters SET online = 1 WHERE guid = '%u'", pCurrChar->GetGUIDLow());
725 loginDatabase.PExecute("UPDATE account SET online = 1 WHERE id = '%u'", GetAccountId());
726 pCurrChar->SetInGameTime( getMSTime() );
728 // announce group about member online (must be after add to player list to receive announce to self)
729 if(Group *group = pCurrChar->GetGroup())
731 //pCurrChar->groupInfo.group->SendInit(this); // useless
732 group->SendUpdate();
735 // friend status
736 sSocialMgr.SendFriendStatus(pCurrChar, FRIEND_ONLINE, pCurrChar->GetGUIDLow(), true);
738 // Place character in world (and load zone) before some object loading
739 pCurrChar->LoadCorpse();
741 // setting Ghost+speed if dead
742 if (pCurrChar->m_deathState != ALIVE)
744 // not blizz like, we must correctly save and load player instead...
745 if(pCurrChar->getRace() == RACE_NIGHTELF)
746 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)
747 pCurrChar->CastSpell(pCurrChar, 8326, true, 0); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
749 pCurrChar->SetMovement(MOVE_WATER_WALK);
752 if(uint32 sourceNode = pCurrChar->m_taxi.GetTaxiSource())
754 sLog.outDebug( "WORLD: Restart character %u taxi flight", pCurrChar->GetGUIDLow() );
756 uint32 MountId = objmgr.GetTaxiMount(sourceNode, pCurrChar->GetTeam());
757 uint32 path = pCurrChar->m_taxi.GetCurrentTaxiPath();
759 // search appropriate start path node
760 uint32 startNode = 0;
762 TaxiPathNodeList const& nodeList = sTaxiPathNodesByPath[path];
764 float distPrev = MAP_SIZE*MAP_SIZE;
765 float distNext =
766 (nodeList[0].x-pCurrChar->GetPositionX())*(nodeList[0].x-pCurrChar->GetPositionX())+
767 (nodeList[0].y-pCurrChar->GetPositionY())*(nodeList[0].y-pCurrChar->GetPositionY())+
768 (nodeList[0].z-pCurrChar->GetPositionZ())*(nodeList[0].z-pCurrChar->GetPositionZ());
770 for(uint32 i = 1; i < nodeList.size(); ++i)
772 TaxiPathNode const& node = nodeList[i];
773 TaxiPathNode const& prevNode = nodeList[i-1];
775 // skip nodes at another map
776 if(node.mapid != pCurrChar->GetMapId())
777 continue;
779 distPrev = distNext;
781 distNext =
782 (node.x-pCurrChar->GetPositionX())*(node.x-pCurrChar->GetPositionX())+
783 (node.y-pCurrChar->GetPositionY())*(node.y-pCurrChar->GetPositionY())+
784 (node.z-pCurrChar->GetPositionZ())*(node.z-pCurrChar->GetPositionZ());
786 float distNodes =
787 (node.x-prevNode.x)*(node.x-prevNode.x)+
788 (node.y-prevNode.y)*(node.y-prevNode.y)+
789 (node.z-prevNode.z)*(node.z-prevNode.z);
791 if(distNext + distPrev < distNodes)
793 startNode = i;
794 break;
798 SendDoFlight( MountId, path, startNode );
801 // Load pet if any (if player not alive and in taxi flight or another then pet will remember as temporary unsummoned)
802 pCurrChar->LoadPet();
804 // Set FFA PvP for non GM in non-rest mode
805 if(sWorld.IsFFAPvPRealm() && !pCurrChar->isGameMaster() && !pCurrChar->HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_RESTING) )
806 pCurrChar->SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
808 if(pCurrChar->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP))
809 pCurrChar->SetContestedPvP();
811 // Apply at_login requests
812 if(pCurrChar->HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
814 pCurrChar->resetSpells();
815 SendNotification(LANG_RESET_SPELLS);
818 if(pCurrChar->HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
820 pCurrChar->resetTalents(true);
821 SendNotification(LANG_RESET_TALENTS);
824 // show time before shutdown if shutdown planned.
825 if(sWorld.IsShutdowning())
826 sWorld.ShutdownMsg(true,pCurrChar);
828 if(sWorld.getConfig(CONFIG_ALL_TAXI_PATHS))
829 pCurrChar->SetTaxiCheater(true);
831 if(pCurrChar->isGameMaster())
832 SendNotification(LANG_GM_ON);
834 std::string IP_str = GetRemoteAddress();
835 sLog.outChar("Account: %d (IP: %s) Login Character:[%s] (guid:%u)",
836 GetAccountId(),IP_str.c_str(),pCurrChar->GetName() ,pCurrChar->GetGUIDLow());
838 m_playerLoading = false;
839 delete holder;
842 void WorldSession::HandleSetFactionAtWar( WorldPacket & recv_data )
844 CHECK_PACKET_SIZE(recv_data,4+1);
846 DEBUG_LOG( "WORLD: Received CMSG_SET_FACTION_ATWAR" );
848 uint32 repListID;
849 uint8 flag;
851 recv_data >> repListID;
852 recv_data >> flag;
854 GetPlayer()->GetReputationMgr().SetAtWar(repListID,flag);
857 //I think this function is never used :/ I dunno, but i guess this opcode not exists
858 void WorldSession::HandleSetFactionCheat( WorldPacket & /*recv_data*/ )
860 //CHECK_PACKET_SIZE(recv_data,4+4);
862 sLog.outError("WORLD SESSION: HandleSetFactionCheat, not expected call, please report.");
864 uint32 FactionID;
865 uint32 Standing;
867 recv_data >> FactionID;
868 recv_data >> Standing;
870 std::list<struct Factions>::iterator itr;
872 for(itr = GetPlayer()->factions.begin(); itr != GetPlayer()->factions.end(); ++itr)
874 if(itr->ReputationListID == FactionID)
876 itr->Standing += Standing;
877 itr->Flags = (itr->Flags | 1);
878 break;
882 GetPlayer()->GetReputationMgr().SendStates();
885 void WorldSession::HandleMeetingStoneInfo( WorldPacket & /*recv_data*/ )
887 DEBUG_LOG( "WORLD: Received CMSG_MEETING_STONE_INFO" );
889 WorldPacket data(SMSG_MEETINGSTONE_SETQUEUE, 5);
890 data << uint32(0) << uint8(6);
891 SendPacket(&data);
894 void WorldSession::HandleTutorialFlag( WorldPacket & recv_data )
896 CHECK_PACKET_SIZE(recv_data,4);
898 uint32 iFlag;
899 recv_data >> iFlag;
901 uint32 wInt = (iFlag / 32);
902 if (wInt >= 8)
904 //sLog.outError("CHEATER? Account:[%d] Guid[%u] tried to send wrong CMSG_TUTORIAL_FLAG", GetAccountId(),GetGUID());
905 return;
907 uint32 rInt = (iFlag % 32);
909 uint32 tutflag = GetPlayer()->GetTutorialInt( wInt );
910 tutflag |= (1 << rInt);
911 GetPlayer()->SetTutorialInt( wInt, tutflag );
913 //sLog.outDebug("Received Tutorial Flag Set {%u}.", iFlag);
916 void WorldSession::HandleTutorialClear( WorldPacket & /*recv_data*/ )
918 for ( uint32 iI = 0; iI < 8; iI++)
919 GetPlayer()->SetTutorialInt( iI, 0xFFFFFFFF );
922 void WorldSession::HandleTutorialReset( WorldPacket & /*recv_data*/ )
924 for ( uint32 iI = 0; iI < 8; iI++)
925 GetPlayer()->SetTutorialInt( iI, 0x00000000 );
928 void WorldSession::HandleSetWatchedFactionIndexOpcode(WorldPacket & recv_data)
930 CHECK_PACKET_SIZE(recv_data,4);
932 DEBUG_LOG("WORLD: Received CMSG_SET_WATCHED_FACTION");
933 uint32 fact;
934 recv_data >> fact;
935 GetPlayer()->SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, fact);
938 void WorldSession::HandleSetWatchedFactionInactiveOpcode(WorldPacket & recv_data)
940 CHECK_PACKET_SIZE(recv_data,4+1);
942 DEBUG_LOG("WORLD: Received CMSG_SET_FACTION_INACTIVE");
943 uint32 replistid;
944 uint8 inactive;
945 recv_data >> replistid >> inactive;
947 _player->GetReputationMgr().SetInactive(replistid, inactive);
950 void WorldSession::HandleToggleHelmOpcode( WorldPacket & /*recv_data*/ )
952 DEBUG_LOG("CMSG_TOGGLE_HELM for %s", _player->GetName());
953 _player->ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM);
956 void WorldSession::HandleToggleCloakOpcode( WorldPacket & /*recv_data*/ )
958 DEBUG_LOG("CMSG_TOGGLE_CLOAK for %s", _player->GetName());
959 _player->ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK);
962 void WorldSession::HandleChangePlayerNameOpcode(WorldPacket& recv_data)
964 CHECK_PACKET_SIZE(recv_data, 8+1);
966 uint64 guid;
967 std::string newname;
969 recv_data >> guid;
970 recv_data >> newname;
972 // prevent character rename to invalid name
973 if(!normalizePlayerName(newname))
975 WorldPacket data(SMSG_CHAR_RENAME, 1);
976 data << uint8(CHAR_NAME_NO_NAME);
977 SendPacket( &data );
978 return;
981 if(!ObjectMgr::IsValidName(newname, true))
983 WorldPacket data(SMSG_CHAR_RENAME, 1);
984 data << uint8(CHAR_NAME_INVALID_CHARACTER);
985 SendPacket( &data );
986 return;
989 // check name limitations
990 if(GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(newname))
992 WorldPacket data(SMSG_CHAR_RENAME, 1);
993 data << uint8(CHAR_NAME_RESERVED);
994 SendPacket( &data );
995 return;
998 std::string escaped_newname = newname;
999 CharacterDatabase.escape_string(escaped_newname);
1001 // make sure that the character belongs to the current account, that rename at login is enabled
1002 // and that there is no character with the desired new name
1003 CharacterDatabase.AsyncPQuery(&WorldSession::HandleChangePlayerNameOpcodeCallBack,
1004 GetAccountId(), newname,
1005 "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')",
1006 GUID_LOPART(guid), GetAccountId(), AT_LOGIN_RENAME, AT_LOGIN_RENAME, escaped_newname.c_str()
1010 void WorldSession::HandleChangePlayerNameOpcodeCallBack(QueryResult *result, uint32 accountId, std::string newname)
1012 WorldSession * session = sWorld.FindSession(accountId);
1013 if(!session)
1015 if(result) delete result;
1016 return;
1019 if (!result)
1021 WorldPacket data(SMSG_CHAR_RENAME, 1);
1022 data << uint8(CHAR_CREATE_ERROR);
1023 session->SendPacket( &data );
1024 return;
1027 uint32 guidLow = result->Fetch()[0].GetUInt32();
1028 uint64 guid = MAKE_NEW_GUID(guidLow, 0, HIGHGUID_PLAYER);
1029 std::string oldname = result->Fetch()[1].GetCppString();
1031 delete result;
1033 CharacterDatabase.PExecute("UPDATE characters set name = '%s', at_login = at_login & ~ %u WHERE guid ='%u'", newname.c_str(), uint32(AT_LOGIN_RENAME), guidLow);
1034 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid ='%u'", guidLow);
1036 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());
1038 WorldPacket data(SMSG_CHAR_RENAME, 1+8+(newname.size()+1));
1039 data << uint8(RESPONSE_SUCCESS);
1040 data << uint64(guid);
1041 data << newname;
1042 session->SendPacket(&data);
1045 void WorldSession::HandleDeclinedPlayerNameOpcode(WorldPacket& recv_data)
1047 uint64 guid;
1049 CHECK_PACKET_SIZE(recv_data, 8);
1050 recv_data >> guid;
1052 // not accept declined names for unsupported languages
1053 std::string name;
1054 if(!objmgr.GetPlayerNameByGUID(guid, name))
1056 WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8);
1057 data << uint32(1);
1058 data << uint64(guid);
1059 SendPacket(&data);
1060 return;
1063 std::wstring wname;
1064 if(!Utf8toWStr(name, wname))
1066 WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8);
1067 data << uint32(1);
1068 data << uint64(guid);
1069 SendPacket(&data);
1070 return;
1073 if(!isCyrillicCharacter(wname[0])) // name already stored as only single alphabet using
1075 WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8);
1076 data << uint32(1);
1077 data << uint64(guid);
1078 SendPacket(&data);
1079 return;
1082 std::string name2;
1083 DeclinedName declinedname;
1085 CHECK_PACKET_SIZE(recv_data, recv_data.rpos() + 1);
1086 recv_data >> name2;
1088 if(name2 != name) // character have different name
1090 WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8);
1091 data << uint32(1);
1092 data << uint64(guid);
1093 SendPacket(&data);
1094 return;
1097 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
1099 CHECK_PACKET_SIZE(recv_data, recv_data.rpos() + 1);
1100 recv_data >> declinedname.name[i];
1101 if(!normalizePlayerName(declinedname.name[i]))
1103 WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8);
1104 data << uint32(1);
1105 data << uint64(guid);
1106 SendPacket(&data);
1107 return;
1111 if(!ObjectMgr::CheckDeclinedNames(GetMainPartOfName(wname, 0), declinedname))
1113 WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8);
1114 data << uint32(1);
1115 data << uint64(guid);
1116 SendPacket(&data);
1117 return;
1120 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
1121 CharacterDatabase.escape_string(declinedname.name[i]);
1123 CharacterDatabase.BeginTransaction();
1124 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'", GUID_LOPART(guid));
1125 CharacterDatabase.PExecute("INSERT INTO character_declinedname (guid, genitive, dative, accusative, instrumental, prepositional) VALUES ('%u','%s','%s','%s','%s','%s')",
1126 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());
1127 CharacterDatabase.CommitTransaction();
1129 WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8);
1130 data << uint32(0); // OK
1131 data << uint64(guid);
1132 SendPacket(&data);
1135 void WorldSession::HandleAlterAppearance( WorldPacket & recv_data )
1137 sLog.outDebug("CMSG_ALTER_APPEARANCE");
1139 CHECK_PACKET_SIZE(recv_data, 4+4+4);
1141 uint32 Hair, Color, FacialHair;
1142 recv_data >> Hair >> Color >> FacialHair;
1144 BarberShopStyleEntry const* bs_hair = sBarberShopStyleStore.LookupEntry(Hair);
1146 if(!bs_hair || bs_hair->type != 0 || bs_hair->race != _player->getRace() || bs_hair->gender != _player->getGender())
1147 return;
1149 BarberShopStyleEntry const* bs_facialHair = sBarberShopStyleStore.LookupEntry(FacialHair);
1151 if(!bs_facialHair || bs_facialHair->type != 2 || bs_facialHair->race != _player->getRace() || bs_facialHair->gender != _player->getGender())
1152 return;
1154 uint32 Cost = _player->GetBarberShopCost(bs_hair->hair_id, Color, bs_facialHair->hair_id);
1156 // 0 - ok
1157 // 1,3 - not enough money
1158 // 2 - you have to seat on barber chair
1159 if(_player->GetMoney() < Cost)
1161 WorldPacket data(SMSG_BARBER_SHOP_RESULT, 4);
1162 data << uint32(1); // no money
1163 SendPacket(&data);
1164 return;
1166 else
1168 WorldPacket data(SMSG_BARBER_SHOP_RESULT, 4);
1169 data << uint32(0); // ok
1170 SendPacket(&data);
1173 _player->ModifyMoney(-int32(Cost)); // it isn't free
1174 _player->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_AT_BARBER, Cost);
1176 _player->SetByteValue(PLAYER_BYTES, 2, uint8(bs_hair->hair_id));
1177 _player->SetByteValue(PLAYER_BYTES, 3, uint8(Color));
1178 _player->SetByteValue(PLAYER_BYTES_2, 0, uint8(bs_facialHair->hair_id));
1180 _player->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_VISIT_BARBER_SHOP, 1);
1182 _player->SetStandState(0); // stand up
1185 void WorldSession::HandleRemoveGlyph( WorldPacket & recv_data )
1187 CHECK_PACKET_SIZE(recv_data, 4);
1189 uint32 slot;
1190 recv_data >> slot;
1192 if(slot >= MAX_GLYPH_SLOT_INDEX)
1194 sLog.outDebug("Client sent wrong glyph slot number in opcode CMSG_REMOVE_GLYPH %u", slot);
1195 return;
1198 if(uint32 glyph = _player->GetGlyph(slot))
1200 if(GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph))
1202 _player->RemoveAurasDueToSpell(gp->SpellId);
1203 _player->SetGlyph(slot, 0);
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);