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

Revision 44, 38.5 kB (checked in by yumileroy, 17 years ago)

[svn] * Merge Temp dev SVN with Assembla.
* Changes include:

  • Implementation of w12x's Outdoor PvP and Game Event Systems.
  • Temporary removal of IRC Chat Bot (until infinite loop when disabled is fixed).
  • All mangos -> trinity (to convert your mangos_string table, please run mangos_string_to_trinity_string.sql).
  • Improved Config cleanup.
  • And many more changes.

Original author: Seline
Date: 2008-10-14 11:57:03-05:00

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