root/trunk/src/game/CharacterHandler.cpp @ 6

Revision 6, 38.3 kB (checked in by yumileroy, 17 years ago)

[svn] * Added ACE for Linux and Windows (Thanks Derex for Linux part and partial Windows part)
* Updated to 6721 and 676
* Fixed TrinityScript? logo
* Version updated to 0.2.6721.676

Original author: Neo2003
Date: 2008-10-04 06:17:19-05:00

Line 
1/*
2 * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
3 *
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.
8 *
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.
13 *
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
17 */
18
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
40class LoginQueryHolder : public SqlQueryHolder
41{
42    private:
43        uint32 m_accountId;
44        uint64 m_guid;
45    public:
46        LoginQueryHolder(uint32 accountId, uint64 guid)
47            : m_accountId(accountId), m_guid(guid) { }
48        uint64 GetGuid() const { return m_guid; }
49        uint32 GetAccountId() const { return m_accountId; }
50        bool Initialize();
51};
52
53bool LoginQueryHolder::Initialize()
54{
55    SetSize(MAX_PLAYER_LOGIN_QUERY);
56
57    bool res = true;
58
59    // NOTE: all fields in `characters` must be read to prevent lost character data at next save in case wrong DB structure.
60    // !!! NOTE: including unused `zone`,`online`
61    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, gmstate, stable_slots, at_login, zone, online, death_expire_time, taxi_path, dungeon_difficulty FROM characters WHERE guid = '%u'", GUID_LOPART(m_guid));
62    res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADGROUP,           "SELECT leaderGuid FROM group_member WHERE memberGuid ='%u'", GUID_LOPART(m_guid));
63    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));
64    res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADAURAS,           "SELECT caster_guid,spell,effect_index,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'", GUID_LOPART(m_guid));
65    res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADSPELLS,          "SELECT spell,slot,active,disabled FROM character_spell WHERE guid = '%u'", GUID_LOPART(m_guid));
66    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));
67    res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS,"SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GUID_LOPART(m_guid));
68    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);
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
82    return res;
83}
84
85// don't call WorldSession directly
86// it may get deleted before the query callbacks get executed
87// instead pass an account id to this handler
88class CharacterHandler
89{
90    public:
91        void HandleCharEnumCallback(QueryResult * result, uint32 account)
92        {
93            WorldSession * session = sWorld.FindSession(account);
94            if(!session)
95            {
96                delete result;
97                return;
98            }
99            session->HandleCharEnum(result);
100        }
101        void HandlePlayerLoginCallback(QueryResult * /*dummy*/, SqlQueryHolder * holder)
102        {
103            if (!holder) return;
104            WorldSession *session = sWorld.FindSession(((LoginQueryHolder*)holder)->GetAccountId());
105            if(!session)
106            {
107                delete holder;
108                return;
109            }
110            session->HandlePlayerLogin((LoginQueryHolder*)holder);
111        }
112} chrHandler;
113
114void WorldSession::HandleCharEnum(QueryResult * result)
115{
116    // keys can be non cleared if player open realm list and close it by 'cancel'
117    loginDatabase.PExecute("UPDATE account SET v = '0', s = '0' WHERE id = '%u'", GetAccountId());
118
119    WorldPacket data(SMSG_CHAR_ENUM, 100);                  // we guess size
120
121    uint8 num = 0;
122
123    data << num;
124
125    if( result )
126    {
127        Player *plr = new Player(this);
128        do
129        {
130            sLog.outDetail("Loading char guid %u from account %u.",(*result)[0].GetUInt32(),GetAccountId());
131
132            if(plr->MinimalLoadFromDB( result, (*result)[0].GetUInt32() ))
133            {
134                plr->BuildEnumData( result, &data );
135                ++num;
136            }
137        }
138        while( result->NextRow() );
139
140        delete plr;
141        delete result;
142    }
143
144    data.put<uint8>(0, num);
145
146    SendPacket( &data );
147}
148
149void WorldSession::HandleCharEnumOpcode( WorldPacket & /*recv_data*/ )
150{
151    /// get all the data necessary for loading all characters (along with their pets) on the account
152    CharacterDatabase.AsyncPQuery(&chrHandler, &CharacterHandler::HandleCharEnumCallback, GetAccountId(),
153         !sWorld.getConfig(CONFIG_DECLINED_NAMES_USED) ?
154    //   ------- Query Without Declined Names --------
155    //          0                1                2                      3                      4                      5               6                     7                     8
156        "SELECT characters.data, characters.name, characters.position_x, characters.position_y, characters.position_z, characters.map, characters.totaltime, characters.leveltime, characters.at_login, "
157    //   9                    10                     11
158        "character_pet.entry, character_pet.modelid, character_pet.level "
159        "FROM characters LEFT JOIN character_pet ON characters.guid=character_pet.owner AND character_pet.slot='0' "
160        "WHERE characters.account = '%u' ORDER BY characters.guid"
161        :
162    //   --------- Query With Declined Names ---------
163    //          0                1                2                      3                      4                      5               6                     7                     8
164        "SELECT characters.data, characters.name, characters.position_x, characters.position_y, characters.position_z, characters.map, characters.totaltime, characters.leveltime, characters.at_login, "
165    //   9                    10                     11                   12
166        "character_pet.entry, character_pet.modelid, character_pet.level, genitive "
167        "FROM characters LEFT JOIN character_pet ON characters.guid = character_pet.owner AND character_pet.slot='0' "
168        "LEFT JOIN character_declinedname ON characters.guid = character_declinedname.guid "
169        "WHERE characters.account = '%u' ORDER BY characters.guid",
170        GetAccountId());
171}
172
173void WorldSession::HandleCharCreateOpcode( WorldPacket & recv_data )
174{
175    CHECK_PACKET_SIZE(recv_data,1+1+1+1+1+1+1+1+1+1);
176
177    std::string name;
178    uint8 race_,class_;
179    bool pTbc = this->IsTBC() && sWorld.getConfig(CONFIG_EXPANSION) > 0;
180    recv_data >> name;
181
182    // recheck with known string size
183    CHECK_PACKET_SIZE(recv_data,(name.size()+1)+1+1+1+1+1+1+1+1+1);
184
185    recv_data >> race_;
186    recv_data >> class_;
187
188    WorldPacket data(SMSG_CHAR_CREATE, 1);                  // returned with diff.values in all cases
189
190    if(GetSecurity() == SEC_PLAYER)
191    {
192        if(uint32 mask = sWorld.getConfig(CONFIG_CHARACTERS_CREATING_DISABLED))
193        {
194            bool disabled = false;
195
196            uint32 team = Player::TeamForRace(race_);
197            switch(team)
198            {
199                case ALLIANCE: disabled = mask & (1<<0); break;
200                case HORDE:    disabled = mask & (1<<1); break;
201            }
202
203            if(disabled)
204            {
205                data << (uint8)CHAR_CREATE_DISABLED;
206                SendPacket( &data );
207                return;
208            }
209        }
210    }
211
212    if (!sChrClassesStore.LookupEntry(class_)||
213        !sChrRacesStore.LookupEntry(race_))
214    {
215        data << (uint8)CHAR_CREATE_FAILED;
216        SendPacket( &data );
217        sLog.outError("Class: %u or Race %u not found in DBC (Wrong DBC files?) or Cheater?", class_, race_);
218        return;
219    }
220
221    // prevent character creating Expansion race without Expansion account
222    if (!pTbc&&(race_>RACE_TROLL))
223    {
224        data << (uint8)CHAR_CREATE_EXPANSION;
225        sLog.outError("No Expansion Account:[%d] but tried to Create TBC character",GetAccountId());
226        SendPacket( &data );
227        return;
228    }
229
230    // prevent character creating with invalid name
231    if(!normalizePlayerName(name))
232    {
233        data << (uint8)CHAR_NAME_INVALID_CHARACTER;
234        SendPacket( &data );
235        sLog.outError("Account:[%d] but tried to Create character with empty [name] ",GetAccountId());
236        return;
237    }
238
239    // check name limitations
240    if(!ObjectMgr::IsValidName(name,true))
241    {
242        data << (uint8)CHAR_NAME_INVALID_CHARACTER;
243        SendPacket( &data );
244        return;
245    }
246
247    if(GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(name))
248    {
249        data << (uint8)CHAR_NAME_RESERVED;
250        SendPacket( &data );
251        return;
252    }
253
254    if(objmgr.GetPlayerGUIDByName(name))
255    {
256        data << (uint8)CHAR_CREATE_NAME_IN_USE;
257        SendPacket( &data );
258        return;
259    }
260
261    QueryResult *resultacct = loginDatabase.PQuery("SELECT SUM(numchars) FROM realmcharacters WHERE acctid = '%d'", GetAccountId());
262    if ( resultacct )
263    {
264        Field *fields=resultacct->Fetch();
265        uint32 acctcharcount = fields[0].GetUInt32();
266        delete resultacct;
267
268        if (acctcharcount >= sWorld.getConfig(CONFIG_CHARACTERS_PER_ACCOUNT))
269        {
270            data << (uint8)CHAR_CREATE_ACCOUNT_LIMIT;
271            SendPacket( &data );
272            return;
273        }
274    }
275
276    QueryResult *result = CharacterDatabase.PQuery("SELECT COUNT(guid) FROM characters WHERE account = '%d'", GetAccountId());
277    uint8 charcount = 0;
278    if ( result )
279    {
280        Field *fields=result->Fetch();
281        charcount = fields[0].GetUInt8();
282        delete result;
283
284        if (charcount >= sWorld.getConfig(CONFIG_CHARACTERS_PER_REALM))
285        {
286            data << (uint8)CHAR_CREATE_SERVER_LIMIT;
287            SendPacket( &data );
288            return;
289        }
290    }
291
292    bool AllowTwoSideAccounts = !sWorld.IsPvPRealm() || sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_ACCOUNTS) || GetSecurity() > SEC_PLAYER;
293    uint32 skipCinematics = sWorld.getConfig(CONFIG_SKIP_CINEMATICS);
294
295    bool have_same_race = false;
296    if(!AllowTwoSideAccounts || skipCinematics == 1)
297    {
298        QueryResult *result2 = CharacterDatabase.PQuery("SELECT DISTINCT race FROM characters WHERE account = '%u' %s", GetAccountId(),skipCinematics == 1 ? "" : "LIMIT 1");
299        if(result2)
300        {
301            uint32 team_= Player::TeamForRace(race_);
302
303            Field* field = result2->Fetch();
304            uint8 race = field[0].GetUInt32();
305
306            // need to check team only for first character
307            // TODO: what to if account already has characters of both races?
308            if (!AllowTwoSideAccounts)
309            {
310                uint32 team=0;
311                if(race > 0)
312                    team = Player::TeamForRace(race);
313
314                if(team != team_)
315                {
316                    data << (uint8)CHAR_CREATE_PVP_TEAMS_VIOLATION;
317                    SendPacket( &data );
318                    delete result2;
319                    return;
320                }
321            }
322
323            if (skipCinematics == 1)
324            {
325                // TODO: check if cinematic already shown? (already logged in?; cinematic field)
326                while (race_ != race && result2->NextRow())
327                {
328                    field = result2->Fetch();
329                    race = field[0].GetUInt32();
330                }
331                have_same_race = race_ == race;
332            }
333            delete result2;
334        }
335    }
336
337    // extract other data required for player creating
338    uint8 gender, skin, face, hairStyle, hairColor, facialHair, outfitId;
339    recv_data >> gender >> skin >> face;
340    recv_data >> hairStyle >> hairColor >> facialHair >> outfitId;
341
342    Player * pNewChar = new Player(this);
343    if(!pNewChar->Create( objmgr.GenerateLowGuid(HIGHGUID_PLAYER), name, race_, class_, gender, skin, face, hairStyle, hairColor, facialHair, outfitId ))
344    {
345        // Player not create (race/class problem?)
346        delete pNewChar;
347
348        data << (uint8)CHAR_CREATE_ERROR;
349        SendPacket( &data );
350
351        return;
352    }
353
354    if(have_same_race && skipCinematics == 1 || skipCinematics == 2)
355        pNewChar->setCinematic(1);                          // not show intro
356
357    // Player created, save it now
358    pNewChar->SaveToDB();
359    charcount+=1;
360
361    loginDatabase.PExecute("DELETE FROM realmcharacters WHERE acctid= '%d' AND realmid = '%d'", GetAccountId(), realmID);
362    loginDatabase.PExecute("INSERT INTO realmcharacters (numchars, acctid, realmid) VALUES (%u, %u, %u)",  charcount, GetAccountId(), realmID);
363
364    delete pNewChar;                                        // created only to call SaveToDB()
365
366    data << (uint8)CHAR_CREATE_SUCCESS;
367    SendPacket( &data );
368
369    std::string IP_str = GetRemoteAddress().c_str();
370    sLog.outBasic("Account: %d (IP: %s) Create Character:[%s]",GetAccountId(),IP_str.c_str(),name.c_str());
371    sLog.outChar("Account: %d (IP: %s) Create Character:[%s]",GetAccountId(),IP_str.c_str(),name.c_str());
372}
373
374void WorldSession::HandleCharDeleteOpcode( WorldPacket & recv_data )
375{
376    CHECK_PACKET_SIZE(recv_data,8);
377
378    uint64 guid;
379    recv_data >> guid;
380
381    // can't delete loaded character
382    if(objmgr.GetPlayer(guid))
383        return;
384
385    uint32 accountId = 0;
386    std::string name;
387
388    // is guild leader
389    if(objmgr.GetGuildByLeader(guid))
390    {
391        WorldPacket data(SMSG_CHAR_DELETE, 1);
392        data << (uint8)CHAR_DELETE_FAILED_GUILD_LEADER;
393        SendPacket( &data );
394        return;
395    }
396
397    // is arena team captain
398    if(objmgr.GetArenaTeamByCapitan(guid))
399    {
400        WorldPacket data(SMSG_CHAR_DELETE, 1);
401        data << (uint8)CHAR_DELETE_FAILED_ARENA_CAPTAIN;
402        SendPacket( &data );
403        return;
404    }
405
406    QueryResult *result = CharacterDatabase.PQuery("SELECT account,name FROM characters WHERE guid='%u'", GUID_LOPART(guid));
407    if(result)
408    {
409        Field *fields = result->Fetch();
410        accountId = fields[0].GetUInt32();
411        name = fields[1].GetCppString();
412        delete result;
413    }
414
415    // prevent deleting other players' characters using cheating tools
416    if(accountId != GetAccountId())
417        return;
418
419    std::string IP_str = GetRemoteAddress();
420    sLog.outBasic("Account: %d (IP: %s) Delete Character:[%s] (guid:%u)",GetAccountId(),IP_str.c_str(),name.c_str(),GUID_LOPART(guid));
421    sLog.outChar("Account: %d (IP: %s) Delete Character:[%s] (guid: %u)",GetAccountId(),IP_str.c_str(),name.c_str(),GUID_LOPART(guid));
422
423    if(sLog.IsOutCharDump())                                // optimize GetPlayerDump call
424    {
425        std::string dump = PlayerDumpWriter().GetDump(GUID_LOPART(guid));
426        sLog.outCharDump(dump.c_str(),GetAccountId(),GUID_LOPART(guid),name.c_str());
427    }
428
429    Player::DeleteFromDB(guid, GetAccountId());
430
431    WorldPacket data(SMSG_CHAR_DELETE, 1);
432    data << (uint8)CHAR_DELETE_SUCCESS;
433    SendPacket( &data );
434}
435
436void WorldSession::HandlePlayerLoginOpcode( WorldPacket & recv_data )
437{
438    CHECK_PACKET_SIZE(recv_data,8);
439
440    m_playerLoading = true;
441    uint64 playerGuid = 0;
442
443    DEBUG_LOG( "WORLD: Recvd Player Logon Message" );
444
445    recv_data >> playerGuid;
446
447    LoginQueryHolder *holder = new LoginQueryHolder(GetAccountId(), playerGuid);
448    if(!holder->Initialize())
449    {
450        delete holder;                                      // delete all unprocessed queries
451        m_playerLoading = false;
452        return;
453    }
454
455    CharacterDatabase.DelayQueryHolder(&chrHandler, &CharacterHandler::HandlePlayerLoginCallback, holder);
456}
457
458void WorldSession::HandlePlayerLogin(LoginQueryHolder * holder)
459{
460    uint64 playerGuid = holder->GetGuid();
461
462    Player* pCurrChar = new Player(this);
463    pCurrChar->GetMotionMaster()->Initialize();
464
465    // "GetAccountId()==db stored account id" checked in LoadFromDB (prevent login not own character using cheating tools)
466    if(!pCurrChar->LoadFromDB(GUID_LOPART(playerGuid), holder))
467    {
468        KickPlayer();                                       // disconnect client, player no set to session and it will not deleted or saved at kick
469        delete pCurrChar;                                   // delete it manually
470        delete holder;                                      // delete all unprocessed queries
471        m_playerLoading = false;
472        return;
473    }
474
475    SetPlayer(pCurrChar);
476
477    pCurrChar->SendDungeonDifficulty(false);
478
479    WorldPacket data( SMSG_LOGIN_VERIFY_WORLD, 20 );
480    data << pCurrChar->GetMapId();
481    data << pCurrChar->GetPositionX();
482    data << pCurrChar->GetPositionY();
483    data << pCurrChar->GetPositionZ();
484    data << pCurrChar->GetOrientation();
485    SendPacket(&data);
486
487    data.Initialize( SMSG_ACCOUNT_DATA_TIMES, 128 );
488    for(int i = 0; i < 32; i++)
489        data << uint32(0);
490    SendPacket(&data);
491
492    data.Initialize(SMSG_FEATURE_SYSTEM_STATUS, 2);         // added in 2.2.0
493    data << uint8(2);                                       // unknown value
494    data << uint8(0);                                       // enable(1)/disable(0) voice chat interface in client
495    SendPacket(&data);
496
497    // Send MOTD
498    {
499        data.Initialize(SMSG_MOTD, 50);                     // new in 2.0.1
500        data << (uint32)0;
501
502        uint32 linecount=0;
503        std::string str_motd = sWorld.GetMotd();
504        std::string::size_type pos, nextpos;
505
506        pos = 0;
507        while ( (nextpos= str_motd.find('@',pos)) != std::string::npos )
508        {
509            if (nextpos != pos)
510            {
511                data << str_motd.substr(pos,nextpos-pos);
512                ++linecount;
513            }
514            pos = nextpos+1;
515        }
516
517        if (pos<str_motd.length())
518        {
519            data << str_motd.substr(pos);
520            ++linecount;
521        }
522
523        data.put(0, linecount);
524
525        SendPacket( &data );
526        DEBUG_LOG( "WORLD: Sent motd (SMSG_MOTD)" );
527    }
528
529    if(pCurrChar->GetGuildId() != 0)
530    {
531        Guild* guild = objmgr.GetGuildById(pCurrChar->GetGuildId());
532        if(guild)
533        {
534            data.Initialize(SMSG_GUILD_EVENT, (2+guild->GetMOTD().size()+1));
535            data << (uint8)GE_MOTD;
536            data << (uint8)1;
537            data << guild->GetMOTD();
538            SendPacket(&data);
539            DEBUG_LOG( "WORLD: Sent guild-motd (SMSG_GUILD_EVENT)" );
540
541            data.Initialize(SMSG_GUILD_EVENT, (5+10));      // we guess size
542            data<<(uint8)GE_SIGNED_ON;
543            data<<(uint8)1;
544            data<<pCurrChar->GetName();
545            data<<pCurrChar->GetGUID();
546            guild->BroadcastPacket(&data);
547            DEBUG_LOG( "WORLD: Sent guild-signed-on (SMSG_GUILD_EVENT)" );
548
549            // Increment online members of the guild
550            guild->IncOnlineMemberCount();
551        }
552        else
553        {
554            // remove wrong guild data
555            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());
556            pCurrChar->SetUInt32Value(PLAYER_GUILDID,0);
557            pCurrChar->SetUInt32ValueInDB(PLAYER_GUILDID,0,pCurrChar->GetGUID());
558        }
559    }
560
561    if(!pCurrChar->isAlive())
562        pCurrChar->SendCorpseReclaimDelay(true);
563
564    pCurrChar->SendInitialPacketsBeforeAddToMap();
565
566    //Show cinematic at the first time that player login
567    if( !pCurrChar->getCinematic() )
568    {
569        pCurrChar->setCinematic(1);
570
571        ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(pCurrChar->getRace());
572        if(rEntry)
573        {
574            data.Initialize( SMSG_TRIGGER_CINEMATIC,4 );
575            data << uint32(rEntry->startmovie);
576            SendPacket( &data );
577        }
578    }
579
580    //QueryResult *result = CharacterDatabase.PQuery("SELECT guildid,rank FROM guild_member WHERE guid = '%u'",pCurrChar->GetGUIDLow());
581    QueryResult *resultGuild = holder->GetResult(PLAYER_LOGIN_QUERY_LOADGUILD);
582
583    if(resultGuild)
584    {
585        Field *fields = resultGuild->Fetch();
586        pCurrChar->SetInGuild(fields[0].GetUInt32());
587        pCurrChar->SetRank(fields[1].GetUInt32());
588        delete resultGuild;
589    }
590    else if(pCurrChar->GetGuildId())                        // clear guild related fields in case wrong data about non existed membership
591    {
592        pCurrChar->SetInGuild(0);
593        pCurrChar->SetRank(0);
594    }
595
596    if (!MapManager::Instance().GetMap(pCurrChar->GetMapId(), pCurrChar)->Add(pCurrChar))
597    {
598        AreaTrigger const* at = objmgr.GetGoBackTrigger(pCurrChar->GetMapId());
599        if(at)
600            pCurrChar->TeleportTo(at->target_mapId, at->target_X, at->target_Y, at->target_Z, pCurrChar->GetOrientation());
601        else
602            pCurrChar->TeleportTo(pCurrChar->m_homebindMapId, pCurrChar->m_homebindX, pCurrChar->m_homebindY, pCurrChar->m_homebindZ, pCurrChar->GetOrientation());
603    }
604
605    ObjectAccessor::Instance().AddObject(pCurrChar);
606    //sLog.outDebug("Player %s added to Map.",pCurrChar->GetName());
607    pCurrChar->GetSocial()->SendSocialList();
608
609    pCurrChar->SendInitialPacketsAfterAddToMap();
610
611    CharacterDatabase.PExecute("UPDATE characters SET online = 1 WHERE guid = '%u'", pCurrChar->GetGUIDLow());
612    loginDatabase.PExecute("UPDATE account SET online = 1 WHERE id = '%u'", GetAccountId());
613    pCurrChar->SetInGameTime( getMSTime() );
614
615    // announce group about member online (must be after add to player list to receive announce to self)
616    if(Group *group = pCurrChar->GetGroup())
617    {
618        //pCurrChar->groupInfo.group->SendInit(this); // useless
619        group->SendUpdate();
620    }
621
622    // friend status
623    sSocialMgr.SendFriendStatus(pCurrChar, FRIEND_ONLINE, pCurrChar->GetGUIDLow(), "", true);
624
625    // Place character in world (and load zone) before some object loading
626    pCurrChar->LoadCorpse();
627
628    // setting Ghost+speed if dead
629    //if ( pCurrChar->m_deathState == DEAD )
630    if (pCurrChar->m_deathState != ALIVE)
631    {
632        // not blizz like, we must correctly save and load player instead...
633        if(pCurrChar->getRace() == RACE_NIGHTELF)
634            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)
635        pCurrChar->CastSpell(pCurrChar, 8326, true, 0);     // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
636
637        //pCurrChar->SetUInt32Value(UNIT_FIELD_AURA+41, 8326);
638        //pCurrChar->SetUInt32Value(UNIT_FIELD_AURA+42, 20584);
639        //pCurrChar->SetUInt32Value(UNIT_FIELD_AURAFLAGS+6, 238);
640        //pCurrChar->SetUInt32Value(UNIT_FIELD_AURALEVELS+11, 514);
641        //pCurrChar->SetUInt32Value(UNIT_FIELD_AURAAPPLICATIONS+11, 65535);
642        //pCurrChar->SetUInt32Value(UNIT_FIELD_DISPLAYID, 1825);
643        //if (pCurrChar->getRace() == RACE_NIGHTELF)
644        //{
645        //    pCurrChar->SetSpeed(MOVE_RUN,  1.5f*1.2f, true);
646        //    pCurrChar->SetSpeed(MOVE_SWIM, 1.5f*1.2f, true);
647        //}
648        //else
649        //{
650        //    pCurrChar->SetSpeed(MOVE_RUN,  1.5f, true);
651        //    pCurrChar->SetSpeed(MOVE_SWIM, 1.5f, true);
652        //}
653        pCurrChar->SetMovement(MOVE_WATER_WALK);
654    }
655
656    if(uint32 sourceNode = pCurrChar->m_taxi.GetTaxiSource())
657    {
658
659        sLog.outDebug( "WORLD: Restart character %u taxi flight", pCurrChar->GetGUIDLow() );
660
661        uint32 MountId = objmgr.GetTaxiMount(sourceNode, pCurrChar->GetTeam());
662        uint32 path = pCurrChar->m_taxi.GetCurrentTaxiPath();
663
664        // search appropriate start path node
665        uint32 startNode = 0;
666
667        TaxiPathNodeList const& nodeList = sTaxiPathNodesByPath[path];
668
669        float distPrev = MAP_SIZE*MAP_SIZE;
670        float distNext =
671            (nodeList[0].x-pCurrChar->GetPositionX())*(nodeList[0].x-pCurrChar->GetPositionX())+
672            (nodeList[0].y-pCurrChar->GetPositionY())*(nodeList[0].y-pCurrChar->GetPositionY())+
673            (nodeList[0].z-pCurrChar->GetPositionZ())*(nodeList[0].z-pCurrChar->GetPositionZ());
674
675        for(uint32 i = 1; i < nodeList.size(); ++i)
676        {
677            TaxiPathNode const& node = nodeList[i];
678            TaxiPathNode const& prevNode = nodeList[i-1];
679
680            // skip nodes at another map
681            if(node.mapid != pCurrChar->GetMapId())
682                continue;
683
684            distPrev = distNext;
685
686            distNext =
687                (node.x-pCurrChar->GetPositionX())*(node.x-pCurrChar->GetPositionX())+
688                (node.y-pCurrChar->GetPositionY())*(node.y-pCurrChar->GetPositionY())+
689                (node.z-pCurrChar->GetPositionZ())*(node.z-pCurrChar->GetPositionZ());
690
691            float distNodes =
692                (node.x-prevNode.x)*(node.x-prevNode.x)+
693                (node.y-prevNode.y)*(node.y-prevNode.y)+
694                (node.z-prevNode.z)*(node.z-prevNode.z);
695
696            if(distNext + distPrev < distNodes)
697            {
698                startNode = i;
699                break;
700            }
701        }
702
703        SendDoFlight( MountId, path, startNode );
704    }
705
706    // Load pet if any and player is alive and not in taxi flight
707    if(pCurrChar->isAlive() && pCurrChar->m_taxi.GetTaxiSource()==0)
708        pCurrChar->LoadPet();
709
710    // Set FFA PvP for non GM in non-rest mode
711    if(sWorld.IsFFAPvPRealm() && !pCurrChar->isGameMaster() && !pCurrChar->HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_RESTING) )
712        pCurrChar->SetFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
713
714    if(pCurrChar->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP))
715        pCurrChar->SetContestedPvP();
716
717    // Apply at_login requests
718    if(pCurrChar->HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
719    {
720        pCurrChar->resetSpells();
721        SendNotification("Spells has been reset.");
722    }
723
724    if(pCurrChar->HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
725    {
726        pCurrChar->resetTalents(true);
727        SendNotification("Talents has been reset.");
728    }
729
730    // show time before shutdown if shutdown planned.
731    if(sWorld.IsShutdowning())
732        sWorld.ShutdownMsg(true,pCurrChar);
733
734    if(pCurrChar->isGameMaster())
735        SendNotification("GM mode is ON");
736
737    std::string IP_str = GetRemoteAddress();
738    sLog.outChar("Account: %d (IP: %s) Login Character:[%s] (guid:%u)",GetAccountId(),IP_str.c_str(),pCurrChar->GetName() ,pCurrChar->GetGUID());
739
740    m_playerLoading = false;
741    delete holder;
742}
743
744void WorldSession::HandleSetFactionAtWar( WorldPacket & recv_data )
745{
746    CHECK_PACKET_SIZE(recv_data,4+1);
747
748    DEBUG_LOG( "WORLD: Received CMSG_SET_FACTION_ATWAR" );
749
750    uint32 repListID;
751    uint8  flag;
752
753    recv_data >> repListID;
754    recv_data >> flag;
755
756    FactionStateList::iterator itr = GetPlayer()->m_factions.find(repListID);
757    if (itr == GetPlayer()->m_factions.end())
758        return;
759
760    // always invisible or hidden faction can't change war state
761    if(itr->second.Flags & (FACTION_FLAG_INVISIBLE_FORCED|FACTION_FLAG_HIDDEN) )
762        return;
763
764    GetPlayer()->SetFactionAtWar(&itr->second,flag);
765}
766
767//I think this function is never used :/ I dunno, but i guess this opcode not exists
768void WorldSession::HandleSetFactionCheat( WorldPacket & /*recv_data*/ )
769{
770    //CHECK_PACKET_SIZE(recv_data,4+4);
771
772    //sLog.outDebug("WORLD SESSION: HandleSetFactionCheat");
773    /*
774        uint32 FactionID;
775        uint32 Standing;
776
777        recv_data >> FactionID;
778        recv_data >> Standing;
779
780        std::list<struct Factions>::iterator itr;
781
782        for(itr = GetPlayer()->factions.begin(); itr != GetPlayer()->factions.end(); ++itr)
783        {
784            if(itr->ReputationListID == FactionID)
785            {
786                itr->Standing += Standing;
787                itr->Flags = (itr->Flags | 1);
788                break;
789            }
790        }
791    */
792    GetPlayer()->UpdateReputation();
793}
794
795void WorldSession::HandleMeetingStoneInfo( WorldPacket & /*recv_data*/ )
796{
797    DEBUG_LOG( "WORLD: Received CMSG_MEETING_STONE_INFO" );
798
799    WorldPacket data(SMSG_MEETINGSTONE_SETQUEUE, 5);
800    data << uint32(0) << uint8(6);
801    SendPacket(&data);
802}
803
804void WorldSession::HandleTutorialFlag( WorldPacket & recv_data )
805{
806    CHECK_PACKET_SIZE(recv_data,4);
807
808    uint32 iFlag;
809    recv_data >> iFlag;
810
811    uint32 wInt = (iFlag / 32);
812    if (wInt >= 8)
813    {
814        //sLog.outError("CHEATER? Account:[%d] Guid[%u] tried to send wrong CMSG_TUTORIAL_FLAG", GetAccountId(),GetGUID());
815        return;
816    }
817    uint32 rInt = (iFlag % 32);
818
819    uint32 tutflag = GetPlayer()->GetTutorialInt( wInt );
820    tutflag |= (1 << rInt);
821    GetPlayer()->SetTutorialInt( wInt, tutflag );
822
823    //sLog.outDebug("Received Tutorial Flag Set {%u}.", iFlag);
824}
825
826void WorldSession::HandleTutorialClear( WorldPacket & /*recv_data*/ )
827{
828    for ( uint32 iI = 0; iI < 8; iI++)
829        GetPlayer()->SetTutorialInt( iI, 0xFFFFFFFF );
830}
831
832void WorldSession::HandleTutorialReset( WorldPacket & /*recv_data*/ )
833{
834    for ( uint32 iI = 0; iI < 8; iI++)
835        GetPlayer()->SetTutorialInt( iI, 0x00000000 );
836}
837
838void WorldSession::HandleSetWatchedFactionIndexOpcode(WorldPacket & recv_data)
839{
840    CHECK_PACKET_SIZE(recv_data,4);
841
842    DEBUG_LOG("WORLD: Received CMSG_SET_WATCHED_FACTION");
843    uint32 fact;
844    recv_data >> fact;
845    GetPlayer()->SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, fact);
846}
847
848void WorldSession::HandleSetWatchedFactionInactiveOpcode(WorldPacket & recv_data)
849{
850    CHECK_PACKET_SIZE(recv_data,4+1);
851
852    DEBUG_LOG("WORLD: Received CMSG_SET_FACTION_INACTIVE");
853    uint32 replistid;
854    uint8 inactive;
855    recv_data >> replistid >> inactive;
856
857    FactionStateList::iterator itr = _player->m_factions.find(replistid);
858    if (itr == _player->m_factions.end())
859        return;
860
861    _player->SetFactionInactive(&itr->second, inactive);
862}
863
864void WorldSession::HandleToggleHelmOpcode( WorldPacket & /*recv_data*/ )
865{
866    DEBUG_LOG("CMSG_TOGGLE_HELM for %s", _player->GetName());
867    _player->ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM);
868}
869
870void WorldSession::HandleToggleCloakOpcode( WorldPacket & /*recv_data*/ )
871{
872    DEBUG_LOG("CMSG_TOGGLE_CLOAK for %s", _player->GetName());
873    _player->ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK);
874}
875
876void WorldSession::HandleChangePlayerNameOpcode(WorldPacket& recv_data)
877{
878    CHECK_PACKET_SIZE(recv_data,8+1);
879
880    uint64 guid;
881    std::string newname;
882    std::string oldname;
883
884    CHECK_PACKET_SIZE(recv_data, 8+1);
885
886    recv_data >> guid;
887    recv_data >> newname;
888
889    QueryResult *result = CharacterDatabase.PQuery("SELECT at_login FROM characters WHERE guid ='%u'", GUID_LOPART(guid));
890    if (result)
891    {
892        uint32 at_loginFlags;
893        Field *fields = result->Fetch();
894        at_loginFlags = fields[0].GetUInt32();
895        delete result;
896
897        if (!(at_loginFlags & AT_LOGIN_RENAME))
898        {
899            WorldPacket data(SMSG_CHAR_RENAME, 1);
900            data << (uint8)CHAR_CREATE_ERROR;
901            SendPacket( &data );
902            return;
903        }
904    }
905    else
906    {
907        WorldPacket data(SMSG_CHAR_RENAME, 1);
908        data << (uint8)CHAR_CREATE_ERROR;
909        SendPacket( &data );
910        return;
911    }
912
913    if(!objmgr.GetPlayerNameByGUID(guid, oldname))          // character not exist, because we have no name for this guid
914    {
915        WorldPacket data(SMSG_CHAR_RENAME, 1);
916        data << (uint8)CHAR_LOGIN_NO_CHARACTER;
917        SendPacket( &data );
918        return;
919    }
920
921    // prevent character rename to invalid name
922    if(!normalizePlayerName(newname))
923    {
924        WorldPacket data(SMSG_CHAR_RENAME, 1);
925        data << (uint8)CHAR_NAME_NO_NAME;
926        SendPacket( &data );
927        return;
928    }
929
930    if(!ObjectMgr::IsValidName(newname,true))
931    {
932        WorldPacket data(SMSG_CHAR_RENAME, 1);
933        data << (uint8)CHAR_NAME_INVALID_CHARACTER;
934        SendPacket( &data );
935        return;
936    }
937
938    // check name limitations
939    if(GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(newname))
940    {
941        WorldPacket data(SMSG_CHAR_RENAME, 1);
942        data << (uint8)CHAR_NAME_RESERVED;
943        SendPacket( &data );
944        return;
945    }
946
947    if(objmgr.GetPlayerGUIDByName(newname))                 // character with this name already exist
948    {
949        WorldPacket data(SMSG_CHAR_RENAME, 1);
950        data << (uint8)CHAR_CREATE_ERROR;
951        SendPacket( &data );
952        return;
953    }
954
955    if(newname == oldname)                                  // checked by client
956    {
957        WorldPacket data(SMSG_CHAR_RENAME, 1);
958        data << (uint8)CHAR_NAME_FAILURE;
959        SendPacket( &data );
960        return;
961    }
962
963    // we have to check character at_login_flag & AT_LOGIN_RENAME also (fake packets hehe)
964
965    CharacterDatabase.escape_string(newname);
966    CharacterDatabase.PExecute("UPDATE characters set name = '%s', at_login = at_login & ~ %u WHERE guid ='%u'", newname.c_str(), uint32(AT_LOGIN_RENAME),GUID_LOPART(guid));
967    CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid ='%u'", GUID_LOPART(guid));
968
969    std::string IP_str = GetRemoteAddress();
970    sLog.outChar("Account: %d (IP: %s) Character:[%s] (guid:%u) Changed name to: %s",GetAccountId(),IP_str.c_str(),oldname.c_str(),GUID_LOPART(guid),newname.c_str());
971
972    WorldPacket data(SMSG_CHAR_RENAME,1+8+(newname.size()+1));
973    data << (uint8)RESPONSE_SUCCESS;
974    data << guid;
975    data << newname;
976    SendPacket(&data);
977}
978
979void WorldSession::HandleDeclinedPlayerNameOpcode(WorldPacket& recv_data)
980{
981    uint64 guid;
982
983    CHECK_PACKET_SIZE(recv_data, 8+6);
984    recv_data >> guid;
985
986    // not accept declined names for unsupported languages
987    std::string name;
988    if(!objmgr.GetPlayerNameByGUID(guid,name))
989    {
990        WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT,4+8);
991        data << (uint32)1;
992        data << guid;
993        SendPacket(&data);
994        return;
995    }
996
997    std::wstring wname;
998    if(!Utf8toWStr(name,wname))
999    {
1000        WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT,4+8);
1001        data << (uint32)1;
1002        data << guid;
1003        SendPacket(&data);
1004        return;
1005    }
1006
1007    if(!isCyrillicCharacter(wname[0]))                      // name already stored as only single alphabet using
1008    {
1009        WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT,4+8);
1010        data << (uint32)1;
1011        data << guid;
1012        SendPacket(&data);
1013        return;
1014    }
1015
1016    std::string name2;
1017    DeclinedName declinedname;
1018
1019    recv_data >> name2;
1020
1021    if(name2!=name)                                         // character have different name
1022    {
1023        WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT,4+8);
1024        data << (uint32)1;
1025        data << guid;
1026        SendPacket(&data);
1027        return;
1028    }
1029
1030    for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
1031    {
1032        recv_data >> declinedname.name[i];
1033        if(!normalizePlayerName(declinedname.name[i]))
1034        {
1035            WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT,4+8);
1036            data << (uint32)1;
1037            data << guid;
1038            SendPacket(&data);
1039            return;
1040        }
1041    }
1042
1043    if(!ObjectMgr::CheckDeclinedNames(GetMainPartOfName(wname,0),declinedname))
1044    {
1045        WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT,4+8);
1046        data << (uint32)1;
1047        data << guid;
1048        SendPacket(&data);
1049        return;
1050    }
1051
1052    for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
1053        CharacterDatabase.escape_string(declinedname.name[i]);
1054
1055    CharacterDatabase.BeginTransaction();
1056    CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'", GUID_LOPART(guid));
1057    CharacterDatabase.PExecute("INSERT INTO character_declinedname (guid, genitive, dative, accusative, instrumental, prepositional) VALUES ('%u','%s','%s','%s','%s','%s')",
1058        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());
1059    CharacterDatabase.CommitTransaction();
1060
1061    WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT,4+8);
1062    data << (uint32)0;                                      // OK
1063    data << guid;
1064    SendPacket(&data);
1065}
Note: See TracBrowser for help on using the browser.