[6922] Whitespace and newline fixes
[getmangos.git] / src / game / CharacterHandler.cpp
blobf16680b3c45868bf13820def437fa453e6c4ea53
1 /*
2 * Copyright (C) 2005-2008 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 "MapManager.h"
33 #include "ObjectAccessor.h"
34 #include "Group.h"
35 #include "Database/DatabaseImpl.h"
36 #include "PlayerDump.h"
37 #include "SocialMgr.h"
38 #include "Util.h"
39 #include "ArenaTeam.h"
40 #include "Language.h"
42 class LoginQueryHolder : public SqlQueryHolder
44 private:
45 uint32 m_accountId;
46 uint64 m_guid;
47 public:
48 LoginQueryHolder(uint32 accountId, uint64 guid)
49 : m_accountId(accountId), m_guid(guid) { }
50 uint64 GetGuid() const { return m_guid; }
51 uint32 GetAccountId() const { return m_accountId; }
52 bool Initialize();
55 bool LoginQueryHolder::Initialize()
57 SetSize(MAX_PLAYER_LOGIN_QUERY);
59 bool res = true;
61 // NOTE: all fields in `characters` must be read to prevent lost character data at next save in case wrong DB structure.
62 // !!! NOTE: including unused `zone`,`online`
63 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 FROM characters WHERE guid = '%u'", GUID_LOPART(m_guid));
64 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADGROUP, "SELECT leaderGuid FROM group_member WHERE memberGuid ='%u'", GUID_LOPART(m_guid));
65 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));
66 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));
67 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADSPELLS, "SELECT spell,slot,active,disabled FROM character_spell WHERE guid = '%u'", GUID_LOPART(m_guid));
68 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));
69 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS,"SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GUID_LOPART(m_guid));
70 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);
71 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADREPUTATION, "SELECT faction,standing,flags FROM character_reputation WHERE guid = '%u'", GUID_LOPART(m_guid));
72 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));
73 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADACTIONS, "SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button", GUID_LOPART(m_guid));
74 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));
75 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADMAILDATE, "SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(m_guid));
76 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADSOCIALLIST, "SELECT friend,flags,note FROM character_social WHERE guid = '%u' LIMIT 255", GUID_LOPART(m_guid));
77 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));
78 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS, "SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'", GUID_LOPART(m_guid));
79 if(sWorld.getConfig(CONFIG_DECLINED_NAMES_USED))
80 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES, "SELECT genitive, dative, accusative, instrumental, prepositional FROM character_declinedname WHERE guid = '%u'",GUID_LOPART(m_guid));
81 // in other case still be dummy query
82 res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADGUILD, "SELECT guildid,rank FROM guild_member WHERE guid = '%u'", GUID_LOPART(m_guid));
83 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));
85 return res;
88 // don't call WorldSession directly
89 // it may get deleted before the query callbacks get executed
90 // instead pass an account id to this handler
91 class CharacterHandler
93 public:
94 void HandleCharEnumCallback(QueryResult * result, uint32 account)
96 WorldSession * session = sWorld.FindSession(account);
97 if(!session)
99 delete result;
100 return;
102 session->HandleCharEnum(result);
104 void HandlePlayerLoginCallback(QueryResult * /*dummy*/, SqlQueryHolder * holder)
106 if (!holder) return;
107 WorldSession *session = sWorld.FindSession(((LoginQueryHolder*)holder)->GetAccountId());
108 if(!session)
110 delete holder;
111 return;
113 session->HandlePlayerLogin((LoginQueryHolder*)holder);
115 } chrHandler;
117 void WorldSession::HandleCharEnum(QueryResult * result)
119 // keys can be non cleared if player open realm list and close it by 'cancel'
120 loginDatabase.PExecute("UPDATE account SET v = '0', s = '0' WHERE id = '%u'", GetAccountId());
122 WorldPacket data(SMSG_CHAR_ENUM, 100); // we guess size
124 uint8 num = 0;
126 data << num;
128 if( result )
130 Player *plr = new Player(this);
133 uint32 guidlow = (*result)[0].GetUInt32();
134 sLog.outDetail("Loading char guid %u from account %u.",guidlow,GetAccountId());
136 if(plr->MinimalLoadFromDB( result, guidlow ))
138 plr->BuildEnumData( result, &data );
139 ++num;
142 while( result->NextRow() );
144 delete plr;
145 delete result;
148 data.put<uint8>(0, num);
150 SendPacket( &data );
153 void WorldSession::HandleCharEnumOpcode( WorldPacket & /*recv_data*/ )
155 /// get all the data necessary for loading all characters (along with their pets) on the account
156 CharacterDatabase.AsyncPQuery(&chrHandler, &CharacterHandler::HandleCharEnumCallback, GetAccountId(),
157 !sWorld.getConfig(CONFIG_DECLINED_NAMES_USED) ?
158 // ------- Query Without Declined Names --------
159 // 0 1 2 3 4 5 6 7 8
160 "SELECT characters.guid, characters.data, characters.name, characters.position_x, characters.position_y, characters.position_z, characters.map, characters.totaltime, characters.leveltime, "
161 // 9 10 11 12 13
162 "characters.at_login, character_pet.entry, character_pet.modelid, character_pet.level, guild_member.guildid "
163 "FROM characters LEFT JOIN character_pet ON characters.guid=character_pet.owner AND character_pet.slot='0' "
164 "LEFT JOIN guild_member ON characters.guid = guild_member.guid "
165 "WHERE characters.account = '%u' ORDER BY characters.guid"
167 // --------- Query With Declined Names ---------
168 // 0 1 2 3 4 5 6 7 8
169 "SELECT characters.guid, characters.data, characters.name, characters.position_x, characters.position_y, characters.position_z, characters.map, characters.totaltime, characters.leveltime, "
170 // 9 10 11 12 13 14
171 "characters.at_login, character_pet.entry, character_pet.modelid, character_pet.level, guild_member.guildid, genitive "
172 "FROM characters LEFT JOIN character_pet ON characters.guid = character_pet.owner AND character_pet.slot='0' "
173 "LEFT JOIN character_declinedname ON characters.guid = character_declinedname.guid "
174 "LEFT JOIN guild_member ON characters.guid = guild_member.guid "
175 "WHERE characters.account = '%u' ORDER BY characters.guid",
176 GetAccountId());
179 void WorldSession::HandleCharCreateOpcode( WorldPacket & recv_data )
181 CHECK_PACKET_SIZE(recv_data,1+1+1+1+1+1+1+1+1+1);
183 std::string name;
184 uint8 race_,class_;
186 recv_data >> name;
188 // recheck with known string size
189 CHECK_PACKET_SIZE(recv_data,(name.size()+1)+1+1+1+1+1+1+1+1+1);
191 recv_data >> race_;
192 recv_data >> class_;
194 WorldPacket data(SMSG_CHAR_CREATE, 1); // returned with diff.values in all cases
196 if(GetSecurity() == SEC_PLAYER)
198 if(uint32 mask = sWorld.getConfig(CONFIG_CHARACTERS_CREATING_DISABLED))
200 bool disabled = false;
202 uint32 team = Player::TeamForRace(race_);
203 switch(team)
205 case ALLIANCE: disabled = mask & (1<<0); break;
206 case HORDE: disabled = mask & (1<<1); break;
209 if(disabled)
211 data << (uint8)CHAR_CREATE_DISABLED;
212 SendPacket( &data );
213 return;
218 ChrClassesEntry const* classEntry = sChrClassesStore.LookupEntry(class_);
219 ChrRacesEntry const* raceEntry = sChrRacesStore.LookupEntry(race_);
221 if( !classEntry || !raceEntry )
223 data << (uint8)CHAR_CREATE_FAILED;
224 SendPacket( &data );
225 sLog.outError("Class: %u or Race %u not found in DBC (Wrong DBC files?) or Cheater?", class_, race_);
226 return;
229 // prevent character creating Expansion race without Expansion account
230 if (raceEntry->addon > Expansion())
232 data << (uint8)CHAR_CREATE_EXPANSION;
233 sLog.outError("Not Expansion 1 account:[%d] but tried to Create character with expansion 1 race (%u)",GetAccountId(),race_);
234 SendPacket( &data );
235 return;
238 // prevent character creating Expansion class without Expansion account
239 // TODO: use possible addon field in ChrClassesEntry in next dbc version
240 if (Expansion() < 2 && class_ == CLASS_DEATH_KNIGHT)
242 data << (uint8)CHAR_CREATE_EXPANSION;
243 sLog.outError("Not Expansion 2 account:[%d] but tried to Create character with expansion 2 class (%u)",GetAccountId(),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 bool AllowTwoSideAccounts = !sWorld.IsPvPRealm() || sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_ACCOUNTS) || GetSecurity() > SEC_PLAYER;
311 uint32 skipCinematics = sWorld.getConfig(CONFIG_SKIP_CINEMATICS);
313 bool have_same_race = false;
314 if(!AllowTwoSideAccounts || skipCinematics == 1)
316 QueryResult *result2 = CharacterDatabase.PQuery("SELECT DISTINCT race FROM characters WHERE account = '%u' %s", GetAccountId(),skipCinematics == 1 ? "" : "LIMIT 1");
317 if(result2)
319 uint32 team_= Player::TeamForRace(race_);
321 Field* field = result2->Fetch();
322 uint8 race = field[0].GetUInt32();
324 // need to check team only for first character
325 // TODO: what to if account already has characters of both races?
326 if (!AllowTwoSideAccounts)
328 uint32 team=0;
329 if(race > 0)
330 team = Player::TeamForRace(race);
332 if(team != team_)
334 data << (uint8)CHAR_CREATE_PVP_TEAMS_VIOLATION;
335 SendPacket( &data );
336 delete result2;
337 return;
341 if (skipCinematics == 1)
343 // TODO: check if cinematic already shown? (already logged in?; cinematic field)
344 while (race_ != race && result2->NextRow())
346 field = result2->Fetch();
347 race = field[0].GetUInt32();
349 have_same_race = race_ == race;
351 delete result2;
355 // extract other data required for player creating
356 uint8 gender, skin, face, hairStyle, hairColor, facialHair, outfitId;
357 recv_data >> gender >> skin >> face;
358 recv_data >> hairStyle >> hairColor >> facialHair >> outfitId;
360 Player * pNewChar = new Player(this);
361 if(!pNewChar->Create( objmgr.GenerateLowGuid(HIGHGUID_PLAYER), name, race_, class_, gender, skin, face, hairStyle, hairColor, facialHair, outfitId ))
363 // Player not create (race/class problem?)
364 delete pNewChar;
366 data << (uint8)CHAR_CREATE_ERROR;
367 SendPacket( &data );
369 return;
372 if(have_same_race && skipCinematics == 1 || skipCinematics == 2)
373 pNewChar->setCinematic(1); // not show intro
375 // Player created, save it now
376 pNewChar->SaveToDB();
377 charcount+=1;
379 loginDatabase.PExecute("DELETE FROM realmcharacters WHERE acctid= '%d' AND realmid = '%d'", GetAccountId(), realmID);
380 loginDatabase.PExecute("INSERT INTO realmcharacters (numchars, acctid, realmid) VALUES (%u, %u, %u)", charcount, GetAccountId(), realmID);
382 delete pNewChar; // created only to call SaveToDB()
384 data << (uint8)CHAR_CREATE_SUCCESS;
385 SendPacket( &data );
387 std::string IP_str = GetRemoteAddress();
388 sLog.outBasic("Account: %d (IP: %s) Create Character:[%s]",GetAccountId(),IP_str.c_str(),name.c_str());
389 sLog.outChar("Account: %d (IP: %s) Create Character:[%s]",GetAccountId(),IP_str.c_str(),name.c_str());
392 void WorldSession::HandleCharDeleteOpcode( WorldPacket & recv_data )
394 CHECK_PACKET_SIZE(recv_data,8);
396 uint64 guid;
397 recv_data >> guid;
399 // can't delete loaded character
400 if(objmgr.GetPlayer(guid))
401 return;
403 uint32 accountId = 0;
404 std::string name;
406 // is guild leader
407 if(objmgr.GetGuildByLeader(guid))
409 WorldPacket data(SMSG_CHAR_DELETE, 1);
410 data << (uint8)CHAR_DELETE_FAILED_GUILD_LEADER;
411 SendPacket( &data );
412 return;
415 // is arena team captain
416 if(objmgr.GetArenaTeamByCaptain(guid))
418 WorldPacket data(SMSG_CHAR_DELETE, 1);
419 data << (uint8)CHAR_DELETE_FAILED_ARENA_CAPTAIN;
420 SendPacket( &data );
421 return;
424 QueryResult *result = CharacterDatabase.PQuery("SELECT account,name FROM characters WHERE guid='%u'", GUID_LOPART(guid));
425 if(result)
427 Field *fields = result->Fetch();
428 accountId = fields[0].GetUInt32();
429 name = fields[1].GetCppString();
430 delete result;
433 // prevent deleting other players' characters using cheating tools
434 if(accountId != GetAccountId())
435 return;
437 std::string IP_str = GetRemoteAddress();
438 sLog.outBasic("Account: %d (IP: %s) Delete Character:[%s] (guid:%u)",GetAccountId(),IP_str.c_str(),name.c_str(),GUID_LOPART(guid));
439 sLog.outChar("Account: %d (IP: %s) Delete Character:[%s] (guid: %u)",GetAccountId(),IP_str.c_str(),name.c_str(),GUID_LOPART(guid));
441 if(sLog.IsOutCharDump()) // optimize GetPlayerDump call
443 std::string dump = PlayerDumpWriter().GetDump(GUID_LOPART(guid));
444 sLog.outCharDump(dump.c_str(),GetAccountId(),GUID_LOPART(guid),name.c_str());
447 Player::DeleteFromDB(guid, GetAccountId());
449 WorldPacket data(SMSG_CHAR_DELETE, 1);
450 data << (uint8)CHAR_DELETE_SUCCESS;
451 SendPacket( &data );
454 void WorldSession::HandlePlayerLoginOpcode( WorldPacket & recv_data )
456 CHECK_PACKET_SIZE(recv_data,8);
458 if(PlayerLoading() || GetPlayer() != NULL)
460 sLog.outError("Player tryes to login again, AccountId = %d",GetAccountId());
461 return;
464 m_playerLoading = true;
465 uint64 playerGuid = 0;
467 DEBUG_LOG( "WORLD: Recvd Player Logon Message" );
469 recv_data >> playerGuid;
471 LoginQueryHolder *holder = new LoginQueryHolder(GetAccountId(), playerGuid);
472 if(!holder->Initialize())
474 delete holder; // delete all unprocessed queries
475 m_playerLoading = false;
476 return;
479 CharacterDatabase.DelayQueryHolder(&chrHandler, &CharacterHandler::HandlePlayerLoginCallback, holder);
482 void WorldSession::HandlePlayerLogin(LoginQueryHolder * holder)
484 uint64 playerGuid = holder->GetGuid();
486 Player* pCurrChar = new Player(this);
487 pCurrChar->GetMotionMaster()->Initialize();
489 // "GetAccountId()==db stored account id" checked in LoadFromDB (prevent login not own character using cheating tools)
490 if(!pCurrChar->LoadFromDB(GUID_LOPART(playerGuid), holder))
492 KickPlayer(); // disconnect client, player no set to session and it will not deleted or saved at kick
493 delete pCurrChar; // delete it manually
494 delete holder; // delete all unprocessed queries
495 m_playerLoading = false;
496 return;
499 SetPlayer(pCurrChar);
501 pCurrChar->SendDungeonDifficulty(false);
503 WorldPacket data( SMSG_LOGIN_VERIFY_WORLD, 20 );
504 data << pCurrChar->GetMapId();
505 data << pCurrChar->GetPositionX();
506 data << pCurrChar->GetPositionY();
507 data << pCurrChar->GetPositionZ();
508 data << pCurrChar->GetOrientation();
509 SendPacket(&data);
511 data.Initialize( SMSG_ACCOUNT_DATA_TIMES, 128 );
512 for(int i = 0; i < 32; i++)
513 data << uint32(0);
514 SendPacket(&data);
516 data.Initialize(SMSG_FEATURE_SYSTEM_STATUS, 2); // added in 2.2.0
517 data << uint8(2); // unknown value
518 data << uint8(0); // enable(1)/disable(0) voice chat interface in client
519 SendPacket(&data);
521 // Send MOTD
523 data.Initialize(SMSG_MOTD, 50); // new in 2.0.1
524 data << (uint32)0;
526 uint32 linecount=0;
527 std::string str_motd = sWorld.GetMotd();
528 std::string::size_type pos, nextpos;
530 pos = 0;
531 while ( (nextpos= str_motd.find('@',pos)) != std::string::npos )
533 if (nextpos != pos)
535 data << str_motd.substr(pos,nextpos-pos);
536 ++linecount;
538 pos = nextpos+1;
541 if (pos<str_motd.length())
543 data << str_motd.substr(pos);
544 ++linecount;
547 data.put(0, linecount);
549 SendPacket( &data );
550 DEBUG_LOG( "WORLD: Sent motd (SMSG_MOTD)" );
553 //QueryResult *result = CharacterDatabase.PQuery("SELECT guildid,rank FROM guild_member WHERE guid = '%u'",pCurrChar->GetGUIDLow());
554 QueryResult *resultGuild = holder->GetResult(PLAYER_LOGIN_QUERY_LOADGUILD);
556 if(resultGuild)
558 Field *fields = resultGuild->Fetch();
559 pCurrChar->SetInGuild(fields[0].GetUInt32());
560 pCurrChar->SetRank(fields[1].GetUInt32());
561 delete resultGuild;
563 else if(pCurrChar->GetGuildId()) // clear guild related fields in case wrong data about non existed membership
565 pCurrChar->SetInGuild(0);
566 pCurrChar->SetRank(0);
569 if(pCurrChar->GetGuildId() != 0)
571 Guild* guild = objmgr.GetGuildById(pCurrChar->GetGuildId());
572 if(guild)
574 data.Initialize(SMSG_GUILD_EVENT, (2+guild->GetMOTD().size()+1));
575 data << (uint8)GE_MOTD;
576 data << (uint8)1;
577 data << guild->GetMOTD();
578 SendPacket(&data);
579 DEBUG_LOG( "WORLD: Sent guild-motd (SMSG_GUILD_EVENT)" );
581 data.Initialize(SMSG_GUILD_EVENT, (5+10)); // we guess size
582 data<<(uint8)GE_SIGNED_ON;
583 data<<(uint8)1;
584 data<<pCurrChar->GetName();
585 data<<pCurrChar->GetGUID();
586 guild->BroadcastPacket(&data);
587 DEBUG_LOG( "WORLD: Sent guild-signed-on (SMSG_GUILD_EVENT)" );
589 // Increment online members of the guild
590 guild->IncOnlineMemberCount();
592 else
594 // remove wrong guild data
595 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());
596 pCurrChar->SetInGuild(0);
600 if(!pCurrChar->isAlive())
601 pCurrChar->SendCorpseReclaimDelay(true);
603 pCurrChar->SendInitialPacketsBeforeAddToMap();
605 //Show cinematic at the first time that player login
606 if( !pCurrChar->getCinematic() )
608 pCurrChar->setCinematic(1);
610 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(pCurrChar->getRace());
611 if(rEntry)
613 data.Initialize( SMSG_TRIGGER_CINEMATIC,4 );
614 data << uint32(rEntry->startmovie);
615 SendPacket( &data );
619 if (!pCurrChar->GetMap()->Add(pCurrChar))
621 AreaTrigger const* at = objmgr.GetGoBackTrigger(pCurrChar->GetMapId());
622 if(at)
623 pCurrChar->TeleportTo(at->target_mapId, at->target_X, at->target_Y, at->target_Z, pCurrChar->GetOrientation());
624 else
625 pCurrChar->TeleportTo(pCurrChar->m_homebindMapId, pCurrChar->m_homebindX, pCurrChar->m_homebindY, pCurrChar->m_homebindZ, pCurrChar->GetOrientation());
628 ObjectAccessor::Instance().AddObject(pCurrChar);
629 //sLog.outDebug("Player %s added to Map.",pCurrChar->GetName());
630 pCurrChar->GetSocial()->SendSocialList();
632 pCurrChar->SendInitialPacketsAfterAddToMap();
634 CharacterDatabase.PExecute("UPDATE characters SET online = 1 WHERE guid = '%u'", pCurrChar->GetGUIDLow());
635 loginDatabase.PExecute("UPDATE account SET online = 1 WHERE id = '%u'", GetAccountId());
636 pCurrChar->SetInGameTime( getMSTime() );
638 // announce group about member online (must be after add to player list to receive announce to self)
639 if(Group *group = pCurrChar->GetGroup())
641 //pCurrChar->groupInfo.group->SendInit(this); // useless
642 group->SendUpdate();
645 // friend status
646 sSocialMgr.SendFriendStatus(pCurrChar, FRIEND_ONLINE, pCurrChar->GetGUIDLow(), true);
648 // Place character in world (and load zone) before some object loading
649 pCurrChar->LoadCorpse();
651 // setting Ghost+speed if dead
652 if (pCurrChar->m_deathState != ALIVE)
654 // not blizz like, we must correctly save and load player instead...
655 if(pCurrChar->getRace() == RACE_NIGHTELF)
656 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)
657 pCurrChar->CastSpell(pCurrChar, 8326, true, 0); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
659 //pCurrChar->SetUInt32Value(UNIT_FIELD_AURA+41, 8326);
660 //pCurrChar->SetUInt32Value(UNIT_FIELD_AURA+42, 20584);
661 //pCurrChar->SetUInt32Value(UNIT_FIELD_AURAFLAGS+6, 238);
662 //pCurrChar->SetUInt32Value(UNIT_FIELD_AURALEVELS+11, 514);
663 //pCurrChar->SetUInt32Value(UNIT_FIELD_AURAAPPLICATIONS+11, 65535);
664 //pCurrChar->SetUInt32Value(UNIT_FIELD_DISPLAYID, 1825);
665 //if (pCurrChar->getRace() == RACE_NIGHTELF)
667 // pCurrChar->SetSpeed(MOVE_RUN, 1.5f*1.2f, true);
668 // pCurrChar->SetSpeed(MOVE_SWIM, 1.5f*1.2f, true);
670 //else
672 // pCurrChar->SetSpeed(MOVE_RUN, 1.5f, true);
673 // pCurrChar->SetSpeed(MOVE_SWIM, 1.5f, true);
675 pCurrChar->SetMovement(MOVE_WATER_WALK);
678 if(uint32 sourceNode = pCurrChar->m_taxi.GetTaxiSource())
681 sLog.outDebug( "WORLD: Restart character %u taxi flight", pCurrChar->GetGUIDLow() );
683 uint32 MountId = objmgr.GetTaxiMount(sourceNode, pCurrChar->GetTeam());
684 uint32 path = pCurrChar->m_taxi.GetCurrentTaxiPath();
686 // search appropriate start path node
687 uint32 startNode = 0;
689 TaxiPathNodeList const& nodeList = sTaxiPathNodesByPath[path];
691 float distPrev = MAP_SIZE*MAP_SIZE;
692 float distNext =
693 (nodeList[0].x-pCurrChar->GetPositionX())*(nodeList[0].x-pCurrChar->GetPositionX())+
694 (nodeList[0].y-pCurrChar->GetPositionY())*(nodeList[0].y-pCurrChar->GetPositionY())+
695 (nodeList[0].z-pCurrChar->GetPositionZ())*(nodeList[0].z-pCurrChar->GetPositionZ());
697 for(uint32 i = 1; i < nodeList.size(); ++i)
699 TaxiPathNode const& node = nodeList[i];
700 TaxiPathNode const& prevNode = nodeList[i-1];
702 // skip nodes at another map
703 if(node.mapid != pCurrChar->GetMapId())
704 continue;
706 distPrev = distNext;
708 distNext =
709 (node.x-pCurrChar->GetPositionX())*(node.x-pCurrChar->GetPositionX())+
710 (node.y-pCurrChar->GetPositionY())*(node.y-pCurrChar->GetPositionY())+
711 (node.z-pCurrChar->GetPositionZ())*(node.z-pCurrChar->GetPositionZ());
713 float distNodes =
714 (node.x-prevNode.x)*(node.x-prevNode.x)+
715 (node.y-prevNode.y)*(node.y-prevNode.y)+
716 (node.z-prevNode.z)*(node.z-prevNode.z);
718 if(distNext + distPrev < distNodes)
720 startNode = i;
721 break;
725 SendDoFlight( MountId, path, startNode );
728 // Load pet if any and player is alive and not in taxi flight
729 if(pCurrChar->isAlive() && pCurrChar->m_taxi.GetTaxiSource()==0)
730 pCurrChar->LoadPet();
732 // Set FFA PvP for non GM in non-rest mode
733 if(sWorld.IsFFAPvPRealm() && !pCurrChar->isGameMaster() && !pCurrChar->HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_RESTING) )
734 pCurrChar->SetFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
736 if(pCurrChar->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP))
737 pCurrChar->SetContestedPvP();
739 // Apply at_login requests
740 if(pCurrChar->HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
742 pCurrChar->resetSpells();
743 SendNotification(LANG_RESET_SPELLS);
746 if(pCurrChar->HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
748 pCurrChar->resetTalents(true);
749 SendNotification(LANG_RESET_TALENTS);
752 // show time before shutdown if shutdown planned.
753 if(sWorld.IsShutdowning())
754 sWorld.ShutdownMsg(true,pCurrChar);
756 if(sWorld.getConfig(CONFIG_ALL_TAXI_PATHS))
757 pCurrChar->SetTaxiCheater(true);
759 if(pCurrChar->isGameMaster())
760 SendNotification(LANG_GM_ON);
762 std::string IP_str = GetRemoteAddress();
763 sLog.outChar("Account: %d (IP: %s) Login Character:[%s] (guid:%u)",
764 GetAccountId(),IP_str.c_str(),pCurrChar->GetName() ,pCurrChar->GetGUIDLow());
766 m_playerLoading = false;
767 delete holder;
770 void WorldSession::HandleSetFactionAtWar( WorldPacket & recv_data )
772 CHECK_PACKET_SIZE(recv_data,4+1);
774 DEBUG_LOG( "WORLD: Received CMSG_SET_FACTION_ATWAR" );
776 uint32 repListID;
777 uint8 flag;
779 recv_data >> repListID;
780 recv_data >> flag;
782 FactionStateList::iterator itr = GetPlayer()->m_factions.find(repListID);
783 if (itr == GetPlayer()->m_factions.end())
784 return;
786 // always invisible or hidden faction can't change war state
787 if(itr->second.Flags & (FACTION_FLAG_INVISIBLE_FORCED|FACTION_FLAG_HIDDEN) )
788 return;
790 GetPlayer()->SetFactionAtWar(&itr->second,flag);
793 //I think this function is never used :/ I dunno, but i guess this opcode not exists
794 void WorldSession::HandleSetFactionCheat( WorldPacket & /*recv_data*/ )
796 //CHECK_PACKET_SIZE(recv_data,4+4);
798 //sLog.outDebug("WORLD SESSION: HandleSetFactionCheat");
800 uint32 FactionID;
801 uint32 Standing;
803 recv_data >> FactionID;
804 recv_data >> Standing;
806 std::list<struct Factions>::iterator itr;
808 for(itr = GetPlayer()->factions.begin(); itr != GetPlayer()->factions.end(); ++itr)
810 if(itr->ReputationListID == FactionID)
812 itr->Standing += Standing;
813 itr->Flags = (itr->Flags | 1);
814 break;
818 GetPlayer()->UpdateReputation();
821 void WorldSession::HandleMeetingStoneInfo( WorldPacket & /*recv_data*/ )
823 DEBUG_LOG( "WORLD: Received CMSG_MEETING_STONE_INFO" );
825 WorldPacket data(SMSG_MEETINGSTONE_SETQUEUE, 5);
826 data << uint32(0) << uint8(6);
827 SendPacket(&data);
830 void WorldSession::HandleTutorialFlag( WorldPacket & recv_data )
832 CHECK_PACKET_SIZE(recv_data,4);
834 uint32 iFlag;
835 recv_data >> iFlag;
837 uint32 wInt = (iFlag / 32);
838 if (wInt >= 8)
840 //sLog.outError("CHEATER? Account:[%d] Guid[%u] tried to send wrong CMSG_TUTORIAL_FLAG", GetAccountId(),GetGUID());
841 return;
843 uint32 rInt = (iFlag % 32);
845 uint32 tutflag = GetPlayer()->GetTutorialInt( wInt );
846 tutflag |= (1 << rInt);
847 GetPlayer()->SetTutorialInt( wInt, tutflag );
849 //sLog.outDebug("Received Tutorial Flag Set {%u}.", iFlag);
852 void WorldSession::HandleTutorialClear( WorldPacket & /*recv_data*/ )
854 for ( uint32 iI = 0; iI < 8; iI++)
855 GetPlayer()->SetTutorialInt( iI, 0xFFFFFFFF );
858 void WorldSession::HandleTutorialReset( WorldPacket & /*recv_data*/ )
860 for ( uint32 iI = 0; iI < 8; iI++)
861 GetPlayer()->SetTutorialInt( iI, 0x00000000 );
864 void WorldSession::HandleSetWatchedFactionIndexOpcode(WorldPacket & recv_data)
866 CHECK_PACKET_SIZE(recv_data,4);
868 DEBUG_LOG("WORLD: Received CMSG_SET_WATCHED_FACTION");
869 uint32 fact;
870 recv_data >> fact;
871 GetPlayer()->SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, fact);
874 void WorldSession::HandleSetWatchedFactionInactiveOpcode(WorldPacket & recv_data)
876 CHECK_PACKET_SIZE(recv_data,4+1);
878 DEBUG_LOG("WORLD: Received CMSG_SET_FACTION_INACTIVE");
879 uint32 replistid;
880 uint8 inactive;
881 recv_data >> replistid >> inactive;
883 FactionStateList::iterator itr = _player->m_factions.find(replistid);
884 if (itr == _player->m_factions.end())
885 return;
887 _player->SetFactionInactive(&itr->second, inactive);
890 void WorldSession::HandleToggleHelmOpcode( WorldPacket & /*recv_data*/ )
892 DEBUG_LOG("CMSG_TOGGLE_HELM for %s", _player->GetName());
893 _player->ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM);
896 void WorldSession::HandleToggleCloakOpcode( WorldPacket & /*recv_data*/ )
898 DEBUG_LOG("CMSG_TOGGLE_CLOAK for %s", _player->GetName());
899 _player->ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK);
902 void WorldSession::HandleChangePlayerNameOpcode(WorldPacket& recv_data)
904 uint64 guid;
905 std::string newname;
907 CHECK_PACKET_SIZE(recv_data, 8+1);
909 recv_data >> guid;
910 recv_data >> newname;
912 // prevent character rename to invalid name
913 if(!normalizePlayerName(newname))
915 WorldPacket data(SMSG_CHAR_RENAME, 1);
916 data << (uint8)CHAR_NAME_NO_NAME;
917 SendPacket( &data );
918 return;
921 if(!ObjectMgr::IsValidName(newname,true))
923 WorldPacket data(SMSG_CHAR_RENAME, 1);
924 data << (uint8)CHAR_NAME_INVALID_CHARACTER;
925 SendPacket( &data );
926 return;
929 // check name limitations
930 if(GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(newname))
932 WorldPacket data(SMSG_CHAR_RENAME, 1);
933 data << (uint8)CHAR_NAME_RESERVED;
934 SendPacket( &data );
935 return;
938 std::string escaped_newname = newname;
939 CharacterDatabase.escape_string(escaped_newname);
941 // make sure that the character belongs to the current account, that rename at login is enabled
942 // and that there is no character with the desired new name
943 CharacterDatabase.AsyncPQuery(&WorldSession::HandleChangePlayerNameOpcodeCallBack,
944 GetAccountId(), newname,
945 "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')",
946 GUID_LOPART(guid), GetAccountId(), AT_LOGIN_RENAME, AT_LOGIN_RENAME, escaped_newname.c_str()
950 void WorldSession::HandleChangePlayerNameOpcodeCallBack(QueryResult *result, uint32 accountId, std::string newname)
952 WorldSession * session = sWorld.FindSession(accountId);
953 if(!session)
955 if(result) delete result;
956 return;
959 if (!result)
961 WorldPacket data(SMSG_CHAR_RENAME, 1);
962 data << (uint8)CHAR_CREATE_ERROR;
963 session->SendPacket( &data );
964 return;
967 uint32 guidLow = result->Fetch()[0].GetUInt32();
968 uint64 guid = MAKE_NEW_GUID(guidLow, 0, HIGHGUID_PLAYER);
969 std::string oldname = result->Fetch()[1].GetCppString();
971 delete result;
973 CharacterDatabase.PExecute("UPDATE characters set name = '%s', at_login = at_login & ~ %u WHERE guid ='%u'", newname.c_str(), uint32(AT_LOGIN_RENAME), guidLow);
974 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid ='%u'", guidLow);
976 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());
978 WorldPacket data(SMSG_CHAR_RENAME,1+8+(newname.size()+1));
979 data << (uint8)RESPONSE_SUCCESS;
980 data << guid;
981 data << newname;
982 session->SendPacket(&data);
985 void WorldSession::HandleDeclinedPlayerNameOpcode(WorldPacket& recv_data)
987 uint64 guid;
989 CHECK_PACKET_SIZE(recv_data, 8);
990 recv_data >> guid;
992 // not accept declined names for unsupported languages
993 std::string name;
994 if(!objmgr.GetPlayerNameByGUID(guid, name))
996 WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8);
997 data << uint32(1);
998 data << uint64(guid);
999 SendPacket(&data);
1000 return;
1003 std::wstring wname;
1004 if(!Utf8toWStr(name, wname))
1006 WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8);
1007 data << uint32(1);
1008 data << uint64(guid);
1009 SendPacket(&data);
1010 return;
1013 if(!isCyrillicCharacter(wname[0])) // name already stored as only single alphabet using
1015 WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8);
1016 data << uint32(1);
1017 data << uint64(guid);
1018 SendPacket(&data);
1019 return;
1022 std::string name2;
1023 DeclinedName declinedname;
1025 CHECK_PACKET_SIZE(recv_data, recv_data.rpos() + 1);
1026 recv_data >> name2;
1028 if(name2 != name) // character have different name
1030 WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8);
1031 data << uint32(1);
1032 data << uint64(guid);
1033 SendPacket(&data);
1034 return;
1037 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
1039 CHECK_PACKET_SIZE(recv_data, recv_data.rpos() + 1);
1040 recv_data >> declinedname.name[i];
1041 if(!normalizePlayerName(declinedname.name[i]))
1043 WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8);
1044 data << uint32(1);
1045 data << uint64(guid);
1046 SendPacket(&data);
1047 return;
1051 if(!ObjectMgr::CheckDeclinedNames(GetMainPartOfName(wname, 0), declinedname))
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 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
1061 CharacterDatabase.escape_string(declinedname.name[i]);
1063 CharacterDatabase.BeginTransaction();
1064 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'", GUID_LOPART(guid));
1065 CharacterDatabase.PExecute("INSERT INTO character_declinedname (guid, genitive, dative, accusative, instrumental, prepositional) VALUES ('%u','%s','%s','%s','%s','%s')",
1066 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());
1067 CharacterDatabase.CommitTransaction();
1069 WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8);
1070 data << uint32(0); // OK
1071 data << uint64(guid);
1072 SendPacket(&data);