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

Revision 173, 56.7 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 "Language.h"
23#include "Database/DatabaseEnv.h"
24#include "Database/DatabaseImpl.h"
25#include "WorldPacket.h"
26#include "Opcodes.h"
27#include "Log.h"
28#include "Player.h"
29#include "World.h"
30#include "ObjectMgr.h"
31#include "WorldSession.h"
32#include "Auth/BigNumber.h"
33#include "Auth/Sha1.h"
34#include "UpdateData.h"
35#include "LootMgr.h"
36#include "Chat.h"
37#include "ScriptCalls.h"
38#include <zlib/zlib.h>
39#include "MapManager.h"
40#include "ObjectAccessor.h"
41#include "Object.h"
42#include "BattleGround.h"
43#include "OutdoorPvP.h"
44#include "SpellAuras.h"
45#include "Pet.h"
46#include "SocialMgr.h"
47
48void WorldSession::HandleRepopRequestOpcode( WorldPacket & /*recv_data*/ )
49{
50    sLog.outDebug( "WORLD: Recvd CMSG_REPOP_REQUEST Message" );
51
52    if(GetPlayer()->isAlive()||GetPlayer()->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
53        return;
54
55    // the world update order is sessions, players, creatures
56    // the netcode runs in parallel with all of these
57    // creatures can kill players
58    // so if the server is lagging enough the player can
59    // release spirit after he's killed but before he is updated
60    if(GetPlayer()->getDeathState() == JUST_DIED)
61    {
62        sLog.outDebug("HandleRepopRequestOpcode: got request after player %s(%d) was killed and before he was updated", GetPlayer()->GetName(), GetPlayer()->GetGUIDLow());
63        GetPlayer()->KillPlayer();
64    }
65
66    //this is spirit release confirm?
67    GetPlayer()->RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
68    GetPlayer()->BuildPlayerRepop();
69    GetPlayer()->RepopAtGraveyard();
70}
71
72void WorldSession::HandleWhoOpcode( WorldPacket & recv_data )
73{
74    CHECK_PACKET_SIZE(recv_data,4+4+1+1+4+4+4+4);
75
76    sLog.outDebug( "WORLD: Recvd CMSG_WHO Message" );
77    //recv_data.hexlike();
78
79    uint32 clientcount = 0;
80
81    uint32 level_min, level_max, racemask, classmask, zones_count, str_count;
82    uint32 zoneids[10];                                     // 10 is client limit
83    std::string player_name, guild_name;
84
85    recv_data >> level_min;                                 // maximal player level, default 0
86    recv_data >> level_max;                                 // minimal player level, default 100
87    recv_data >> player_name;                               // player name, case sensitive...
88
89    // recheck
90    CHECK_PACKET_SIZE(recv_data,4+4+(player_name.size()+1)+1+4+4+4+4);
91
92    recv_data >> guild_name;                                // guild name, case sensitive...
93
94    // recheck
95    CHECK_PACKET_SIZE(recv_data,4+4+(player_name.size()+1)+(guild_name.size()+1)+4+4+4+4);
96
97    recv_data >> racemask;                                  // race mask
98    recv_data >> classmask;                                 // class mask
99    recv_data >> zones_count;                               // zones count, client limit=10 (2.0.10)
100
101    if(zones_count > 10)
102        return;                                             // can't be received from real client or broken packet
103
104    // recheck
105    CHECK_PACKET_SIZE(recv_data,4+4+(player_name.size()+1)+(guild_name.size()+1)+4+4+4+(4*zones_count)+4);
106
107    for(uint32 i = 0; i < zones_count; i++)
108    {
109        uint32 temp;
110        recv_data >> temp;                                  // zone id, 0 if zone is unknown...
111        zoneids[i] = temp;
112        sLog.outDebug("Zone %u: %u", i, zoneids[i]);
113    }
114
115    recv_data >> str_count;                                 // user entered strings count, client limit=4 (checked on 2.0.10)
116
117    if(str_count > 4)
118        return;                                             // can't be received from real client or broken packet
119
120    // recheck
121    CHECK_PACKET_SIZE(recv_data,4+4+(player_name.size()+1)+(guild_name.size()+1)+4+4+4+(4*zones_count)+4+(1*str_count));
122
123    sLog.outDebug("Minlvl %u, maxlvl %u, name %s, guild %s, racemask %u, classmask %u, zones %u, strings %u", level_min, level_max, player_name.c_str(), guild_name.c_str(), racemask, classmask, zones_count, str_count);
124
125    std::wstring str[4];                                    // 4 is client limit
126    for(uint32 i = 0; i < str_count; i++)
127    {
128        // recheck (have one more byte)
129        CHECK_PACKET_SIZE(recv_data,recv_data.rpos());
130
131        std::string temp;
132        recv_data >> temp;                                  // user entered string, it used as universal search pattern(guild+player name)?
133
134        if(!Utf8toWStr(temp,str[i]))
135            continue;
136
137        wstrToLower(str[i]);
138
139        sLog.outDebug("String %u: %s", i, str[i].c_str());
140    }
141
142    std::wstring wplayer_name;
143    std::wstring wguild_name;
144    if(!(Utf8toWStr(player_name, wplayer_name) && Utf8toWStr(guild_name, wguild_name)))
145        return;
146    wstrToLower(wplayer_name);
147    wstrToLower(wguild_name);
148
149    // client send in case not set max level value 100 but Trinity support 255 max level,
150    // update it to show GMs with characters after 100 level
151    if(level_max >= 100)
152        level_max = 255;
153
154    uint32 team = _player->GetTeam();
155    uint32 security = GetSecurity();
156    bool allowTwoSideWhoList = sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_WHO_LIST);
157    bool gmInWhoList         = sWorld.getConfig(CONFIG_GM_IN_WHO_LIST);
158
159    WorldPacket data( SMSG_WHO, 50 );                       // guess size
160    data << clientcount;                                    // clientcount place holder
161    data << clientcount;                                    // clientcount place holder
162
163    //TODO: Guard Player map
164    HashMapHolder<Player>::MapType& m = ObjectAccessor::Instance().GetPlayers();
165    for(HashMapHolder<Player>::MapType::iterator itr = m.begin(); itr != m.end(); ++itr)
166    {
167        if (security == SEC_PLAYER)
168        {
169            // player can see member of other team only if CONFIG_ALLOW_TWO_SIDE_WHO_LIST
170            if (itr->second->GetTeam() != team && !allowTwoSideWhoList )
171                continue;
172
173            // player can see MODERATOR, GAME MASTER, ADMINISTRATOR only if CONFIG_GM_IN_WHO_LIST
174            if ((itr->second->GetSession()->GetSecurity() > SEC_PLAYER && !gmInWhoList))
175                continue;
176        }
177
178        // check if target is globally visible for player
179        if (!(itr->second->IsVisibleGloballyFor(_player)))
180            continue;
181
182        // check if target's level is in level range
183        uint32 lvl = itr->second->getLevel();
184        if (lvl < level_min || lvl > level_max)
185            continue;
186
187        // check if class matches classmask
188        uint32 class_ = itr->second->getClass();
189        if (!(classmask & (1 << class_)))
190            continue;
191
192        // check if race matches racemask
193        uint32 race = itr->second->getRace();
194        if (!(racemask & (1 << race)))
195            continue;
196
197        uint32 pzoneid = itr->second->GetZoneId();
198
199        bool z_show = true;
200        for(uint32 i = 0; i < zones_count; i++)
201        {
202            if(zoneids[i] == pzoneid)
203            {
204                z_show = true;
205                break;
206            }
207
208            z_show = false;
209        }
210        if (!z_show)
211            continue;
212
213        std::string pname = itr->second->GetName();
214        std::wstring wpname;
215        if(!Utf8toWStr(pname,wpname))
216            continue;
217        wstrToLower(wpname);
218
219        if (!(wplayer_name.empty() || wpname.find(wplayer_name) != std::wstring::npos))
220            continue;
221
222        std::string gname = objmgr.GetGuildNameById(itr->second->GetGuildId());
223        std::wstring wgname;
224        if(!Utf8toWStr(gname,wgname))
225            continue;
226        wstrToLower(wgname);
227
228        if (!(wguild_name.empty() || wgname.find(wguild_name) != std::wstring::npos))
229            continue;
230
231        std::string aname;
232        if(AreaTableEntry const* areaEntry = GetAreaEntryByAreaID(itr->second->GetZoneId()))
233            aname = areaEntry->area_name[GetSessionDbcLocale()];
234
235        bool s_show = true;
236        for(uint32 i = 0; i < str_count; i++)
237        {
238            if (!str[i].empty())
239            {
240                if (wgname.find(str[i]) != std::wstring::npos ||
241                    wpname.find(str[i]) != std::wstring::npos ||
242                    Utf8FitTo(aname, str[i]) )
243                {
244                    s_show = true;
245                    break;
246                }
247                s_show = false;
248            }
249        }
250        if (!s_show)
251            continue;
252
253        data << pname;                                      // player name
254        data << gname;                                      // guild name
255        data << uint32( lvl );                              // player level
256        data << uint32( class_ );                           // player class
257        data << uint32( race );                             // player race
258        data << uint8(0);                                   // new 2.4.0
259        data << uint32( pzoneid );                          // player zone id
260
261        // 49 is maximum player count sent to client - can be overriden
262        // through config, but is unstable
263        if ((++clientcount) == sWorld.getConfig(CONFIG_MAX_WHO))
264            break;
265    }
266
267    data.put( 0,              clientcount );                //insert right count
268    data.put( sizeof(uint32), clientcount );                //insert right count
269
270    SendPacket(&data);
271    sLog.outDebug( "WORLD: Send SMSG_WHO Message" );
272}
273
274void WorldSession::HandleLogoutRequestOpcode( WorldPacket & /*recv_data*/ )
275{
276    sLog.outDebug( "WORLD: Recvd CMSG_LOGOUT_REQUEST Message, security - %u", GetSecurity() );
277
278    if (uint64 lguid = GetPlayer()->GetLootGUID())
279        DoLootRelease(lguid);
280
281    //instant logout for admins, gm's, mod's
282    if( GetSecurity() > SEC_PLAYER )
283    {
284        LogoutPlayer(true);
285        return;
286    }
287
288    //Can not logout if...
289    if( GetPlayer()->isInCombat() ||                        //...is in combat
290        GetPlayer()->duel         ||                        //...is in Duel
291        GetPlayer()->HasAura(9454,0)         ||             //...is frozen by GM via freeze command
292                                                            //...is jumping ...is falling
293        GetPlayer()->HasUnitMovementFlag(MOVEMENTFLAG_JUMPING | MOVEMENTFLAG_FALLING))
294    {
295        WorldPacket data( SMSG_LOGOUT_RESPONSE, (2+4) ) ;
296        data << (uint8)0xC;
297        data << uint32(0);
298        data << uint8(0);
299        SendPacket( &data );
300        LogoutRequest(0);
301        return;
302    }
303
304    //instant logout in taverns/cities or on taxi or if its enabled in Trinityd.conf
305    if(GetPlayer()->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) || GetPlayer()->isInFlight() || sWorld.getConfig(CONFIG_INSTANT_LOGOUT))
306    {
307        LogoutPlayer(true);
308        return;
309    }
310
311    // not set flags if player can't free move to prevent lost state at logout cancel
312    if(GetPlayer()->CanFreeMove())
313    {
314        GetPlayer()->SetStandState(PLAYER_STATE_SIT);
315
316        WorldPacket data( SMSG_FORCE_MOVE_ROOT, (8+4) );    // guess size
317        data.append(GetPlayer()->GetPackGUID());
318        data << (uint32)2;
319        SendPacket( &data );
320        GetPlayer()->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_ROTATE);
321    }
322
323    WorldPacket data( SMSG_LOGOUT_RESPONSE, 5 );
324    data << uint32(0);
325    data << uint8(0);
326    SendPacket( &data );
327    LogoutRequest(time(NULL));
328}
329
330void WorldSession::HandlePlayerLogoutOpcode( WorldPacket & /*recv_data*/ )
331{
332    sLog.outDebug( "WORLD: Recvd CMSG_PLAYER_LOGOUT Message" );
333}
334
335void WorldSession::HandleLogoutCancelOpcode( WorldPacket & /*recv_data*/ )
336{
337    sLog.outDebug( "WORLD: Recvd CMSG_LOGOUT_CANCEL Message" );
338
339    LogoutRequest(0);
340
341    WorldPacket data( SMSG_LOGOUT_CANCEL_ACK, 0 );
342    SendPacket( &data );
343
344    // not remove flags if can't free move - its not set in Logout request code.
345    if(GetPlayer()->CanFreeMove())
346    {
347        //!we can move again
348        data.Initialize( SMSG_FORCE_MOVE_UNROOT, 8 );       // guess size
349        data.append(GetPlayer()->GetPackGUID());
350        data << uint32(0);
351        SendPacket( &data );
352
353        //! Stand Up
354        GetPlayer()->SetStandState(PLAYER_STATE_NONE);
355
356        //! DISABLE_ROTATE
357        GetPlayer()->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_ROTATE);
358    }
359
360    sLog.outDebug( "WORLD: sent SMSG_LOGOUT_CANCEL_ACK Message" );
361}
362
363void WorldSession::SendGMTicketGetTicket(uint32 status, char const* text)
364{
365    int len = text ? strlen(text) : 0;
366    WorldPacket data( SMSG_GMTICKET_GETTICKET, (4+len+1+4+2+4+4) );
367    data << uint32(status);                                 // standard 0x0A, 0x06 if text present
368    if(status == 6)
369    {
370        data << text;                                       // ticket text
371        data << uint8(0x7);                                 // ticket category
372        data << float(0);                                   // time from ticket creation?
373        data << float(0);                                   // const
374        data << float(0);                                   // const
375        data << uint8(0);                                   // const
376        data << uint8(0);                                   // const
377    }
378    SendPacket( &data );
379}
380
381void WorldSession::HandleGMTicketGetTicketOpcode( WorldPacket & /*recv_data*/ )
382{
383    WorldPacket data( SMSG_QUERY_TIME_RESPONSE, 4+4 );
384    data << (uint32)time(NULL);
385    data << (uint32)0;
386    SendPacket( &data );
387
388    uint64 guid;
389    Field *fields;
390    guid = GetPlayer()->GetGUID();
391
392    QueryResult *result = CharacterDatabase.PQuery("SELECT COUNT(ticket_id) FROM character_ticket WHERE guid = '%u'", GUID_LOPART(guid));
393
394    if (result)
395    {
396        int cnt;
397        fields = result->Fetch();
398        cnt = fields[0].GetUInt32();
399        delete result;
400
401        if ( cnt > 0 )
402        {
403            QueryResult *result2 = CharacterDatabase.PQuery("SELECT ticket_text FROM character_ticket WHERE guid = '%u'", GUID_LOPART(guid));
404            if(result2)
405            {
406                Field *fields2 = result2->Fetch();
407                SendGMTicketGetTicket(0x06,fields2[0].GetString());
408                delete result2;
409            }
410        }
411        else
412            SendGMTicketGetTicket(0x0A,0);
413    }
414}
415
416void WorldSession::HandleGMTicketUpdateTextOpcode( WorldPacket & recv_data )
417{
418    CHECK_PACKET_SIZE(recv_data,1);
419
420    std::string ticketText;
421    recv_data >> ticketText;
422
423    CharacterDatabase.escape_string(ticketText);
424    CharacterDatabase.PExecute("UPDATE character_ticket SET ticket_text = '%s' WHERE guid = '%u'", ticketText.c_str(), _player->GetGUIDLow());
425}
426
427void WorldSession::HandleGMTicketDeleteOpcode( WorldPacket & /*recv_data*/ )
428{
429    uint32 guid = GetPlayer()->GetGUIDLow();
430
431    CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u' LIMIT 1",guid);
432
433    WorldPacket data( SMSG_GMTICKET_DELETETICKET, 4 );
434    data << uint32(9);
435    SendPacket( &data );
436
437    SendGMTicketGetTicket(0x0A, 0);
438}
439
440void WorldSession::HandleGMTicketCreateOpcode( WorldPacket & recv_data )
441{
442    CHECK_PACKET_SIZE(recv_data, 4*4+1+2*4);
443
444    uint32 map;
445    float x, y, z;
446    std::string ticketText = "";
447    uint32 unk1, unk2;
448
449    recv_data >> map >> x >> y >> z;                        // last check 2.4.3
450    recv_data >> ticketText;
451
452    // recheck
453    CHECK_PACKET_SIZE(recv_data,4*4+(ticketText.size()+1)+2*4);
454
455    recv_data >> unk1 >> unk2;
456    // note: the packet might contain more data, but the exact structure of that is unknown
457
458    sLog.outDebug("TicketCreate: map %u, x %f, y %f, z %f, text %s, unk1 %u, unk2 %u", map, x, y, z, ticketText.c_str(), unk1, unk2);
459
460    CharacterDatabase.escape_string(ticketText);
461
462    QueryResult *result = CharacterDatabase.PQuery("SELECT COUNT(*) FROM character_ticket WHERE guid = '%u'", _player->GetGUIDLow());
463
464    if (result)
465    {
466        int cnt;
467        Field *fields = result->Fetch();
468        cnt = fields[0].GetUInt32();
469        delete result;
470
471        if ( cnt > 0 )
472        {
473            WorldPacket data( SMSG_GMTICKET_CREATE, 4 );
474            data << uint32(1);
475            SendPacket( &data );
476        }
477        else
478        {
479            CharacterDatabase.PExecute("INSERT INTO character_ticket (guid,ticket_text) VALUES ('%u', '%s')", _player->GetGUIDLow(), ticketText.c_str());
480
481            WorldPacket data( SMSG_QUERY_TIME_RESPONSE, 4+4 );
482            data << (uint32)time(NULL);
483            data << (uint32)0;
484            SendPacket( &data );
485
486            data.Initialize( SMSG_GMTICKET_CREATE, 4 );
487            data << uint32(2);
488            SendPacket( &data );
489            DEBUG_LOG("update the ticket\n");
490
491            //TODO: Guard player map
492            HashMapHolder<Player>::MapType &m = ObjectAccessor::Instance().GetPlayers();
493            for(HashMapHolder<Player>::MapType::iterator itr = m.begin(); itr != m.end(); ++itr)
494            {
495                if(itr->second->GetSession()->GetSecurity() >= SEC_GAMEMASTER && itr->second->isAcceptTickets())
496                    ChatHandler(itr->second).PSendSysMessage(LANG_COMMAND_TICKETNEW,GetPlayer()->GetName());
497            }
498        }
499    }
500}
501
502void WorldSession::HandleGMTicketSystemStatusOpcode( WorldPacket & /*recv_data*/ )
503{
504    WorldPacket data( SMSG_GMTICKET_SYSTEMSTATUS,4 );
505    data << uint32(1);                                      // we can also disable ticket system by sending 0 value
506
507    SendPacket( &data );
508}
509
510void WorldSession::HandleGMSurveySubmit( WorldPacket & recv_data)
511{
512    // GM survey is shown after SMSG_GM_TICKET_STATUS_UPDATE with status = 3
513    CHECK_PACKET_SIZE(recv_data,4+4);
514    uint32 x;
515    recv_data >> x;                                         // answer range? (6 = 0-5?)
516    sLog.outDebug("SURVEY: X = %u", x);
517
518    uint8 result[10];
519    memset(result, 0, sizeof(result));
520    for( int i = 0; i < 10; ++i)
521    {
522        CHECK_PACKET_SIZE(recv_data,recv_data.rpos()+4);
523        uint32 questionID;
524        recv_data >> questionID;                            // GMSurveyQuestions.dbc
525        if (!questionID)
526            break;
527
528        CHECK_PACKET_SIZE(recv_data,recv_data.rpos()+1+1);
529        uint8 value;
530        std::string unk_text;
531        recv_data >> value;                                 // answer
532        recv_data >> unk_text;                              // always empty?
533
534        result[i] = value;
535        sLog.outDebug("SURVEY: ID %u, value %u, text %s", questionID, value, unk_text.c_str());
536    }
537
538    CHECK_PACKET_SIZE(recv_data,recv_data.rpos()+1);
539    std::string comment;
540    recv_data >> comment;                                   // addional comment
541    sLog.outDebug("SURVEY: comment %s", comment.c_str());
542
543    // TODO: chart this data in some way
544}
545
546void WorldSession::HandleTogglePvP( WorldPacket & recv_data )
547{
548    // this opcode can be used in two ways: Either set explicit new status or toggle old status
549    if(recv_data.size() == 1)
550    {
551        bool newPvPStatus;
552        recv_data >> newPvPStatus;
553        GetPlayer()->ApplyModFlag(PLAYER_FLAGS, PLAYER_FLAGS_IN_PVP, newPvPStatus);
554    }
555    else
556    {
557        GetPlayer()->ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_IN_PVP);
558    }
559
560    if(GetPlayer()->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_IN_PVP))
561    {
562        if(!GetPlayer()->IsPvP() || GetPlayer()->pvpInfo.endTimer != 0)
563            GetPlayer()->UpdatePvP(true, true);
564    }
565    else
566    {
567        if(!GetPlayer()->pvpInfo.inHostileArea && GetPlayer()->IsPvP())
568            GetPlayer()->pvpInfo.endTimer = time(NULL);     // start toggle-off
569    }
570
571    if(OutdoorPvP * pvp = _player->GetOutdoorPvP())
572    {
573        pvp->HandlePlayerActivityChanged(_player);
574    }
575}
576
577void WorldSession::HandleZoneUpdateOpcode( WorldPacket & recv_data )
578{
579    CHECK_PACKET_SIZE(recv_data,4);
580
581    uint32 newZone;
582    recv_data >> newZone;
583
584    sLog.outDetail("WORLD: Recvd ZONE_UPDATE: %u", newZone);
585
586    GetPlayer()->UpdateZone(newZone);
587
588    GetPlayer()->SendInitWorldStates(true,newZone);
589}
590
591void WorldSession::HandleSetTargetOpcode( WorldPacket & recv_data )
592{
593    // When this packet send?
594    CHECK_PACKET_SIZE(recv_data,8);
595
596    uint64 guid ;
597    recv_data >> guid;
598
599    _player->SetUInt32Value(UNIT_FIELD_TARGET,guid);
600
601    // update reputation list if need
602    Unit* unit = ObjectAccessor::GetUnit(*_player, guid );
603    if(!unit)
604        return;
605
606    _player->SetFactionVisibleForFactionTemplateId(unit->getFaction());
607}
608
609void WorldSession::HandleSetSelectionOpcode( WorldPacket & recv_data )
610{
611    CHECK_PACKET_SIZE(recv_data,8);
612
613    uint64 guid;
614    recv_data >> guid;
615
616    _player->SetSelection(guid);
617
618    // update reputation list if need
619    Unit* unit = ObjectAccessor::GetUnit(*_player, guid );
620    if(!unit)
621        return;
622
623    _player->SetFactionVisibleForFactionTemplateId(unit->getFaction());
624}
625
626void WorldSession::HandleStandStateChangeOpcode( WorldPacket & recv_data )
627{
628    CHECK_PACKET_SIZE(recv_data,1);
629
630    sLog.outDebug( "WORLD: Received CMSG_STAND_STATE_CHANGE"  );
631    uint8 animstate;
632    recv_data >> animstate;
633
634    _player->SetStandState(animstate);
635}
636
637void WorldSession::HandleFriendListOpcode( WorldPacket & recv_data )
638{
639    CHECK_PACKET_SIZE(recv_data, 4);
640    sLog.outDebug( "WORLD: Received CMSG_CONTACT_LIST" );
641    uint32 unk;
642    recv_data >> unk;
643    sLog.outDebug("unk value is %u", unk);
644    _player->GetSocial()->SendSocialList();
645}
646
647void WorldSession::HandleAddFriendOpcode( WorldPacket & recv_data )
648{
649    CHECK_PACKET_SIZE(recv_data, 1+1);
650
651    sLog.outDebug( "WORLD: Received CMSG_ADD_FRIEND" );
652
653    std::string friendName = GetTrinityString(LANG_FRIEND_IGNORE_UNKNOWN);
654    std::string friendNote;
655   
656    recv_data >> friendName;
657
658    // recheck
659    CHECK_PACKET_SIZE(recv_data, (friendName.size()+1)+1);
660
661    recv_data >> friendNote;
662
663    if(!normalizePlayerName(friendName))
664        return;
665
666    CharacterDatabase.escape_string(friendName);            // prevent SQL injection - normal name don't must changed by this call
667
668    sLog.outDebug( "WORLD: %s asked to add friend : '%s'",
669        GetPlayer()->GetName(), friendName.c_str() );
670
671    CharacterDatabase.AsyncPQuery(&WorldSession::HandleAddFriendOpcodeCallBack, GetAccountId(), friendNote, "SELECT guid, race FROM characters WHERE name = '%s'", friendName.c_str());
672}
673
674void WorldSession::HandleAddFriendOpcodeCallBack(QueryResult *result, uint32 accountId, std::string friendNote)
675{
676    if(!result)
677        return;
678       
679    uint64 friendGuid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
680    uint32 team = Player::TeamForRace((*result)[1].GetUInt8());
681   
682    delete result;
683   
684    WorldSession * session = sWorld.FindSession(accountId);
685    if(!session)
686        return;
687       
688    FriendsResult friendResult = FRIEND_NOT_FOUND;
689    if(friendGuid)
690    {
691        if(friendGuid==session->GetPlayer()->GetGUID())
692            friendResult = FRIEND_SELF;
693        else if(session->GetPlayer()->GetTeam() != team && !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_ADD_FRIEND) && session->GetSecurity() < SEC_MODERATOR)
694            friendResult = FRIEND_ENEMY;
695        else if(session->GetPlayer()->GetSocial()->HasFriend(GUID_LOPART(friendGuid)))
696            friendResult = FRIEND_ALREADY;
697        else
698        {
699            Player* pFriend = ObjectAccessor::FindPlayer(friendGuid);
700            if( pFriend && pFriend->IsInWorld() && pFriend->IsVisibleGloballyFor(session->GetPlayer()))
701                friendResult = FRIEND_ADDED_ONLINE;
702            else
703                friendResult = FRIEND_ADDED_OFFLINE;
704               
705        if(!session->GetPlayer()->GetSocial()->AddToSocialList(GUID_LOPART(friendGuid), false))
706        {
707            friendResult = FRIEND_LIST_FULL;
708            sLog.outDebug( "WORLD: %s's friend list is full.", session->GetPlayer()->GetName());
709        }
710
711            session->GetPlayer()->GetSocial()->SetFriendNote(GUID_LOPART(friendGuid), friendNote);
712        }
713    }
714
715    sSocialMgr.SendFriendStatus(session->GetPlayer(), friendResult, GUID_LOPART(friendGuid), false);
716
717    sLog.outDebug( "WORLD: Sent (SMSG_FRIEND_STATUS)" );
718}
719
720void WorldSession::HandleDelFriendOpcode( WorldPacket & recv_data )
721{
722    CHECK_PACKET_SIZE(recv_data, 8);
723
724    uint64 FriendGUID;
725
726    sLog.outDebug( "WORLD: Received CMSG_DEL_FRIEND" );
727
728    recv_data >> FriendGUID;
729
730    _player->GetSocial()->RemoveFromSocialList(GUID_LOPART(FriendGUID), false);
731
732    sSocialMgr.SendFriendStatus(GetPlayer(), FRIEND_REMOVED, GUID_LOPART(FriendGUID), false);
733
734    sLog.outDebug( "WORLD: Sent motd (SMSG_FRIEND_STATUS)" );
735}
736
737void WorldSession::HandleAddIgnoreOpcode( WorldPacket & recv_data )
738{
739    CHECK_PACKET_SIZE(recv_data,1);
740
741    sLog.outDebug( "WORLD: Received CMSG_ADD_IGNORE" );
742
743    std::string IgnoreName = GetTrinityString(LANG_FRIEND_IGNORE_UNKNOWN);
744
745    recv_data >> IgnoreName;
746
747    if(!normalizePlayerName(IgnoreName))
748        return;
749
750    CharacterDatabase.escape_string(IgnoreName);            // prevent SQL injection - normal name don't must changed by this call
751
752    sLog.outDebug( "WORLD: %s asked to Ignore: '%s'",
753        GetPlayer()->GetName(), IgnoreName.c_str() );
754
755    CharacterDatabase.AsyncPQuery(&WorldSession::HandleAddIgnoreOpcodeCallBack, GetAccountId(), "SELECT guid FROM characters WHERE name = '%s'", IgnoreName.c_str());
756}
757
758void WorldSession::HandleAddIgnoreOpcodeCallBack(QueryResult *result, uint32 accountId)
759{
760    if(!result)
761        return;
762   
763    uint64 IgnoreGuid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
764   
765    delete result;
766   
767    WorldSession * session = sWorld.FindSession(accountId);
768    if(!session)
769        return;
770       
771    FriendsResult ignoreResult = FRIEND_IGNORE_NOT_FOUND;
772    if(IgnoreGuid)
773    {
774        if(IgnoreGuid==session->GetPlayer()->GetGUID())              //not add yourself
775            ignoreResult = FRIEND_IGNORE_SELF;
776            else if( session->GetPlayer()->GetSocial()->HasIgnore(GUID_LOPART(IgnoreGuid)) )
777                ignoreResult = FRIEND_IGNORE_ALREADY;
778        else
779        {
780            ignoreResult = FRIEND_IGNORE_ADDED;
781
782        // ignore list full
783        if(!session->GetPlayer()->GetSocial()->AddToSocialList(GUID_LOPART(IgnoreGuid), true))
784            ignoreResult = FRIEND_IGNORE_FULL;
785        }
786    }
787
788    sSocialMgr.SendFriendStatus(session->GetPlayer(), ignoreResult, GUID_LOPART(IgnoreGuid), false);
789
790    sLog.outDebug( "WORLD: Sent (SMSG_FRIEND_STATUS)" );
791}
792
793void WorldSession::HandleDelIgnoreOpcode( WorldPacket & recv_data )
794{
795    CHECK_PACKET_SIZE(recv_data, 8);
796
797    uint64 IgnoreGUID;
798
799    sLog.outDebug( "WORLD: Received CMSG_DEL_IGNORE" );
800
801    recv_data >> IgnoreGUID;
802
803    _player->GetSocial()->RemoveFromSocialList(GUID_LOPART(IgnoreGUID), true);
804
805    sSocialMgr.SendFriendStatus(GetPlayer(), FRIEND_IGNORE_REMOVED, GUID_LOPART(IgnoreGUID), false);
806
807    sLog.outDebug( "WORLD: Sent motd (SMSG_FRIEND_STATUS)" );
808}
809
810void WorldSession::HandleSetFriendNoteOpcode( WorldPacket & recv_data )
811{
812    CHECK_PACKET_SIZE(recv_data, 8+1);
813    uint64 guid;
814    std::string note;
815    recv_data >> guid >> note;
816    _player->GetSocial()->SetFriendNote(guid, note);
817}
818
819void WorldSession::HandleBugOpcode( WorldPacket & recv_data )
820{
821    CHECK_PACKET_SIZE(recv_data,4+4+1+4+1);
822
823    uint32 suggestion, contentlen;
824    std::string content;
825    uint32 typelen;
826    std::string type;
827
828    recv_data >> suggestion >> contentlen >> content;
829
830    //recheck
831    CHECK_PACKET_SIZE(recv_data,4+4+(content.size()+1)+4+1);
832
833    recv_data >> typelen >> type;
834
835    if( suggestion == 0 )
836        sLog.outDebug( "WORLD: Received CMSG_BUG [Bug Report]" );
837    else
838        sLog.outDebug( "WORLD: Received CMSG_BUG [Suggestion]" );
839
840    sLog.outDebug( type.c_str( ) );
841    sLog.outDebug( content.c_str( ) );
842
843    CharacterDatabase.escape_string(type);
844    CharacterDatabase.escape_string(content);
845    CharacterDatabase.PExecute ("INSERT INTO bugreport (type,content) VALUES('%s', '%s')", type.c_str( ), content.c_str( ));
846}
847
848void WorldSession::HandleCorpseReclaimOpcode(WorldPacket &recv_data)
849{
850    CHECK_PACKET_SIZE(recv_data,8);
851
852    sLog.outDetail("WORLD: Received CMSG_RECLAIM_CORPSE");
853    if (GetPlayer()->isAlive())
854        return;
855
856    if (BattleGround * bg = _player->GetBattleGround())
857        if(bg->isArena())
858            return;
859
860    // body not released yet
861    if(!GetPlayer()->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
862        return;
863
864    Corpse *corpse = GetPlayer()->GetCorpse();
865
866    if (!corpse )
867        return;
868
869    // prevent resurrect before 30-sec delay after body release not finished
870    if(corpse->GetGhostTime() + GetPlayer()->GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP) > time(NULL))
871        return;
872
873    float dist = corpse->GetDistance2d(GetPlayer());
874    sLog.outDebug("Corpse 2D Distance: \t%f",dist);
875    if (dist > CORPSE_RECLAIM_RADIUS)
876        return;
877
878    uint64 guid;
879    recv_data >> guid;
880
881    // resurrect
882    GetPlayer()->ResurrectPlayer(GetPlayer()->InBattleGround() ? 1.0f : 0.5f);
883
884    // spawn bones
885    GetPlayer()->SpawnCorpseBones();
886
887    GetPlayer()->SaveToDB();
888}
889
890void WorldSession::HandleResurrectResponseOpcode(WorldPacket & recv_data)
891{
892    CHECK_PACKET_SIZE(recv_data,8+1);
893
894    sLog.outDetail("WORLD: Received CMSG_RESURRECT_RESPONSE");
895
896    if(GetPlayer()->isAlive())
897        return;
898
899    uint64 guid;
900    uint8 status;
901    recv_data >> guid;
902    recv_data >> status;
903
904    if(status == 0)
905    {
906        GetPlayer()->clearResurrectRequestData();           // reject
907        return;
908    }
909
910    if(!GetPlayer()->isRessurectRequestedBy(guid))
911        return;
912
913    GetPlayer()->ResurectUsingRequestData();
914    GetPlayer()->SaveToDB();
915}
916
917void WorldSession::HandleAreaTriggerOpcode(WorldPacket & recv_data)
918{
919    CHECK_PACKET_SIZE(recv_data,4);
920
921    sLog.outDebug("WORLD: Received CMSG_AREATRIGGER");
922
923    uint32 Trigger_ID;
924
925    recv_data >> Trigger_ID;
926    sLog.outDebug("Trigger ID:%u",Trigger_ID);
927
928    if(GetPlayer()->isInFlight())
929    {
930        sLog.outDebug("Player '%s' (GUID: %u) in flight, ignore Area Trigger ID:%u",GetPlayer()->GetName(),GetPlayer()->GetGUIDLow(), Trigger_ID);
931        return;
932    }
933
934    AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
935    if(!atEntry)
936    {
937        sLog.outDebug("Player '%s' (GUID: %u) send unknown (by DBC) Area Trigger ID:%u",GetPlayer()->GetName(),GetPlayer()->GetGUIDLow(), Trigger_ID);
938        return;
939    }
940
941    if (GetPlayer()->GetMapId()!=atEntry->mapid)
942    {
943        sLog.outDebug("Player '%s' (GUID: %u) too far (trigger map: %u player map: %u), ignore Area Trigger ID: %u", GetPlayer()->GetName(), atEntry->mapid, GetPlayer()->GetMapId(), GetPlayer()->GetGUIDLow(), Trigger_ID);
944        return;
945    }
946
947    // delta is safe radius
948    const float delta = 5.0f;
949    // check if player in the range of areatrigger
950    Player* pl = GetPlayer();
951
952    if (atEntry->radius > 0)
953    {
954        // if we have radius check it
955        float dist = pl->GetDistance(atEntry->x,atEntry->y,atEntry->z);
956        if(dist > atEntry->radius + delta)
957        {
958            sLog.outDebug("Player '%s' (GUID: %u) too far (radius: %f distance: %f), ignore Area Trigger ID: %u",
959                pl->GetName(), pl->GetGUIDLow(), atEntry->radius, dist, Trigger_ID);
960            return;
961        }
962    }
963    else
964    {
965        // we have only extent
966        float dx = pl->GetPositionX() - atEntry->x;
967        float dy = pl->GetPositionY() - atEntry->y;
968        float dz = pl->GetPositionZ() - atEntry->z;
969        double es = sin(atEntry->box_orientation);
970        double ec = cos(atEntry->box_orientation);
971        // calc rotated vector based on extent axis
972        double rotateDx = dx*ec - dy*es;
973        double rotateDy = dx*es + dy*ec;
974
975        if( (fabs(rotateDx) > atEntry->box_x/2 + delta) ||
976            (fabs(rotateDy) > atEntry->box_y/2 + delta) ||
977            (fabs(dz) > atEntry->box_z/2 + delta) )
978        {
979            sLog.outDebug("Player '%s' (GUID: %u) too far (1/2 box X: %f 1/2 box Y: %u 1/2 box Z: %u rotate dX: %f rotate dY: %f dZ:%f), ignore Area Trigger ID: %u",
980                pl->GetName(), pl->GetGUIDLow(), atEntry->box_x/2, atEntry->box_y/2, atEntry->box_z/2, rotateDx, rotateDy, dz, Trigger_ID);
981            return;
982        }
983    }
984
985    if(Script->scriptAreaTrigger(GetPlayer(), atEntry))
986        return;
987
988    uint32 quest_id = objmgr.GetQuestForAreaTrigger( Trigger_ID );
989    if( quest_id && GetPlayer()->isAlive() && GetPlayer()->IsActiveQuest(quest_id) )
990    {
991        Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
992        if( pQuest )
993        {
994            if(GetPlayer()->GetQuestStatus(quest_id) == QUEST_STATUS_INCOMPLETE)
995                GetPlayer()->AreaExploredOrEventHappens( quest_id );
996        }
997    }
998
999    if(objmgr.IsTavernAreaTrigger(Trigger_ID))
1000    {
1001        // set resting flag we are in the inn
1002        GetPlayer()->SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
1003        GetPlayer()->InnEnter(time(NULL), atEntry->mapid, atEntry->x, atEntry->y, atEntry->z);
1004        GetPlayer()->SetRestType(REST_TYPE_IN_TAVERN);
1005
1006        if(sWorld.IsFFAPvPRealm())
1007            GetPlayer()->RemoveFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
1008
1009        return;
1010    }
1011
1012    if(GetPlayer()->InBattleGround())
1013    {
1014        BattleGround* bg = GetPlayer()->GetBattleGround();
1015        if(bg)
1016            if(bg->GetStatus() == STATUS_IN_PROGRESS)
1017                bg->HandleAreaTrigger(GetPlayer(), Trigger_ID);
1018
1019        return;
1020    }
1021
1022    if(OutdoorPvP * pvp = GetPlayer()->GetOutdoorPvP())
1023    {
1024        if(pvp->HandleAreaTrigger(_player, Trigger_ID))
1025            return;
1026    }
1027
1028    // NULL if all values default (non teleport trigger)
1029    AreaTrigger const* at = objmgr.GetAreaTrigger(Trigger_ID);
1030    if(!at)
1031        return;
1032
1033    if(!GetPlayer()->isGameMaster())
1034    {
1035        uint32 missingLevel = 0;
1036        if(GetPlayer()->getLevel() < at->requiredLevel && !sWorld.getConfig(CONFIG_INSTANCE_IGNORE_LEVEL))
1037            missingLevel = at->requiredLevel;
1038
1039        // must have one or the other, report the first one that's missing
1040        uint32 missingItem = 0;
1041        if(at->requiredItem)
1042        {
1043            if(!GetPlayer()->HasItemCount(at->requiredItem, 1) &&
1044                (!at->requiredItem2 || !GetPlayer()->HasItemCount(at->requiredItem2, 1)))
1045                missingItem = at->requiredItem;
1046        }
1047        else if(at->requiredItem2 && !GetPlayer()->HasItemCount(at->requiredItem2, 1))
1048            missingItem = at->requiredItem2;
1049
1050        uint32 missingKey = 0;
1051        if(GetPlayer()->GetDifficulty() == DIFFICULTY_HEROIC)
1052        {
1053            if(at->heroicKey)
1054            {
1055                if(!GetPlayer()->HasItemCount(at->heroicKey, 1) &&
1056                    (!at->heroicKey2 || !GetPlayer()->HasItemCount(at->heroicKey2, 1)))
1057                    missingKey = at->heroicKey;
1058            }
1059            else if(at->heroicKey2 && !GetPlayer()->HasItemCount(at->heroicKey2, 1))
1060                missingKey = at->heroicKey2;
1061        }
1062
1063        uint32 missingQuest = 0;
1064        if(at->requiredQuest && !GetPlayer()->GetQuestRewardStatus(at->requiredQuest))
1065            missingQuest = at->requiredQuest;
1066
1067        if(missingLevel || missingItem || missingKey || missingQuest)
1068        {
1069            // TODO: all this is probably wrong
1070            if(missingItem)
1071                SendAreaTriggerMessage(GetTrinityString(LANG_LEVEL_MINREQUIRED_AND_ITEM), at->requiredLevel, objmgr.GetItemPrototype(missingItem)->Name1);
1072            else if(missingKey)
1073                GetPlayer()->SendTransferAborted(at->target_mapId, TRANSFER_ABORT_DIFFICULTY2);
1074            else if(missingQuest)
1075                SendAreaTriggerMessage(at->requiredFailedText.c_str());
1076            else if(missingLevel)
1077                SendAreaTriggerMessage(GetTrinityString(LANG_LEVEL_MINREQUIRED), missingLevel);
1078            return;
1079        }
1080    }
1081
1082    GetPlayer()->TeleportTo(at->target_mapId,at->target_X,at->target_Y,at->target_Z,at->target_Orientation,TELE_TO_NOT_LEAVE_TRANSPORT);
1083}
1084
1085void WorldSession::HandleUpdateAccountData(WorldPacket &/*recv_data*/)
1086{
1087    sLog.outDetail("WORLD: Received CMSG_UPDATE_ACCOUNT_DATA");
1088    //recv_data.hexlike();
1089}
1090
1091void WorldSession::HandleRequestAccountData(WorldPacket& /*recv_data*/)
1092{
1093    sLog.outDetail("WORLD: Received CMSG_REQUEST_ACCOUNT_DATA");
1094    //recv_data.hexlike();
1095}
1096
1097void WorldSession::HandleSetActionButtonOpcode(WorldPacket& recv_data)
1098{
1099    CHECK_PACKET_SIZE(recv_data,1+2+1+1);
1100
1101    sLog.outDebug(  "WORLD: Received CMSG_SET_ACTION_BUTTON" );
1102    uint8 button, misc, type;
1103    uint16 action;
1104    recv_data >> button >> action >> misc >> type;
1105    sLog.outDetail( "BUTTON: %u ACTION: %u TYPE: %u MISC: %u", button, action, type, misc );
1106    if(action==0)
1107    {
1108        sLog.outDetail( "MISC: Remove action from button %u", button );
1109
1110        GetPlayer()->removeActionButton(button);
1111    }
1112    else
1113    {
1114        if(type==ACTION_BUTTON_MACRO || type==ACTION_BUTTON_CMACRO)
1115        {
1116            sLog.outDetail( "MISC: Added Macro %u into button %u", action, button );
1117            GetPlayer()->addActionButton(button,action,type,misc);
1118        }
1119        else if(type==ACTION_BUTTON_SPELL)
1120        {
1121            sLog.outDetail( "MISC: Added Action %u into button %u", action, button );
1122            GetPlayer()->addActionButton(button,action,type,misc);
1123        }
1124        else if(type==ACTION_BUTTON_ITEM)
1125        {
1126            sLog.outDetail( "MISC: Added Item %u into button %u", action, button );
1127            GetPlayer()->addActionButton(button,action,type,misc);
1128        }
1129        else
1130            sLog.outError( "MISC: Unknown action button type %u for action %u into button %u", type, action, button );
1131    }
1132}
1133
1134void WorldSession::HandleCompleteCinema( WorldPacket & /*recv_data*/ )
1135{
1136    DEBUG_LOG( "WORLD: Player is watching cinema" );
1137}
1138
1139void WorldSession::HandleNextCinematicCamera( WorldPacket & /*recv_data*/ )
1140{
1141    DEBUG_LOG( "WORLD: Which movie to play" );
1142}
1143
1144void WorldSession::HandleMoveTimeSkippedOpcode( WorldPacket & /*recv_data*/ )
1145{
1146    /*  WorldSession::Update( getMSTime() );*/
1147    DEBUG_LOG( "WORLD: Time Lag/Synchronization Resent/Update" );
1148
1149    /*
1150        CHECK_PACKET_SIZE(recv_data,8+4);
1151        uint64 guid;
1152        uint32 time_skipped;
1153        recv_data >> guid;
1154        recv_data >> time_skipped;
1155        sLog.outDebug( "WORLD: CMSG_MOVE_TIME_SKIPPED" );
1156
1157        /// TODO
1158        must be need use in Trinity
1159        We substract server Lags to move time ( AntiLags )
1160        for exmaple
1161        GetPlayer()->ModifyLastMoveTime( -int32(time_skipped) );
1162    */
1163}
1164
1165void WorldSession::HandleFeatherFallAck(WorldPacket &/*recv_data*/)
1166{
1167    DEBUG_LOG("WORLD: CMSG_MOVE_FEATHER_FALL_ACK");
1168}
1169
1170void WorldSession::HandleMoveUnRootAck(WorldPacket&/* recv_data*/)
1171{
1172    /*
1173        CHECK_PACKET_SIZE(recv_data,8+8+4+4+4+4+4);
1174
1175        sLog.outDebug( "WORLD: CMSG_FORCE_MOVE_UNROOT_ACK" );
1176        recv_data.hexlike();
1177        uint64 guid;
1178        uint64 unknown1;
1179        uint32 unknown2;
1180        float PositionX;
1181        float PositionY;
1182        float PositionZ;
1183        float Orientation;
1184
1185        recv_data >> guid;
1186        recv_data >> unknown1;
1187        recv_data >> unknown2;
1188        recv_data >> PositionX;
1189        recv_data >> PositionY;
1190        recv_data >> PositionZ;
1191        recv_data >> Orientation;
1192
1193        // TODO for later may be we can use for anticheat
1194        DEBUG_LOG("Guid " I64FMTD,guid);
1195        DEBUG_LOG("unknown1 " I64FMTD,unknown1);
1196        DEBUG_LOG("unknown2 %u",unknown2);
1197        DEBUG_LOG("X %f",PositionX);
1198        DEBUG_LOG("Y %f",PositionY);
1199        DEBUG_LOG("Z %f",PositionZ);
1200        DEBUG_LOG("O %f",Orientation);
1201    */
1202}
1203
1204void WorldSession::HandleMoveRootAck(WorldPacket&/* recv_data*/)
1205{
1206    /*
1207        CHECK_PACKET_SIZE(recv_data,8+8+4+4+4+4+4);
1208
1209        sLog.outDebug( "WORLD: CMSG_FORCE_MOVE_ROOT_ACK" );
1210        recv_data.hexlike();
1211        uint64 guid;
1212        uint64 unknown1;
1213        uint32 unknown2;
1214        float PositionX;
1215        float PositionY;
1216        float PositionZ;
1217        float Orientation;
1218
1219        recv_data >> guid;
1220        recv_data >> unknown1;
1221        recv_data >> unknown2;
1222        recv_data >> PositionX;
1223        recv_data >> PositionY;
1224        recv_data >> PositionZ;
1225        recv_data >> Orientation;
1226
1227        // for later may be we can use for anticheat
1228        DEBUG_LOG("Guid " I64FMTD,guid);
1229        DEBUG_LOG("unknown1 " I64FMTD,unknown1);
1230        DEBUG_LOG("unknown1 %u",unknown2);
1231        DEBUG_LOG("X %f",PositionX);
1232        DEBUG_LOG("Y %f",PositionY);
1233        DEBUG_LOG("Z %f",PositionZ);
1234        DEBUG_LOG("O %f",Orientation);
1235    */
1236}
1237
1238void WorldSession::HandleMoveTeleportAck(WorldPacket&/* recv_data*/)
1239{
1240    /*
1241        CHECK_PACKET_SIZE(recv_data,8+4);
1242
1243        sLog.outDebug("MSG_MOVE_TELEPORT_ACK");
1244        uint64 guid;
1245        uint32 flags, time;
1246
1247        recv_data >> guid;
1248        recv_data >> flags >> time;
1249        DEBUG_LOG("Guid " I64FMTD,guid);
1250        DEBUG_LOG("Flags %u, time %u",flags, time/1000);
1251    */
1252}
1253
1254void WorldSession::HandleSetActionBar(WorldPacket& recv_data)
1255{
1256    CHECK_PACKET_SIZE(recv_data,1);
1257
1258    uint8 ActionBar;
1259
1260    recv_data >> ActionBar;
1261
1262    if(!GetPlayer())                                        // ignore until not logged (check needed because STATUS_AUTHED)
1263    {
1264        if(ActionBar!=0)
1265            sLog.outError("WorldSession::HandleSetActionBar in not logged state with value: %u, ignored",uint32(ActionBar));
1266        return;
1267    }
1268
1269    GetPlayer()->SetByteValue(PLAYER_FIELD_BYTES, 2, ActionBar);
1270}
1271
1272void WorldSession::HandleWardenDataOpcode(WorldPacket& /*recv_data*/)
1273{
1274    /*
1275        CHECK_PACKET_SIZE(recv_data,1);
1276
1277        uint8 tmp;
1278        recv_data >> tmp;
1279        sLog.outDebug("Received opcode CMSG_WARDEN_DATA, not resolve.uint8 = %u",tmp);
1280    */
1281}
1282
1283void WorldSession::HandlePlayedTime(WorldPacket& /*recv_data*/)
1284{
1285    uint32 TotalTimePlayed = GetPlayer()->GetTotalPlayedTime();
1286    uint32 LevelPlayedTime = GetPlayer()->GetLevelPlayedTime();
1287
1288    WorldPacket data(SMSG_PLAYED_TIME, 8);
1289    data << TotalTimePlayed;
1290    data << LevelPlayedTime;
1291    SendPacket(&data);
1292}
1293
1294void WorldSession::HandleInspectOpcode(WorldPacket& recv_data)
1295{
1296    CHECK_PACKET_SIZE(recv_data, 8);
1297
1298    uint64 guid;
1299    recv_data >> guid;
1300    DEBUG_LOG("Inspected guid is " I64FMTD, guid);
1301
1302    _player->SetSelection(guid);
1303
1304    Player *plr = objmgr.GetPlayer(guid);
1305    if(!plr)                                                // wrong player
1306        return;
1307
1308    uint32 talent_points = 0x3D;
1309    uint32 guid_size = plr->GetPackGUID().size();
1310    WorldPacket data(SMSG_INSPECT_TALENT, 4+talent_points);
1311    data.append(plr->GetPackGUID());
1312    data << uint32(talent_points);
1313
1314    // fill by 0 talents array
1315    for(uint32 i = 0; i < talent_points; ++i)
1316        data << uint8(0);
1317
1318    if(sWorld.getConfig(CONFIG_TALENTS_INSPECTING) || _player->isGameMaster())
1319    {
1320        // find class talent tabs (all players have 3 talent tabs)
1321        uint32 const* talentTabIds = GetTalentTabPages(plr->getClass());
1322
1323        uint32 talentTabPos = 0;                            // pos of first talent rank in tab including all prev tabs
1324        for(uint32 i = 0; i < 3; ++i)
1325        {
1326            uint32 talentTabId = talentTabIds[i];
1327
1328            // fill by real data
1329            for(uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
1330            {
1331                TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
1332                if(!talentInfo)
1333                    continue;
1334
1335                // skip another tab talents
1336                if(talentInfo->TalentTab != talentTabId)
1337                    continue;
1338
1339                // find talent rank
1340                uint32 curtalent_maxrank = 0;
1341                for(uint32 k = 5; k > 0; --k)
1342                {
1343                    if(talentInfo->RankID[k-1] && plr->HasSpell(talentInfo->RankID[k-1]))
1344                    {
1345                        curtalent_maxrank = k;
1346                        break;
1347                    }
1348                }
1349
1350                // not learned talent
1351                if(!curtalent_maxrank)
1352                    continue;
1353
1354                // 1 rank talent bit index
1355                uint32 curtalent_index = talentTabPos + GetTalentInspectBitPosInTab(talentId);
1356
1357                uint32 curtalent_rank_index = curtalent_index+curtalent_maxrank-1;
1358
1359                // slot/offset in 7-bit bytes
1360                uint32 curtalent_rank_slot7   = curtalent_rank_index / 7;
1361                uint32 curtalent_rank_offset7 = curtalent_rank_index % 7;
1362
1363                // rank pos with skipped 8 bit
1364                uint32 curtalent_rank_index2 = curtalent_rank_slot7 * 8 + curtalent_rank_offset7;
1365
1366                // slot/offset in 8-bit bytes with skipped high bit
1367                uint32 curtalent_rank_slot = curtalent_rank_index2 / 8;
1368                uint32 curtalent_rank_offset =  curtalent_rank_index2 % 8;
1369
1370                // apply mask
1371                uint32 val = data.read<uint8>(guid_size + 4 + curtalent_rank_slot);
1372                val |= (1 << curtalent_rank_offset);
1373                data.put<uint8>(guid_size + 4 + curtalent_rank_slot, val & 0xFF);
1374            }
1375
1376            talentTabPos += GetTalentTabInspectBitSize(talentTabId);
1377        }
1378    }
1379
1380    SendPacket(&data);
1381}
1382
1383void WorldSession::HandleInspectHonorStatsOpcode(WorldPacket& recv_data)
1384{
1385    CHECK_PACKET_SIZE(recv_data, 8);
1386
1387    uint64 guid;
1388    recv_data >> guid;
1389
1390    Player *player = objmgr.GetPlayer(guid);
1391
1392    if(!player)
1393    {
1394        sLog.outError("InspectHonorStats: WTF, player not found...");
1395        return;
1396    }
1397
1398    WorldPacket data(MSG_INSPECT_HONOR_STATS, 8+1+4*4);
1399    data << uint64(player->GetGUID());
1400    data << uint8(player->GetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY));
1401    data << uint32(player->GetUInt32Value(PLAYER_FIELD_KILLS));
1402    data << uint32(player->GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
1403    data << uint32(player->GetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION));
1404    data << uint32(player->GetUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS));
1405    SendPacket(&data);
1406}
1407
1408void WorldSession::HandleWorldTeleportOpcode(WorldPacket& recv_data)
1409{
1410    CHECK_PACKET_SIZE(recv_data,4+4+4+4+4+4);
1411
1412    // write in client console: worldport 469 452 6454 2536 180 or /console worldport 469 452 6454 2536 180
1413    // Received opcode CMSG_WORLD_TELEPORT
1414    // Time is ***, map=469, x=452.000000, y=6454.000000, z=2536.000000, orient=3.141593
1415
1416    //sLog.outDebug("Received opcode CMSG_WORLD_TELEPORT");
1417
1418    if(GetPlayer()->isInFlight())
1419    {
1420        sLog.outDebug("Player '%s' (GUID: %u) in flight, ignore worldport command.",GetPlayer()->GetName(),GetPlayer()->GetGUIDLow());
1421        return;
1422    }
1423
1424    uint32 time;
1425    uint32 mapid;
1426    float PositionX;
1427    float PositionY;
1428    float PositionZ;
1429    float Orientation;
1430
1431    recv_data >> time;                                      // time in m.sec.
1432    recv_data >> mapid;
1433    recv_data >> PositionX;
1434    recv_data >> PositionY;
1435    recv_data >> PositionZ;
1436    recv_data >> Orientation;                               // o (3.141593 = 180 degrees)
1437    DEBUG_LOG("Time %u sec, map=%u, x=%f, y=%f, z=%f, orient=%f", time/1000, mapid, PositionX, PositionY, PositionZ, Orientation);
1438
1439    if (GetSecurity() >= SEC_ADMINISTRATOR)
1440        GetPlayer()->TeleportTo(mapid,PositionX,PositionY,PositionZ,Orientation);
1441    else
1442        SendNotification(LANG_YOU_NOT_HAVE_PERMISSION);
1443    sLog.outDebug("Received worldport command from player %s", GetPlayer()->GetName());
1444}
1445
1446void WorldSession::HandleWhoisOpcode(WorldPacket& recv_data)
1447{
1448    CHECK_PACKET_SIZE(recv_data, 1);
1449
1450    sLog.outDebug("Received opcode CMSG_WHOIS");
1451    std::string charname;
1452    recv_data >> charname;
1453
1454    if (GetSecurity() < SEC_ADMINISTRATOR)
1455    {
1456        SendNotification(LANG_YOU_NOT_HAVE_PERMISSION);
1457        return;
1458    }
1459
1460    if(charname.empty())
1461    {
1462        SendNotification(LANG_NEED_CHARACTER_NAME);
1463        return;
1464    }
1465
1466    Player *plr = objmgr.GetPlayer(charname.c_str());
1467
1468    if(!plr)
1469    {
1470        SendNotification(LANG_PLAYER_NOT_EXIST_OR_OFFLINE, charname.c_str());
1471        return;
1472    }
1473
1474    uint32 accid = plr->GetSession()->GetAccountId();
1475
1476    QueryResult *result = loginDatabase.PQuery("SELECT username,email,last_ip FROM account WHERE id=%u", accid);
1477    if(!result)
1478    {
1479        SendNotification(LANG_ACCOUNT_FOR_PLAYER_NOT_FOUND, charname.c_str());
1480        return;
1481    }
1482
1483    Field *fields = result->Fetch();
1484    std::string acc = fields[0].GetCppString();
1485    if(acc.empty())
1486        acc = "Unknown";
1487    std::string email = fields[1].GetCppString();
1488    if(email.empty())
1489        email = "Unknown";
1490    std::string lastip = fields[2].GetCppString();
1491    if(lastip.empty())
1492        lastip = "Unknown";
1493
1494    std::string msg = charname + "'s " + "account is " + acc + ", e-mail: " + email + ", last ip: " + lastip;
1495
1496    WorldPacket data(SMSG_WHOIS, msg.size()+1);
1497    data << msg;
1498    _player->GetSession()->SendPacket(&data);
1499
1500    delete result;
1501
1502    sLog.outDebug("Received whois command from player %s for character %s", GetPlayer()->GetName(), charname.c_str());
1503}
1504
1505void WorldSession::HandleReportSpamOpcode( WorldPacket & recv_data )
1506{
1507    CHECK_PACKET_SIZE(recv_data, 1+8);
1508    sLog.outDebug("WORLD: CMSG_REPORT_SPAM");
1509    recv_data.hexlike();
1510
1511    uint8 spam_type;                                        // 0 - mail, 1 - chat
1512    uint64 spammer_guid;
1513    uint32 unk1, unk2, unk3, unk4 = 0;
1514    std::string description = "";
1515    recv_data >> spam_type;                                 // unk 0x01 const, may be spam type (mail/chat)
1516    recv_data >> spammer_guid;                              // player guid
1517    switch(spam_type)
1518    {
1519        case 0:
1520            CHECK_PACKET_SIZE(recv_data, recv_data.rpos()+4+4+4);
1521            recv_data >> unk1;                              // const 0
1522            recv_data >> unk2;                              // probably mail id
1523            recv_data >> unk3;                              // const 0
1524            break;
1525        case 1:
1526            CHECK_PACKET_SIZE(recv_data, recv_data.rpos()+4+4+4+4+1);
1527            recv_data >> unk1;                              // probably language
1528            recv_data >> unk2;                              // message type?
1529            recv_data >> unk3;                              // probably channel id
1530            recv_data >> unk4;                              // unk random value
1531            recv_data >> description;                       // spam description string (messagetype, channel name, player name, message)
1532            break;
1533    }
1534
1535    // NOTE: all chat messages from this spammer automatically ignored by spam reporter until logout in case chat spam.
1536    // if it's mail spam - ALL mails from this spammer automatically removed by client
1537
1538    // Complaint Received message
1539    WorldPacket data(SMSG_COMPLAIN_RESULT, 1);
1540    data << uint8(0);
1541    SendPacket(&data);
1542
1543    sLog.outDebug("REPORT SPAM: type %u, guid %u, unk1 %u, unk2 %u, unk3 %u, unk4 %u, message %s", spam_type, GUID_LOPART(spammer_guid), unk1, unk2, unk3, unk4, description.c_str());
1544}
1545
1546void WorldSession::HandleRealmStateRequestOpcode( WorldPacket & recv_data )
1547{
1548    CHECK_PACKET_SIZE(recv_data, 4);
1549
1550    sLog.outDebug("CMSG_REALM_SPLIT");
1551
1552    uint32 unk;
1553    std::string split_date = "01/01/01";
1554    recv_data >> unk;
1555
1556    WorldPacket data(SMSG_REALM_SPLIT, 4+4+split_date.size()+1);
1557    data << unk;
1558    data << uint32(0x00000000);                             // realm split state
1559    // split states:
1560    // 0x0 realm normal
1561    // 0x1 realm split
1562    // 0x2 realm split pending
1563    data << split_date;
1564    SendPacket(&data);
1565    //sLog.outDebug("response sent %u", unk);
1566}
1567
1568void WorldSession::HandleFarSightOpcode( WorldPacket & recv_data )
1569{
1570    CHECK_PACKET_SIZE(recv_data, 1);
1571
1572    sLog.outDebug("WORLD: CMSG_FAR_SIGHT");
1573    //recv_data.hexlike();
1574
1575    uint8 unk;
1576    recv_data >> unk;
1577
1578    switch(unk)
1579    {
1580        case 0:
1581            //WorldPacket data(SMSG_CLEAR_FAR_SIGHT_IMMEDIATE, 0)
1582            //SendPacket(&data);
1583            //_player->SetUInt64Value(PLAYER_FARSIGHT, 0);
1584            sLog.outDebug("Removed FarSight from player %u", _player->GetGUIDLow());
1585            break;
1586        case 1:
1587            sLog.outDebug("Added FarSight " I64FMTD " to player %u", _player->GetUInt64Value(PLAYER_FARSIGHT), _player->GetGUIDLow());
1588            break;
1589    }
1590}
1591
1592void WorldSession::HandleChooseTitleOpcode( WorldPacket & recv_data )
1593{
1594    CHECK_PACKET_SIZE(recv_data, 4);
1595
1596    sLog.outDebug("CMSG_SET_TITLE");
1597
1598    int32 title;
1599    recv_data >> title;
1600
1601    // -1 at none
1602    if(title > 0 && title < 64)
1603    {
1604       if(!GetPlayer()->HasFlag64(PLAYER__FIELD_KNOWN_TITLES,uint64(1) << title))
1605            return;
1606    }
1607    else
1608        title = 0;
1609
1610    GetPlayer()->SetUInt32Value(PLAYER_CHOSEN_TITLE, title);
1611}
1612
1613void WorldSession::HandleAllowMoveAckOpcode( WorldPacket & recv_data )
1614{
1615    CHECK_PACKET_SIZE(recv_data, 4+4);
1616
1617    sLog.outDebug("CMSG_ALLOW_MOVE_ACK");
1618
1619    uint32 counter, time_;
1620    recv_data >> counter >> time_;
1621
1622    // time_ seems always more than getMSTime()
1623    uint32 diff = getMSTimeDiff(getMSTime(),time_);
1624
1625    sLog.outDebug("response sent: counter %u, time %u (HEX: %X), ms. time %u, diff %u", counter, time_, time_, getMSTime(), diff);
1626}
1627
1628void WorldSession::HandleResetInstancesOpcode( WorldPacket & /*recv_data*/ )
1629{
1630    sLog.outDebug("WORLD: CMSG_RESET_INSTANCES");
1631    Group *pGroup = _player->GetGroup();
1632    if(pGroup)
1633    {
1634        if(pGroup->IsLeader(_player->GetGUID()))
1635            pGroup->ResetInstances(INSTANCE_RESET_ALL, _player);
1636    }
1637    else
1638        _player->ResetInstances(INSTANCE_RESET_ALL);
1639}
1640
1641void WorldSession::HandleDungeonDifficultyOpcode( WorldPacket & recv_data )
1642{
1643    CHECK_PACKET_SIZE(recv_data, 4);
1644
1645    sLog.outDebug("MSG_SET_DUNGEON_DIFFICULTY");
1646
1647    uint32 mode;
1648    recv_data >> mode;
1649
1650    if(mode == _player->GetDifficulty())
1651        return;
1652
1653    if(mode > DIFFICULTY_HEROIC)
1654    {
1655        sLog.outError("WorldSession::HandleDungeonDifficultyOpcode: player %d sent an invalid instance mode %d!", _player->GetGUIDLow(), mode);
1656        return;
1657    }
1658
1659    // cannot reset while in an instance
1660    Map *map = _player->GetMap();
1661    if(map && map->IsDungeon())
1662    {
1663        sLog.outError("WorldSession::HandleDungeonDifficultyOpcode: player %d tried to reset the instance while inside!", _player->GetGUIDLow());
1664        return;
1665    }
1666
1667    if(_player->getLevel() < LEVELREQUIREMENT_HEROIC)
1668        return;
1669    Group *pGroup = _player->GetGroup();
1670    if(pGroup)
1671    {
1672        if(pGroup->IsLeader(_player->GetGUID()))
1673        {
1674            // the difficulty is set even if the instances can't be reset
1675            //_player->SendDungeonDifficulty(true);
1676            pGroup->ResetInstances(INSTANCE_RESET_CHANGE_DIFFICULTY, _player);
1677            pGroup->SetDifficulty(mode);
1678        }
1679    }
1680    else
1681    {
1682        _player->ResetInstances(INSTANCE_RESET_CHANGE_DIFFICULTY);
1683        _player->SetDifficulty(mode);
1684    }
1685}
1686
1687void WorldSession::HandleNewUnknownOpcode( WorldPacket & recv_data )
1688{
1689    sLog.outDebug("New Unknown Opcode %u", recv_data.GetOpcode());
1690    recv_data.hexlike();
1691    /*
1692    New Unknown Opcode 837
1693    STORAGE_SIZE: 60
1694    02 00 00 00 00 00 00 00 | 00 00 00 00 01 20 00 00
1695    89 EB 33 01 71 5C 24 C4 | 15 03 35 45 74 47 8B 42
1696    BA B8 1B 40 00 00 00 00 | 00 00 00 00 77 66 42 BF
1697    23 91 26 3F 00 00 60 41 | 00 00 00 00
1698
1699    New Unknown Opcode 837
1700    STORAGE_SIZE: 44
1701    02 00 00 00 00 00 00 00 | 00 00 00 00 00 00 80 00
1702    7B 80 34 01 84 EA 2B C4 | 5F A1 36 45 C9 39 1C 42
1703    BA B8 1B 40 CE 06 00 00 | 00 00 80 3F
1704    */
1705}
1706
1707void WorldSession::HandleDismountOpcode( WorldPacket & /*recv_data*/ )
1708{
1709    sLog.outDebug("WORLD: CMSG_CANCEL_MOUNT_AURA");
1710    //recv_data.hexlike();
1711
1712    //If player is not mounted, so go out :)
1713    if (!_player->IsMounted())                              // not blizz like; no any messages on blizz
1714    {
1715        ChatHandler(this).SendSysMessage(LANG_CHAR_NON_MOUNTED);
1716        return;
1717    }
1718
1719    if(_player->isInFlight())                               // not blizz like; no any messages on blizz
1720    {
1721        ChatHandler(this).SendSysMessage(LANG_YOU_IN_FLIGHT);
1722        return;
1723    }
1724
1725    _player->Unmount();
1726    _player->RemoveSpellsCausingAura(SPELL_AURA_MOUNTED);
1727}
1728
1729void WorldSession::HandleMoveFlyModeChangeAckOpcode( WorldPacket & recv_data )
1730{
1731    CHECK_PACKET_SIZE(recv_data, 8+4+4);
1732
1733    // fly mode on/off
1734    sLog.outDebug("WORLD: CMSG_MOVE_SET_CAN_FLY_ACK");
1735    //recv_data.hexlike();
1736
1737    uint64 guid;
1738    uint32 unk;
1739    uint32 flags;
1740
1741    recv_data >> guid >> unk >> flags;
1742
1743    _player->SetUnitMovementFlags(flags);
1744    /*
1745    on:
1746    25 00 00 00 00 00 00 00 | 00 00 00 00 00 00 80 00
1747    85 4E A9 01 19 BA 7A C3 | 42 0D 70 44 44 B0 A8 42
1748    78 15 94 40 39 03 00 00 | 00 00 80 3F
1749    off:
1750    25 00 00 00 00 00 00 00 | 00 00 00 00 00 00 00 00
1751    10 FD A9 01 19 BA 7A C3 | 42 0D 70 44 44 B0 A8 42
1752    78 15 94 40 39 03 00 00 | 00 00 00 00
1753    */
1754}
1755
1756void WorldSession::HandleRequestPetInfoOpcode( WorldPacket & /*recv_data */)
1757{
1758    /*
1759        sLog.outDebug("WORLD: CMSG_REQUEST_PET_INFO");
1760        recv_data.hexlike();
1761    */
1762}
1763
1764void WorldSession::HandleSetTaxiBenchmarkOpcode( WorldPacket & recv_data )
1765{
1766    CHECK_PACKET_SIZE(recv_data, 1);
1767
1768    uint8 mode;
1769    recv_data >> mode;
1770
1771    sLog.outDebug("Client used \"/timetest %d\" command", mode);
1772}
Note: See TracBrowser for help on using the browser.