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

Revision 173, 39.1 kB (checked in by yumileroy, 17 years ago)

[svn] * Avoid access to bag item prototype for getting bag size, use related item update field instead as more fast source.
* Better check client inventory pos data received in some client packets to skip invalid cases.
* Removed some unnecessary database queries.
* Make guid lookup for adding ignore async.
* Added two parameter versions of the AsyncQuery? function
* Make queries for adding friends async. - Hunuza
* Replace some PQuery() calls with more simple Query() - Hunuza
* Mark spell as executed instead of deleteable to solve crash.
*** Source mangos.

**Its a big commit. so test with care... or without care.... whatever floats your boat.

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