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

Revision 279, 39.2 kB (checked in by yumileroy, 17 years ago)

Merged commit 269 (5f0e38da128a).

Original author: gvcoman
Date: 2008-11-21 14:34:05-05:00

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