Example #1
0
    static bool HandleBoutiqueRecupCommand(ChatHandler* handler, const char* args) {
        /*const uint64 playerGuid = handler->GetSession()->GetPlayer()->GetGUID();

        const char* reqcount = "SELECT count(*) FROM site_recuperations_cata WHERE idperso='%u'";
        QueryResult resultcount = LoginDatabase.PQuery(reqcount, playerGuid);
        Field* fieldscount = resultcount->Fetch();
        if (fieldscount[0].GetInt32()==0) {
            //Aucune r�©cup�©ration n'est disponible pour ce personnage
            handler->PSendSysMessage(11106, handler->GetSession()->GetPlayerName());
            return true;
        }

        //                        0   1           2        3               4       5      6      7            8                  9                         10           11                 12                        13          14                15                       16          17                18                       19          20                21                       22                  23                         24                    25                           26             27                    28              29                     30                    31                           32                   33                     34    35    36    37    38
        const char* req = "SELECT id, validation, idperso, niveauattribue, pvppve, stuff, monte, metierprin1, niveaumetierprin1, niveaumetierprin1palier, metierprin2, niveaumetierprin2, niveaumetierprin2palier, metiersec1, niveaumetiersec1, niveaumetiersec1palier, metiersec2, niveaumetiersec2, niveaumetiersec2palier, metiersec3, niveaumetiersec3, niveaumetiersec3palier, reputgardienshyjal, reputgardienshyjalpallier, reputcercleterrestre, reputcercleterrestrepallier, reputramkahen, reputramkahenpallier, reputtherazane, reputtherazanepallier, reputgardiensbaradin, reputgardiensbaradinpallier, reputpoinghurlenfer, reputpoinghurlenferpallier, sac1, sac2, sac3, sac4, monnaie FROM site_recuperations_cata WHERE idperso='%u' ORDER BY valid_date DESC LIMIT 1;";

        QueryResult result = SiteDatabase.PQuery(req, playerGuid);
        Field* fields = result->Fetch();
        uint32 recupId = fields[0].GetUInt32();
        uint32 validation = fields[1].GetUInt32();

        switch (validation) {
        case 0:
        case 1:
            //La r�©cup�©ration du personnage %s est en cours de validation par un Ma�®tre du Jeu. Reessayez plus tard
            handler->PSendSysMessage(11101, handler->GetSession()->GetPlayerName());
            return true;
            break;
        case 2:
            //La r�©cup�©ration du personnage %s a �©t�© invalid�©e par un Ma�®tre du Jeu. Consultez votre profil sur le site pour plus d'information.
            handler->PSendSysMessage(11102, handler->GetSession()->GetPlayerName());
            return true;
            break;
        case 3:
            //La r�©cup�©ration du personnage %s a �©t�© valid�©e partiellement par un Ma�®tre du Jeu. Consultez votre profil sur le site pour plus d'information.
            handler->PSendSysMessage(11103, handler->GetSession()->GetPlayerName());
            break;
        case 4:
            //La r�©cup�©ration du personnage %s a �©t�© valid�©e par un Ma�®tre du Jeu. Vous allez a pr�©sent recevoir votre �©quipement ainsi que les comp�©tences demand�©es.
            handler->PSendSysMessage(11104, handler->GetSession()->GetPlayerName());
            break;
        case 5:
            //La r�©cup�©ration du personnage %s a d�©j�  �©t�© effectu�©e.
            handler->PSendSysMessage(11105, handler->GetSession()->GetPlayerName());
            return true;
            break;
        default:
            //Aucune r�©cup�©ration n'est disponible pour ce personnage
            handler->PSendSysMessage(11106, handler->GetSession()->GetPlayerName());
            return true;
            break;
        }


        if (validation==3 || validation==4) {
            //Update de la base pour terminer la r�©cup�©ration (validation = 5)
            const char* requpdate = "UPDATE site_recuperations_cata SET validation='5' WHERE id='%u'";
            SiteDatabase.PExecute(requpdate, recupId);

            //recup�©ration du joueur
            Player* player = handler->GetSession()->GetPlayer();

            //niveau
            uint32 niveauattrib = fields[3].GetInt32();
            int32 oldlevel = player->getLevel();
            if(niveauattrib>oldlevel) {
                if (niveauattrib<2) niveauattrib=2;
                if (niveauattrib>STRONG_MAX_LEVEL) niveauattrib = STRONG_MAX_LEVEL;
                player->GiveLevel(niveauattrib);
                player->InitTalentForLevel();
                player->SetUInt32Value(PLAYER_XP, 0);
            }

            //competence de monte
            uint32 monte = fields[6].GetInt32();
            if (monte>=75) { //Apprentice
                uint32 competence = 33388;
                if (sSpellStore.LookupEntry(competence) && !player->HasSpell(competence)) {
                    SpellEntry const* monteCompetenceInfo= sSpellStore.LookupEntry(competence);
                    if (monteCompetenceInfo && SpellMgr::IsSpellValid(monteCompetenceInfo, player)){
                        player->learnSpell(competence, false);
                    }
                }
            }
            if (monte>=150) { //Journeyman
                uint32 competence = 33391;
                if (sSpellStore.LookupEntry(competence) && !player->HasSpell(competence)) {
                    SpellEntry const* monteCompetenceInfo= sSpellStore.LookupEntry(competence);
                    if (monteCompetenceInfo && SpellMgr::IsSpellValid(monteCompetenceInfo, player)){
                        player->learnSpell(competence, false);
                    }
                }
            }
            if (monte>=225) { //Expert
                uint32 competence = 34090;
                if (sSpellStore.LookupEntry(competence) && !player->HasSpell(competence)) {
                    SpellEntry const* monteCompetenceInfo= sSpellStore.LookupEntry(competence);
                    if (monteCompetenceInfo && SpellMgr::IsSpellValid(monteCompetenceInfo, player)){
                        player->learnSpell(competence, false);
                    }
                }
            }
            if (monte>=300) { //Artisan
                uint32 competence = 34091;
                if (sSpellStore.LookupEntry(competence) && !player->HasSpell(competence)) {
                    SpellEntry const* monteCompetenceInfo= sSpellStore.LookupEntry(competence);
                    if (monteCompetenceInfo && SpellMgr::IsSpellValid(monteCompetenceInfo, player)){
                        player->learnSpell(competence, false);
                    }
                }
            }
            if (monte>=375) { //Master
                uint32 competence = 90265;
                if (sSpellStore.LookupEntry(competence) && !player->HasSpell(competence)) {
                    SpellEntry const* monteCompetenceInfo= sSpellStore.LookupEntry(competence);
                    if (monteCompetenceInfo && SpellMgr::IsSpellValid(monteCompetenceInfo, player)){
                        player->learnSpell(competence, false);
                    }
                }
            }


            //metiers
            for (int i=0 ; i<5; i++) {
                uint32 skill = fields[7+3*i].GetInt32();
                uint32 niveau = fields[7+3*i+1].GetInt32();
                uint32 palier = fields[7+3*i+2].GetInt32();

                if (niveau>palier) niveau = palier;
                if (niveau<1) niveau = 1;

                const char* req = "SELECT count(*), competence FROM site_recuperations_cata_metiers WHERE id = '%u' AND niveau = '%u';";

                QueryResult metierres = SiteDatabase.PQuery(req, skill, palier);

                Field* metierfields = metierres->Fetch();
                if (metierfields[0].GetInt32() != 0) {
                    uint32 competence =  metierfields[1].GetInt32();

                    // .learn competence
                    if (sSpellStore.LookupEntry(competence) && !player->HasSpell(competence)) {
                        SpellEntry const* metierCompetenceInfo= sSpellStore.LookupEntry(competence);

                        if (metierCompetenceInfo && SpellMgr::IsSpellValid(metierCompetenceInfo, player)){
                            player->learnSpell(competence, false);
                        }
                    }

                    // .setskill command
                    if(SkillLineEntry const* sl = sSkillLineStore.LookupEntry(skill)) {
                        if (player->GetSkillValue(skill)) {
                            player->SetSkill(uint16(skill), player->GetSkillStep(uint16(skill)), uint16(niveau), uint16(palier));
                        }
                    }
                }
            }


            //reputations
            for (int i = 0; i<6 ; i++) {
                uint16 niveau = fields[22+2*i].GetInt16();
                uint16 palier = fields[22+2*i+1].GetInt16();

                niveau += palier;
                if (niveau<1) niveau = 1;
                if (niveau>42999) niveau = 42999;

                uint16 reputid;
                switch (i) {
                case 0: //gardiens hyjal
                    reputid = 1158;
                    break;
                case 1: //cercle terrestre
                    reputid = 1135;
                    break;
                case 2: //ramkahen
                    reputid = 1173;
                    break;
                case 3: //therazane
                    reputid = 1171;
                    break;
                case 4: //gardiens baradin (alliance)
                    if (!player->GetTeamId() == TEAM_ALLIANCE) continue;
                    reputid = 1177;
                    break;
                case 5: //poing hurlenfer (horde)
                    if (!player->GetTeamId() == TEAM_HORDE) continue;
                    reputid = 1178;
                    break;
                default:
                    continue;
                }

                FactionEntry const *factionEntry = sFactionStore.LookupEntry(reputid);
                if (factionEntry && factionEntry->reputationListID>=0)
                    player->SetReputation(reputid,niveau);
            }


            //monnaie
            uint32 monnaie = fields[38].GetInt32();
            if (monnaie>=0)
                player->ModifyMoney(player->GetMoney()+monnaie);

            //sacs
            int isac = 0;
            for (uint8 ibag = INVENTORY_SLOT_BAG_START; ibag < INVENTORY_SLOT_BAG_END; ibag++) {
                uint32 sacid = fields[34+isac].GetUInt32();
                if (isac==0 && sacid == 0) sacid = 4498;

                isac++;
                if (sacid != 0) {
                    if (Bag *pBag = (Bag*)player->GetItemByPos(INVENTORY_SLOT_BAG_0, ibag)) {

                        for (uint32 jsize = 0; jsize < pBag->GetBagSize(); jsize++){
                            if (pBag->GetItemByPos(jsize)){
                                player->DestroyItem(ibag, jsize, true);
                            }
                        }
                        if (pBag->IsEmpty()) {
                            player->DestroyItem(INVENTORY_SLOT_BAG_0, ibag, true);
                        } else continue;
                    }

                    ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(sacid);
                    if (pProto && pProto->InventoryType == INVTYPE_BAG) {
                        Item *sac = Item::CreateItem(sacid, 1);
                        player->EquipItem(ibag, sac, true);
                    }
                }
            }

            //equipement
            uint32 stuff = fields[5].GetUInt32();
            uint32 pvepvp = fields[4].GetUInt32();

            const char* reqniveau = "SELECT niveau, count(*) FROM site_recuperations_cata_stuff WHERE classe='%u' AND niveau <='%u' GROUP BY niveau ORDER BY niveau DESC LIMIT 1;";
            QueryResult resultniveau = SiteDatabase.PQuery(reqniveau, player->getClass(), niveauattrib);
            if (resultniveau) {
                Field* fieldsniveau = resultniveau->Fetch();

                if (fieldsniveau[1].GetUInt32() != 0) {
                    uint32 niveaupallier = fieldsniveau[0].GetUInt32();

                    QueryResult resultstuff;
                    Field* fieldstuff;
                    uint32 reqstufftype = 0;

                    bool stufffound = false;
                    //test avec tous les choix du joueur
                    if (!stufffound) {
                        const char* reqstuff = "SELECT count(*) FROM site_recuperations_cata_stuff WHERE classe='%u' AND stuff='%u' AND alliancehorde='%u' AND pvepvp='%u' AND niveau ='%u' ;";
                        resultstuff = SiteDatabase.PQuery(reqstuff, player->getClass(), stuff, player->GetTeamId()+1, pvepvp, niveaupallier);
                        if (resultstuff) {
                            fieldstuff = resultstuff->Fetch();
                            if (fieldstuff[0].GetUInt32() != 0) {
                                reqstufftype = 1;
                                stufffound = true;
                            }
                        }
                    }

                    //test en pve
                    if (!stufffound) {
                        const char* reqstuff = "SELECT count(*) FROM site_recuperations_cata_stuff WHERE classe='%u' AND stuff='%u' AND alliancehorde='%u' AND pvepvp='%u' AND niveau ='%u' ;";
                        resultstuff = SiteDatabase.PQuery(reqstuff, player->getClass(), stuff, player->GetTeamId()+1, 0, niveaupallier);
                        if (resultstuff) {
                            fieldstuff = resultstuff->Fetch();
                            if (fieldstuff[0].GetUInt32() != 0) {
                                reqstufftype = 2;
                                stufffound = true;
                            }
                        }
                    }

                    //test en pve neutre
                    if (!stufffound) {
                        const char* reqstuff = "SELECT count(*) FROM site_recuperations_cata_stuff WHERE classe='%u' AND stuff='%u' AND alliancehorde='%u' AND pvepvp='%u' AND niveau ='%u' ;";
                        resultstuff = SiteDatabase.PQuery(reqstuff, player->getClass(), stuff, 0, 0, niveaupallier);
                        if (resultstuff) {
                            fieldstuff = resultstuff->Fetch();
                            if (fieldstuff[0].GetUInt32() != 0) {
                                reqstufftype = 3;
                                stufffound = true;
                            }
                        }
                    }

                    //test en pve dps alli/horde
                    if (!stufffound) {
                        const char* reqstuff = "SELECT count(*) FROM site_recuperations_cata_stuff WHERE classe='%u' AND stuff='%u' AND alliancehorde='%u' AND pvepvp='%u' AND niveau ='%u' ;";
                        resultstuff = SiteDatabase.PQuery(reqstuff, player->getClass(), 0, player->GetTeamId()+1, 0, niveaupallier);
                        if (resultstuff) {
                            fieldstuff = resultstuff->Fetch();
                            if (fieldstuff[0].GetUInt32() != 0) {
                                reqstufftype = 4;
                                stufffound = true;
                            }
                        }
                    }

                    //test en pve neutre dps
                    if (!stufffound) {
                        const char* reqstuff = "SELECT count(*) FROM site_recuperations_cata_stuff WHERE classe='%u' AND stuff='%u' AND alliancehorde='%u' AND pvepvp='%u' AND niveau ='%u' ;";
                        resultstuff = SiteDatabase.PQuery(reqstuff, player->getClass(), 0, 0, 0, niveaupallier);
                        if (resultstuff) {
                            fieldstuff = resultstuff->Fetch();
                            if (fieldstuff[0].GetUInt32() != 0) {
                                reqstufftype = 5;
                                stufffound = true;
                            }
                        }
                    }

                    if (reqstufftype!=0) {

                        char* reqstuffattrib = "SELECT stuff_id FROM site_recuperations_cata_stuff WHERE classe='%u' AND stuff='%u' AND alliancehorde='%u' AND pvepvp='%u' AND niveau ='%u' ;";
                        QueryResult resultstuffattrib;


                        switch (reqstufftype) {
                        case 1:
                            resultstuffattrib = SiteDatabase.PQuery(reqstuffattrib, player->getClass(), stuff, player->GetTeamId()+1, pvepvp, niveaupallier);
                            break;
                        case 2:
                            resultstuffattrib = SiteDatabase.PQuery(reqstuffattrib, player->getClass(), stuff, player->GetTeamId()+1, 0, niveaupallier);
                            break;
                        case 3:
                            resultstuffattrib = SiteDatabase.PQuery(reqstuffattrib, player->getClass(), stuff, 0, 0, niveaupallier);
                            break;
                        case 4:
                            resultstuffattrib = SiteDatabase.PQuery(reqstuffattrib, player->getClass(), 0, player->GetTeamId()+1, 0, niveaupallier);
                            break;
                        case 5:
                            resultstuffattrib = SiteDatabase.PQuery(reqstuffattrib, player->getClass(), 0, 0, 0, niveaupallier);
                            break;
                        default:
                            break;
                        }

                        if(!resultstuffattrib)
                            return false;
                        uint32 bagpos = INVENTORY_SLOT_ITEM_START;
                        uint32 bag = INVENTORY_SLOT_BAG_0;

                        do {
                            Field* fieldstuffid = resultstuffattrib->Fetch();
                            uint32 stuffid = fieldstuffid[0].GetUInt32();

                            ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(stuffid);

                            if (pProto) {
                                if (bagpos == INVENTORY_SLOT_ITEM_END) {
                                    bagpos = 0;
                                    bag = INVENTORY_SLOT_BAG_START;
                                }

                                player->DestroyItem(bag, bagpos, true);
                                player->AddItem(stuffid, 1);

                                bagpos++;
                            }


                        } while (resultstuffattrib->NextRow());
                    }
                }
            }

        }*/

		
		/*
        Player *pPlayer = handler->GetSession()->GetPlayer();

        if(!pPlayer)
            return false;

        uint32 guidLow = pPlayer->GetGUIDLow();

	//sLog->outDebug(LOG_FILTER_NETWORKIO, "NOBODIE test1");

        QueryResult result = LoginDatabase.PQuery("SELECT id, level, stuff_wanted FROM recuperation WHERE idPerso=%u AND state=3", guidLow);
        if(!result)
        {
            handler->PSendSysMessage("Vous ne disposez pas de recuperation pour ce personnage, ou elle n'a pas encore ete validee par un maitre du jeu");
            return true;
        }

	//sLog->outDebug(LOG_FILTER_NETWORKIO, "NOBODIE test2");

        Field *recup = result->Fetch();

        uint32 id = recup[0].GetUInt32();
        uint32 stuffId = recup[2].GetUInt32();
        uint8 level = recup[1].GetUInt8();

        QueryResult metier = LoginDatabase.PQuery("SELECT skill, value, max FROM recuperation_metier WHERE idRecup = %u", id);
        QueryResult reput = LoginDatabase.PQuery("SELECT reputId, value FROM recuperation_reput WHERE idRecup = %u", id);
        QueryResult stuff = LoginDatabase.PQuery("SELECT itemId FROM recuperation_stuff WHERE spe = %u", stuffId);


        uint32 sacId = 0;
        uint32 moneyToAdd = 0;
        if(level == 85)
        {
            sacId = 21841;
            moneyToAdd = 12000 * GOLD;
        }
        else
        {
            sacId = 30744;
            moneyToAdd = 10000 * GOLD;
        }

	//sLog->outDebug(LOG_FILTER_NETWORKIO, "NOBODIE test3");

        pPlayer->ModifyMoney(moneyToAdd);

        for(uint32 i = INVENTORY_SLOT_BAG_START ; i < INVENTORY_SLOT_BAG_END ; i++)
        {
            if(Bag *pBag = (Bag*)pPlayer->GetItemByPos(INVENTORY_SLOT_BAG_0, i))
            {
                for(uint32 j = 0 ; j < pBag->GetBagSize(); j++)
                {
                    if(Item *pItem = pBag->GetItemByPos(j))
                        pPlayer->DestroyItem(INVENTORY_SLOT_BAG_0, j, false);
                }

                pPlayer->DestroyItem(INVENTORY_SLOT_BAG_0, i, true);
            }

        }

	//sLog->outDebug(LOG_FILTER_NETWORKIO, "NOBODIE test4");


        for(uint32 i = INVENTORY_SLOT_ITEM_START ; i < INVENTORY_SLOT_ITEM_END ; i++)
        {
            if(pPlayer->GetItemByPos(INVENTORY_SLOT_BAG_0, i))
                pPlayer->DestroyItem(INVENTORY_SLOT_BAG_0, i, true);
        }

	//sLog->outDebug(LOG_FILTER_NETWORKIO, "NOBODIE test5");


        for(uint32 i = 0 ; i < 4 ; i++)
        {
            pPlayer->EquipNewItem(INVENTORY_SLOT_BAG_START+i, sacId, true);
        }

	//sLog->outDebug(LOG_FILTER_NETWORKIO, "NOBODIE test6");

        pPlayer->GiveLevel(level);
        pPlayer->InitTalentForLevel();
        pPlayer->SetUInt32Value(PLAYER_XP,0);

        if(stuff)
        {
            do
            {
                Field * piece = stuff->Fetch();
                uint32 item = piece[0].GetUInt32();
                pPlayer->AddItem(item, 1);
            }
            while(stuff->NextRow());
        }

	//sLog->outDebug(LOG_FILTER_NETWORKIO, "NOBODIE test7");

        if(reput)
        {
            do
            {
                Field *rep = reput->Fetch();
                uint32 reputId = rep[0].GetUInt32();
                uint32 rank = rep[1].GetUInt32();

                FactionEntry const *fac = sFactionStore.LookupEntry(reputId);

                if(rank == 42000)
                    rank += 1000;

                pPlayer->GetReputationMgr().SetReputation(fac, rank);
            }
            while(reput->NextRow());
        }

	//sLog->outDebug(LOG_FILTER_NETWORKIO, "NOBODIE test8");

        if(metier)
        {
            do
            {
                Field *prof = metier->Fetch();

                uint32 skill = prof[0].GetUInt32();
                uint32 value = prof[1].GetUInt32();
                uint32 max = prof[2].GetUInt32();

                QueryResult profSpellQ = LoginDatabase.PQuery("SELECT competence FROM recuperation_metier_spell WHERE id = %u AND niveau = %u", skill, max);
                if(profSpellQ->GetRowCount() == 0)
                    continue;

                Field *profSpell = profSpellQ->Fetch();
                uint32 spell = profSpell->GetUInt32();

                if(!pPlayer->HasSpell(spell))
                    pPlayer->learnSpell(spell, false);

                pPlayer->SetSkill(skill, pPlayer->GetSkillStep(skill), value, max);
            }
            while(metier->NextRow());
        }

	//sLog->outDebug(LOG_FILTER_NETWORKIO, "NOBODIE test9");


        LoginDatabase.PQuery("UPDATE recuperation SET state=5 WHERE id=%u", id);

	//sLog->outDebug(LOG_FILTER_NETWORKIO, "NOBODIE test10");

        if (pPlayer->getRace() == RACE_GOBLIN)
            pPlayer->TeleportTo(1, 1569, -4398, 18, 0);
        else if (pPlayer->getRace() == RACE_WORGEN)
            pPlayer->TeleportTo(0, -8830, 626, 96, 0);

        pPlayer->SaveToDB();

	//sLog->outDebug(LOG_FILTER_NETWORKIO, "NOBODIE test11");


        return true;*/

        Player *pPlayer = handler->GetSession()->GetPlayer();

        if(!pPlayer)
            return false;

        uint32 guidLow = pPlayer->GetGUIDLow();

        QueryResult result = LoginDatabase.PQuery("SELECT id, level, stuff_wanted FROM recuperation WHERE idPerso=%u AND state=3 AND destination_realm=%u", guidLow, realmID);
        if(!result)
        {
            handler->PSendSysMessage("Vous ne disposez pas de recuperation pour ce personnage, ou elle n'a pas encore été validee par un maitre du jeu");
            return true;
        }

        Field *recup = result->Fetch();

        uint32 id = recup[0].GetUInt32();
        uint32 stuffId = recup[2].GetUInt32();
        uint8 level = recup[1].GetUInt8();

        QueryResult metier = LoginDatabase.PQuery("SELECT skill, value, max FROM recuperation_metier WHERE idRecup = %u", id);
        QueryResult reput = LoginDatabase.PQuery("SELECT reputId, value FROM recuperation_reput WHERE idRecup = %u", id);
        QueryResult stuff = LoginDatabase.PQuery("SELECT itemId FROM recuperation_stuff WHERE spe = %u", stuffId);


        uint32 sacId = 0;
        uint32 moneyToAdd = 0;
        if(level == 85)
        {
            sacId = 21841;
            moneyToAdd = 12000 * GOLD;
        }
        else
        {
            sacId = 30744;
            moneyToAdd = 10000 * GOLD;
        }

        pPlayer->ModifyMoney(moneyToAdd);

        for(uint32 i = INVENTORY_SLOT_BAG_START ; i < INVENTORY_SLOT_BAG_END ; i++)
        {
            if(Bag *pBag = (Bag*)pPlayer->GetItemByPos(INVENTORY_SLOT_BAG_0, i))
            {
                for(uint32 j = 0 ; j < pBag->GetBagSize(); j++)
                {
                    if(Item *pItem = pBag->GetItemByPos(j))
                        pPlayer->DestroyItem(INVENTORY_SLOT_BAG_0, j, false);
                }

                pPlayer->DestroyItem(INVENTORY_SLOT_BAG_0, i, true);
            }

        }

        for(uint32 i = INVENTORY_SLOT_ITEM_START ; i < INVENTORY_SLOT_ITEM_END ; i++)
        {
            if(pPlayer->GetItemByPos(INVENTORY_SLOT_BAG_0, i))
                pPlayer->DestroyItem(INVENTORY_SLOT_BAG_0, i, true);
        }

        for(uint32 i = 0 ; i < 4 ; i++)
        {
            pPlayer->EquipNewItem(INVENTORY_SLOT_BAG_START+i, sacId, true);
        }

        pPlayer->GiveLevel(level);
        pPlayer->InitTalentForLevel();
        pPlayer->SetUInt32Value(PLAYER_XP,0);

        if(stuff)
        {
            do
            {
                Field * piece = stuff->Fetch();
                uint32 item = piece[0].GetUInt32();
                pPlayer->AddItem(item, 1);
            }
            while(stuff->NextRow());
        }

        if(reput)
        {
            do
            {
                Field *rep = reput->Fetch();
                uint32 reputId = rep[0].GetUInt32();
                uint32 rank = rep[1].GetUInt32();

                FactionEntry const *fac = sFactionStore.LookupEntry(reputId);

                if(rank == 42000)
                    rank += 1000;

                pPlayer->GetReputationMgr().SetReputation(fac, rank);
            }
            while(reput->NextRow());
        }

        if(metier)
        {
            do
            {
                Field *prof = metier->Fetch();

                uint32 skill = prof[0].GetUInt32();
                uint32 value = prof[1].GetUInt32();
                uint32 max = prof[2].GetUInt32();

                QueryResult profSpellQ = LoginDatabase.PQuery("SELECT competence FROM recuperation_metier_spell WHERE id = %u AND niveau = %u", skill, max);
                if(profSpellQ->GetRowCount() == 0)
                    continue;

                Field *profSpell = profSpellQ->Fetch();
                uint32 spell = profSpell->GetUInt32();

                if(!pPlayer->HasSpell(spell))
                    pPlayer->learnSpell(spell, true);

                pPlayer->SetSkill(skill, pPlayer->GetSkillStep(skill), value, max);
            }
            while(metier->NextRow());
        }

        LoginDatabase.PQuery("UPDATE recuperation SET state=5 WHERE id=%u", id);

        if (pPlayer->getRace() == RACE_GOBLIN)
            pPlayer->TeleportTo(1, 1569, -4398, 18, 0);
        else if (pPlayer->getRace() == RACE_WORGEN)
            pPlayer->TeleportTo(0, -8830, 626, 96, 0);

        pPlayer->SaveToDB();

        return true;
    }
Example #2
0
        void UpdateAI(uint32 diff) override
        {
            if (PlayerGUID && !me->GetVictim() && me->IsAlive())
            {
                if (ExecuteSpeech_Timer <= diff)
                {
                    Player* player = ObjectAccessor::GetPlayer(*me, PlayerGUID);

                    if (!player)
                    {
                        Reset();
                        return;
                    }

                    /// @todo simplify text's selection

                    switch (player->getRace())
                    {
                        case RACE_HUMAN:
                            switch (ExecuteSpeech_Counter)
                            {
                                case 0: Talk(SAY_EXEC_START_1, player); break;
                                case 1: me->SetStandState(UNIT_STAND_STATE_STAND); break;
                                case 2: Talk(SAY_EXEC_PROG_5, player); break;
                                case 3: Talk(SAY_EXEC_NAME_1, player); break;
                                case 4: Talk(SAY_EXEC_RECOG_1, player); break;
                                case 5: Talk(SAY_EXEC_NOREM_5, player); break;
                                case 6: Talk(SAY_EXEC_THINK_7, player); break;
                                case 7: Talk(SAY_EXEC_LISTEN_1, player); break;
                                case 8:
                                    if (Creature* Plaguefist = GetClosestCreatureWithEntry(me, NPC_PLAGUEFIST, 85.0f))
                                        Plaguefist->AI()->Talk(SAY_PLAGUEFIST, player);
                                    break;
                                case 9:
                                    Talk(SAY_EXEC_TIME_6, player);
                                    me->SetStandState(UNIT_STAND_STATE_KNEEL);
                                    me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC);
                                    break;
                                case 10:
                                    Talk(SAY_EXEC_WAITING, player);
                                    break;
                                case 11:
                                    Talk(EMOTE_DIES);
                                    me->setDeathState(JUST_DIED);
                                    me->SetHealth(0);
                                    return;
                            }
                            break;
                        case RACE_ORC:
                            switch (ExecuteSpeech_Counter)
                            {
                                case 0: Talk(SAY_EXEC_START_1, player); break;
                                case 1: me->SetStandState(UNIT_STAND_STATE_STAND); break;
                                case 2: Talk(SAY_EXEC_PROG_6, player); break;
                                case 3: Talk(SAY_EXEC_NAME_1, player); break;
                                case 4: Talk(SAY_EXEC_RECOG_1, player); break;
                                case 5: Talk(SAY_EXEC_NOREM_7, player); break;
                                case 6: Talk(SAY_EXEC_THINK_8, player); break;
                                case 7: Talk(SAY_EXEC_LISTEN_1, player); break;
                                case 8:
                                    if (Creature* Plaguefist = GetClosestCreatureWithEntry(me, NPC_PLAGUEFIST, 85.0f))
                                        Plaguefist->AI()->Talk(SAY_PLAGUEFIST, player);
                                    break;
                                case 9:
                                    Talk(SAY_EXEC_TIME_8, player);
                                    me->SetStandState(UNIT_STAND_STATE_KNEEL);
                                    me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC);
                                    break;
                                case 10:
                                    Talk(SAY_EXEC_WAITING, player);
                                    break;
                                case 11:
                                    Talk(EMOTE_DIES);
                                    me->setDeathState(JUST_DIED);
                                    me->SetHealth(0);
                                    return;
                            }
                            break;
                        case RACE_DWARF:
                            switch (ExecuteSpeech_Counter)
                            {
                                case 0: Talk(SAY_EXEC_START_2, player); break;
                                case 1: me->SetStandState(UNIT_STAND_STATE_STAND); break;
                                case 2: Talk(SAY_EXEC_PROG_2, player); break;
                                case 3: Talk(SAY_EXEC_NAME_1, player); break;
                                case 4: Talk(SAY_EXEC_RECOG_3, player); break;
                                case 5: Talk(SAY_EXEC_NOREM_2, player); break;
                                case 6: Talk(SAY_EXEC_THINK_5, player); break;
                                case 7: Talk(SAY_EXEC_LISTEN_2, player); break;
                                case 8:
                                    if (Creature* Plaguefist = GetClosestCreatureWithEntry(me, NPC_PLAGUEFIST, 85.0f))
                                        Plaguefist->AI()->Talk(SAY_PLAGUEFIST, player);
                                    break;
                                case 9:
                                    Talk(SAY_EXEC_TIME_3, player);
                                    me->SetStandState(UNIT_STAND_STATE_KNEEL);
                                    me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC);
                                    break;
                                case 10:
                                    Talk(SAY_EXEC_WAITING, player);
                                    break;
                                case 11:
                                    Talk(EMOTE_DIES);
                                    me->setDeathState(JUST_DIED);
                                    me->SetHealth(0);
                                    return;
                            }
                            break;
                        case RACE_NIGHTELF:
                            switch (ExecuteSpeech_Counter)
                            {
                                case 0: Talk(SAY_EXEC_START_1, player); break;
                                case 1: me->SetStandState(UNIT_STAND_STATE_STAND); break;
                                case 2: Talk(SAY_EXEC_PROG_5, player); break;
                                case 3: Talk(SAY_EXEC_NAME_1, player); break;
                                case 4: Talk(SAY_EXEC_RECOG_1, player); break;
                                case 5: Talk(SAY_EXEC_NOREM_6, player); break;
                                case 6: Talk(SAY_EXEC_THINK_2, player); break;
                                case 7: Talk(SAY_EXEC_LISTEN_1, player); break;
                                case 8:
                                    if (Creature* Plaguefist = GetClosestCreatureWithEntry(me, NPC_PLAGUEFIST, 85.0f))
                                        Plaguefist->AI()->Talk(SAY_PLAGUEFIST, player);
                                    break;
                                case 9:
                                    Talk(SAY_EXEC_TIME_7, player);
                                    me->SetStandState(UNIT_STAND_STATE_KNEEL);
                                    me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC);
                                    break;
                                case 10:
                                    Talk(SAY_EXEC_WAITING, player);
                                    break;
                                case 11:
                                    Talk(EMOTE_DIES);
                                    me->setDeathState(JUST_DIED);
                                    me->SetHealth(0);
                                    return;
                            }
                            break;
                        case RACE_UNDEAD_PLAYER:
                            switch (ExecuteSpeech_Counter)
                            {
                                case 0: Talk(SAY_EXEC_START_1, player); break;
                                case 1: me->SetStandState(UNIT_STAND_STATE_STAND); break;
                                case 2: Talk(SAY_EXEC_PROG_3, player); break;
                                case 3: Talk(SAY_EXEC_NAME_1, player); break;
                                case 4: Talk(SAY_EXEC_RECOG_4, player); break;
                                case 5: Talk(SAY_EXEC_NOREM_3, player); break;
                                case 6: Talk(SAY_EXEC_THINK_1, player); break;
                                case 7: Talk(SAY_EXEC_LISTEN_3, player); break;
                                case 8:
                                    if (Creature* Plaguefist = GetClosestCreatureWithEntry(me, NPC_PLAGUEFIST, 85.0f))
                                        Plaguefist->AI()->Talk(SAY_PLAGUEFIST, player);
                                    break;
                                case 9:
                                    Talk(SAY_EXEC_TIME_4, player);
                                    me->SetStandState(UNIT_STAND_STATE_KNEEL);
                                    me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC);
                                    break;
                                case 10:
                                    Talk(SAY_EXEC_WAITING, player);
                                    break;
                                case 11:
                                    Talk(EMOTE_DIES);
                                    me->setDeathState(JUST_DIED);
                                    me->SetHealth(0);
                                    return;
                            }
                            break;
                        case RACE_TAUREN:
                            switch (ExecuteSpeech_Counter)
                            {
                                case 0: Talk(SAY_EXEC_START_1, player); break;
                                case 1: me->SetStandState(UNIT_STAND_STATE_STAND); break;
                                case 2: Talk(SAY_EXEC_PROG_1, player); break;
                                case 3: Talk(SAY_EXEC_NAME_1, player); break;
                                case 4: Talk(SAY_EXEC_RECOG_5, player); break;
                                case 5: Talk(SAY_EXEC_NOREM_8, player); break;
                                case 6: Talk(SAY_EXEC_THINK_9, player); break;
                                case 7: Talk(SAY_EXEC_LISTEN_1, player); break;
                                case 8:
                                    if (Creature* Plaguefist = GetClosestCreatureWithEntry(me, NPC_PLAGUEFIST, 85.0f))
                                        Plaguefist->AI()->Talk(SAY_PLAGUEFIST, player);
                                    break;
                                case 9:
                                    Talk(SAY_EXEC_TIME_9, player);
                                    me->SetStandState(UNIT_STAND_STATE_KNEEL);
                                    me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC);
                                    break;
                                case 10:
                                    Talk(SAY_EXEC_WAITING, player);
                                    break;
                                case 11:
                                    Talk(EMOTE_DIES);
                                    me->setDeathState(JUST_DIED);
                                    me->SetHealth(0);
                                    return;
                            }
                            break;
                        case RACE_GNOME:
                            switch (ExecuteSpeech_Counter)
                            {
                                case 0: Talk(SAY_EXEC_START_1, player); break;
                                case 1: me->SetStandState(UNIT_STAND_STATE_STAND); break;
                                case 2: Talk(SAY_EXEC_PROG_4, player); break;
                                case 3: Talk(SAY_EXEC_NAME_1, player); break;
                                case 4: Talk(SAY_EXEC_RECOG_1, player); break;
                                case 5: Talk(SAY_EXEC_NOREM_4, player); break;
                                case 6: Talk(SAY_EXEC_THINK_6, player); break;
                                case 7: Talk(SAY_EXEC_LISTEN_1, player); break;
                                case 8:
                                    if (Creature* Plaguefist = GetClosestCreatureWithEntry(me, NPC_PLAGUEFIST, 85.0f))
                                        Plaguefist->AI()->Talk(SAY_PLAGUEFIST, player);
                                    break;
                                case 9:
                                    Talk(SAY_EXEC_TIME_5, player);
                                    me->SetStandState(UNIT_STAND_STATE_KNEEL);
                                    me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC);
                                    break;
                                case 10:
                                    Talk(SAY_EXEC_WAITING, player);
                                    break;
                                case 11:
                                    Talk(EMOTE_DIES);
                                    me->setDeathState(JUST_DIED);
                                    me->SetHealth(0);
                                    return;
                            }
                            break;
                        case RACE_TROLL:
                            switch (ExecuteSpeech_Counter)
                            {
                                case 0: Talk(SAY_EXEC_START_3, player); break;
                                case 1: me->SetStandState(UNIT_STAND_STATE_STAND); break;
                                case 2: Talk(SAY_EXEC_PROG_7, player); break;
                                case 3: Talk(SAY_EXEC_NAME_2, player); break;
                                case 4: Talk(SAY_EXEC_RECOG_6, player); break;
                                case 5: Talk(SAY_EXEC_NOREM_9, player); break;
                                case 6: Talk(SAY_EXEC_THINK_10, player); break;
                                case 7: Talk(SAY_EXEC_LISTEN_4, player); break;
                                case 8:
                                    if (Creature* Plaguefist = GetClosestCreatureWithEntry(me, NPC_PLAGUEFIST, 85.0f))
                                        Plaguefist->AI()->Talk(SAY_PLAGUEFIST, player);
                                    break;
                                case 9:
                                    Talk(SAY_EXEC_TIME_10, player);
                                    me->SetStandState(UNIT_STAND_STATE_KNEEL);
                                    me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC);
                                    break;
                                case 10:
                                    Talk(SAY_EXEC_WAITING, player);
                                    break;
                                case 11:
                                    Talk(EMOTE_DIES);
                                    me->setDeathState(JUST_DIED);
                                    me->SetHealth(0);
                                    return;
                            }
                            break;
                        case RACE_BLOODELF:
                            switch (ExecuteSpeech_Counter)
                            {
                                case 0: Talk(SAY_EXEC_START_1, player); break;
                                case 1: me->SetStandState(UNIT_STAND_STATE_STAND); break;
                                case 2: Talk(SAY_EXEC_PROG_1, player); break;
                                case 3: Talk(SAY_EXEC_NAME_1, player); break;
                                case 4: Talk(SAY_EXEC_RECOG_1, player); break;
                                //case 5: //unknown
                                case 6: Talk(SAY_EXEC_THINK_3, player); break;
                                case 7: Talk(SAY_EXEC_LISTEN_1, player); break;
                                case 8:
                                    if (Creature* Plaguefist = GetClosestCreatureWithEntry(me, NPC_PLAGUEFIST, 85.0f))
                                        Plaguefist->AI()->Talk(SAY_PLAGUEFIST, player);
                                    break;
                                case 9:
                                    Talk(SAY_EXEC_TIME_1, player);
                                    me->SetStandState(UNIT_STAND_STATE_KNEEL);
                                    me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC);
                                    break;
                                case 10:
                                    Talk(SAY_EXEC_WAITING, player);
                                    break;
                                case 11:
                                    Talk(EMOTE_DIES);
                                    me->setDeathState(JUST_DIED);
                                    me->SetHealth(0);
                                    return;
                            }
                            break;
                        case RACE_DRAENEI:
                            switch (ExecuteSpeech_Counter)
                            {
                                case 0: Talk(SAY_EXEC_START_1, player); break;
                                case 1: me->SetStandState(UNIT_STAND_STATE_STAND); break;
                                case 2: Talk(SAY_EXEC_PROG_1, player); break;
                                case 3: Talk(SAY_EXEC_NAME_1, player); break;
                                case 4: Talk(SAY_EXEC_RECOG_2, player); break;
                                case 5: Talk(SAY_EXEC_NOREM_1, player); break;
                                case 6: Talk(SAY_EXEC_THINK_4, player); break;
                                case 7: Talk(SAY_EXEC_LISTEN_1, player); break;
                                case 8:
                                    if (Creature* Plaguefist = GetClosestCreatureWithEntry(me, NPC_PLAGUEFIST, 85.0f))
                                        Plaguefist->AI()->Talk(SAY_PLAGUEFIST, player);
                                    break;
                                case 9:
                                    Talk(SAY_EXEC_TIME_2, player);
                                    me->SetStandState(UNIT_STAND_STATE_KNEEL);
                                    me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC);
                                    break;
                                case 10:
                                    Talk(SAY_EXEC_WAITING, player);
                                    break;
                                case 11:
                                    Talk(EMOTE_DIES);
                                    me->setDeathState(JUST_DIED);
                                    me->SetHealth(0);
                                    return;
                            }
                            break;
                    }

                    if (ExecuteSpeech_Counter >= 9)
                        ExecuteSpeech_Timer = 15000;
                    else
                        ExecuteSpeech_Timer = 7000;

                    ++ExecuteSpeech_Counter;
                }
                else
                    ExecuteSpeech_Timer -= diff;
            }
        }
Example #3
0
void WorldSession::HandleWhoOpcode(WorldPacket& recv_data)
{
    DEBUG_LOG("WORLD: Received opcode CMSG_WHO");
    // recv_data.hexlike();

    uint32 clientcount = 0;

    uint32 level_min, level_max, racemask, classmask, zones_count, str_count;
    uint32 zoneids[10];                                     // 10 is client limit
    std::string player_name, guild_name;

    recv_data >> level_min;                                 // maximal player level, default 0
    recv_data >> level_max;                                 // minimal player level, default 100 (MAX_LEVEL)
    recv_data >> player_name;                               // player name, case sensitive...

    recv_data >> guild_name;                                // guild name, case sensitive...

    recv_data >> racemask;                                  // race mask
    recv_data >> classmask;                                 // class mask
    recv_data >> zones_count;                               // zones count, client limit=10 (2.0.10)

    if (zones_count > 10)
        return;                                             // can't be received from real client or broken packet

    for (uint32 i = 0; i < zones_count; ++i)
    {
        uint32 temp;
        recv_data >> temp;                                  // zone id, 0 if zone is unknown...
        zoneids[i] = temp;
        DEBUG_LOG("Zone %u: %u", i, zoneids[i]);
    }

    recv_data >> str_count;                                 // user entered strings count, client limit=4 (checked on 2.0.10)

    if (str_count > 4)
        return;                                             // can't be received from real client or broken packet

    DEBUG_LOG("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);

    std::wstring str[4];                                    // 4 is client limit
    for (uint32 i = 0; i < str_count; ++i)
    {
        std::string temp;
        recv_data >> temp;                                  // user entered string, it used as universal search pattern(guild+player name)?

        if (!Utf8toWStr(temp, str[i]))
            continue;

        wstrToLower(str[i]);

        DEBUG_LOG("String %u: %s", i, temp.c_str());
    }

    std::wstring wplayer_name;
    std::wstring wguild_name;
    if (!(Utf8toWStr(player_name, wplayer_name) && Utf8toWStr(guild_name, wguild_name)))
        return;
    wstrToLower(wplayer_name);
    wstrToLower(wguild_name);

    // client send in case not set max level value 100 but mangos support 255 max level,
    // update it to show GMs with characters after 100 level
    if (level_max >= MAX_LEVEL)
        level_max = STRONG_MAX_LEVEL;

    Team team = _player->GetTeam();
    AccountTypes security = GetSecurity();
    bool allowTwoSideWhoList = sWorld.getConfig(CONFIG_BOOL_ALLOW_TWO_SIDE_WHO_LIST);
    AccountTypes gmLevelInWhoList = (AccountTypes)sWorld.getConfig(CONFIG_UINT32_GM_LEVEL_IN_WHO_LIST);

    WorldPacket data(SMSG_WHO, 50);                         // guess size
    data << uint32(clientcount);                            // clientcount place holder, listed count
    data << uint32(clientcount);                            // clientcount place holder, online count

    // TODO: Guard Player map
    HashMapHolder<Player>::MapType& m = sObjectAccessor.GetPlayers();
    for (HashMapHolder<Player>::MapType::const_iterator itr = m.begin(); itr != m.end(); ++itr)
    {
        Player* pl = itr->second;

        if (security == SEC_PLAYER)
        {
            // player can see member of other team only if CONFIG_BOOL_ALLOW_TWO_SIDE_WHO_LIST
            if (pl->GetTeam() != team && !allowTwoSideWhoList)
                continue;

            // player can see MODERATOR, GAME MASTER, ADMINISTRATOR only if CONFIG_GM_IN_WHO_LIST
            if (pl->GetSession()->GetSecurity() > gmLevelInWhoList)
                continue;
        }

        // do not process players which are not in world
        if (!pl->IsInWorld())
            continue;

        // check if target is globally visible for player
        if (!pl->IsVisibleGloballyFor(_player))
            continue;

        // check if target's level is in level range
        uint32 lvl = pl->getLevel();
        if (lvl < level_min || lvl > level_max)
            continue;

        // check if class matches classmask
        uint32 class_ = pl->getClass();
        if (!(classmask & (1 << class_)))
            continue;

        // check if race matches racemask
        uint32 race = pl->getRace();
        if (!(racemask & (1 << race)))
            continue;

        uint32 pzoneid = pl->GetZoneId();

        bool z_show = true;
        for (uint32 i = 0; i < zones_count; ++i)
        {
            if (zoneids[i] == pzoneid)
            {
                z_show = true;
                break;
            }

            z_show = false;
        }
        if (!z_show)
            continue;

        std::string pname = pl->GetName();
        std::wstring wpname;
        if (!Utf8toWStr(pname, wpname))
            continue;
        wstrToLower(wpname);

        if (!(wplayer_name.empty() || wpname.find(wplayer_name) != std::wstring::npos))
            continue;

        std::string gname = sGuildMgr.GetGuildNameById(pl->GetGuildId());
        std::wstring wgname;
        if (!Utf8toWStr(gname, wgname))
            continue;
        wstrToLower(wgname);

        if (!(wguild_name.empty() || wgname.find(wguild_name) != std::wstring::npos))
            continue;

        std::string aname;
        if (AreaTableEntry const* areaEntry = GetAreaEntryByAreaID(pzoneid))
            aname = areaEntry->area_name[GetSessionDbcLocale()];

        bool s_show = true;
        for (uint32 i = 0; i < str_count; ++i)
        {
            if (!str[i].empty())
            {
                if (wgname.find(str[i]) != std::wstring::npos ||
                        wpname.find(str[i]) != std::wstring::npos ||
                        Utf8FitTo(aname, str[i]))
                {
                    s_show = true;
                    break;
                }
                s_show = false;
            }
        }
        if (!s_show)
            continue;

        data << pname;                                      // player name
        data << gname;                                      // guild name
        data << uint32(lvl);                                // player level
        data << uint32(class_);                             // player class
        data << uint32(race);                               // player race
        data << uint32(pzoneid);                            // player zone id

        // 50 is maximum player count sent to client
        if ((++clientcount) == 49)
            break;
    }

    uint32 count = m.size();
    data.put(0, clientcount);                               // insert right count, listed count
    data.put(4, count > 49 ? count : clientcount);          // insert right count, online count

    SendPacket(&data);
    DEBUG_LOG("WORLD: Send SMSG_WHO Message");
}
Example #4
0
void StatDumper::DumpStats()
{

    double TotalTrafficInKb = 0.0;
    double TotalTrafficOutKb = 0.0;
    double LastTotalTrafficInKb = 0.0;
    double LastTotalTrafficOutKb = 0.0;
    double TrafficInKb = 0.0;
    double TrafficOutKb = 0.0;

    double TrafficInKbsec = 0.0;
    double TrafficOutKbsec = 0.0;

    time_t timediff = 0;

    if( Filename[0] == NULL )
        return;
    FILE* f = fopen( Filename, "w" );
    if( !f )
        return;

	Log.Debug( "StatDumper", "Writing %s", Filename );

    // Dump Header
    fprintf(f, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    fprintf(f, "<?xml-stylesheet type=\"text/xsl\" href=\"server_stats.xsl\"?>\n");
    fprintf(f, "<serverpage>\n");
    fprintf(f, "  <status>\n");

	uint32 races[RACE_DRAENEI+1];
	uint32 classes[DRUID+1];
	memset(&races[0], 0, sizeof(uint32)*(RACE_DRAENEI+1));
	memset(&classes[0], 0, sizeof(uint32)*(RACE_DRAENEI+1));
    std::deque<Player*> gms;
    {
        // Dump server information.
#ifdef WIN32
		fprintf(f, "    <platform>ArcEmu %s r%u/%s-Win-%s (www.ArcEmu.org)</platform>\n", BUILD_TAG, BUILD_REVISION, CONFIG, ARCH);		
#else
		fprintf(f, "    <platform>ArcEmu %s r%u/%s-%s (www.ArcEmu.org)</platform>\n", BUILD_TAG, BUILD_REVISION, PLATFORM_TEXT, ARCH);
#endif

        char uptime[80];
        GenerateUptimeString(uptime);
        float AvgLat;
        uint32 GMCount;
        int gm = 0;
        int count = 0;
        int avg = 0;
        // lock players reader
        objmgr._playerslock.AcquireReadLock();

        HM_NAMESPACE::hash_map<uint32, Player*>::const_iterator itr;
        for (itr = objmgr._players.begin(); itr != objmgr._players.end(); itr++)
        {
            if(itr->second->GetSession() && itr->second->IsInWorld())
            {
                count++;
                avg += itr->second->GetSession()->GetLatency();
                if(itr->second->GetSession()->GetPermissionCount())
                {
                    gm++;
                    gms.push_back(itr->second);
                }
				classes[itr->second->getClass()]++;
				races[itr->second->getRace()]++;
            }            
        }
        objmgr._playerslock.ReleaseReadLock();

        AvgLat = count ? (float)((float)avg / (float)count) : 0;
        GMCount = gm;

        sWorld.QueryTotalTraffic(&TotalTrafficInKb,&TotalTrafficOutKb);

        if(LastTrafficUpdate != 0){
            sWorld.QueryLastTotalTraffic(&LastTotalTrafficInKb, &LastTotalTrafficOutKb);
            TrafficInKb = TotalTrafficInKb - LastTotalTrafficInKb;
            TrafficOutKb = TotalTrafficOutKb - LastTotalTrafficOutKb;

            timediff = UNIXTIME - LastTrafficUpdate;
            if(TrafficInKb != 0 && TrafficOutKb != 0 && timediff != 0){
                
                TrafficInKbsec = TrafficInKb / timediff;
                TrafficOutKbsec = TrafficOutKb / timediff;
            }
        }

        LastTrafficUpdate = UNIXTIME;

        fprintf(f, "    <uptime>%s</uptime>\n", uptime);
		fprintf(f, "    <oplayers>%u</oplayers>\n", (unsigned int)(sWorld.getPlayerCount()));
        fprintf(f, "    <cpu>%2.2f</cpu>\n", GetCPUUsage());
        fprintf(f, "    <qplayers>%u</qplayers>\n", (unsigned int)sWorld.GetQueueCount());
        fprintf(f, "    <ram>%.3f</ram>\n", GetRAMUsage());
        fprintf(f, "    <avglat>%.3f</avglat>\n", AvgLat);
		fprintf(f, "    <threads>%u</threads>\n", (unsigned int)ThreadPool.GetActiveThreadCount());
		fprintf(f, "    <fthreads>%u</fthreads>\n", (unsigned int)ThreadPool.GetFreeThreadCount());
        time_t t = UNIXTIME;
        fprintf(f, "    <gmcount>%u</gmcount>\n", (unsigned int)GMCount);
        fprintf(f, "    <lastupdate>%s</lastupdate>\n", asctime(localtime(&t)));
		fprintf(f, "    <alliance>%u</alliance>\n", (unsigned int)sWorld.getAlliancePlayerCount());
		fprintf(f, "    <horde>%u</horde>\n", (unsigned int)sWorld.getHordePlayerCount());
        fprintf(f, "    <acceptedconns>%u</acceptedconns>\n", (unsigned int)sWorld.mAcceptedConnections);
        fprintf(f, "    <peakcount>%u</peakcount>\n", (unsigned int)sWorld.PeakSessionCount);
		fprintf(f, "    <wdbquerysize>%u</wdbquerysize>\n", WorldDatabase.GetQueueSize());
		fprintf(f, "    <cdbquerysize>%u</cdbquerysize>\n", CharacterDatabase.GetQueueSize());
		fprintf(f, "    <bandwithin>%lf</bandwithin>\n", TrafficInKbsec);
		if( TotalTrafficInKb < 1024.0 )
                  fprintf(f, "    <bandwithintotal>%lf KB</bandwithintotal>\n", TotalTrafficInKb);
                else
                  fprintf(f, "    <bandwithintotal>%lf MB</bandwithintotal>\n", ( TotalTrafficInKb / 1024.0));
		fprintf(f, "    <bandwithout>%lf</bandwithout>\n", TrafficOutKbsec);
		if( TotalTrafficOutKb < 1024.0 )
                  fprintf(f, "    <bandwithouttotal>%lf KB</bandwithouttotal>\n", TotalTrafficOutKb);
                else
		  fprintf(f, "    <bandwithouttotal>%lf MB</bandwithouttotal>\n", ( TotalTrafficOutKb / 1024.0 ));
    }
    fprintf(f, "  </status>\n");
	static const char * race_names[RACE_DRAENEI+1] = {
		NULL,
		"human",
		"orc",
		"dwarf",
		"nightelf",
		"undead",
		"tauren",
		"gnome",
		"troll",
		NULL,
		"bloodelf",
		"draenei",
	};

	static const char * class_names[DRUID+1] = {
		NULL,
		"warrior",
		"paladin",
		"hunter",
		"rogue",
		"priest",
		"deathknight",
		"shaman",
		"mage",
		"warlock",
		NULL,
		"druid",
	};
	
	fprintf(f, "  <statsummary>\n");
	uint32 i;
	for(i = 0; i <= RACE_DRAENEI; ++i)
	{
		if( race_names[i] != NULL )
			fprintf(f, "    <%s>%u</%s>\n", race_names[i], races[i], race_names[i]);
	}

	for(i = 0; i <= DRUID; ++i)
	{
		if( class_names[i] != NULL )
			fprintf(f, "    <%s>%u</%s>\n", class_names[i], classes[i], class_names[i]);
	}
	fprintf(f, "  </statsummary>\n");

    Player * plr;
    uint32 t = (uint32)time(NULL);
    char otime[100];
    {
        fprintf(f, "  <instances>\n");
        
        // need a big buffer..
        static char buf[500000];
        memset(buf, 0, 500000);

        // Dump Instance Information
        //sWorldCreator.BuildXMLStats(buf);
		sInstanceMgr.BuildXMLStats(buf);
        fprintf(f, buf);
        fprintf(f, "  </instances>\n");
    }
    {
        // GM Information
        fprintf(f, "  <gms>\n");
        while(!gms.empty())
        {
            plr = gms.front();
            gms.pop_front();
			if(!plr->bGMTagOn)
				continue;
            FillOnlineTime(t - plr->OnlineTime, otime);
            fprintf(f, "    <gmplr>\n");
            fprintf(f, "      <name>%s</name>\n", plr->GetName());
            fprintf(f, "      <race>%u</race>\n", plr->getRace());
            fprintf(f, "      <class>%u</class>\n", (unsigned int)plr->getClass());
            fprintf(f, "      <gender>%u</gender>\n", (unsigned int)plr->getGender());
            fprintf(f, "      <pvprank>%u</pvprank>\n", (unsigned int)plr->GetPVPRank());
            fprintf(f, "      <level>%u</level>\n", (unsigned int)plr->GetUInt32Value(UNIT_FIELD_LEVEL));
            fprintf(f, "      <map>%u</map>\n", (unsigned int)plr->GetMapId());
            fprintf(f, "      <areaid>%u</areaid>\n", (unsigned int)plr->GetAreaID());
            fprintf(f, "      <ontime>%s</ontime>\n", otime);
            fprintf(f, "      <latency>%u</latency>\n", (unsigned int)plr->GetSession()->GetLatency());
            fprintf(f, "      <permissions>%s</permissions>\n", plr->GetSession()->GetPermissions());
            fprintf(f, "    </gmplr>\n");
        }

        fprintf(f, "  </gms>\n");
    }

    {
    fprintf(f, "  <sessions>\n");
        // Dump Player Information
        objmgr._playerslock.AcquireReadLock();
        HM_NAMESPACE::hash_map<uint32, Player*>::const_iterator itr;

        for (itr = objmgr._players.begin(); itr != objmgr._players.end(); itr++)
        {
            plr = itr->second;
            if(itr->second->GetSession() && itr->second->IsInWorld())
            {
                FillOnlineTime(t - plr->OnlineTime, otime);

                fprintf(f, "    <plr>\n");
                fprintf(f, "      <name>%s</name>\n", plr->GetName());
                fprintf(f, "      <race>%u</race>\n", (unsigned int)plr->getRace());
                fprintf(f, "      <class>%u</class>\n", (unsigned int)plr->getClass());
				fprintf(f, "      <gender>%u</gender>\n", (unsigned int)plr->getGender());
				fprintf(f, "      <pvprank>%u</pvprank>\n", (unsigned int)plr->GetPVPRank());
                fprintf(f, "      <level>%u</level>\n", (unsigned int)plr->GetUInt32Value(UNIT_FIELD_LEVEL));
                fprintf(f, "      <map>%u</map>\n", (unsigned int)plr->GetMapId());
                fprintf(f, "      <areaid>%u</areaid>\n", (unsigned int)plr->GetAreaID());
				//requested by Zdarkside for he's online map. I hope it does not scre up any parser. If so, then make a better one :P
                fprintf(f, "      <xpos>%f</xpos>\n", plr->GetPositionX ());
                fprintf(f, "      <ypos>%f</ypos>\n", plr->GetPositionY());
                fprintf(f, "      <ontime>%s</ontime>\n", otime);
                fprintf(f, "      <latency>%u</latency>\n", (unsigned int)plr->GetSession()->GetLatency());
                fprintf(f, "    </plr>\n");
                if(plr->GetSession()->GetPermissionCount() > 0)
                    gms.push_back(plr);
            }
        }
        objmgr._playerslock.ReleaseReadLock();
        fprintf(f, "  </sessions>\n");

        
    }

    fprintf(f, "</serverpage>\n");
    fclose(f);
}
Example #5
0
void WorldSession::HandleCharCreateOpcode( WorldPacket & recv_data )
{
	CHECK_PACKET_SIZE(recv_data, 10);
	std::string name;
	uint8 race, class_;

	recv_data >> name >> race >> class_;
	recv_data.rpos(0);

	LoginErrorCode res = VerifyName( name.c_str(), name.length() );
	if( res != CHAR_NAME_SUCCESS )
	{
		OutPacket( SMSG_CHAR_CREATE, 1, &res );
		return;
	}
	
	res = g_characterNameFilter->Parse( name, false ) ? CHAR_NAME_PROFANE : CHAR_NAME_SUCCESS;
	if( res != CHAR_NAME_SUCCESS )
	{
		OutPacket( SMSG_CHAR_CREATE, 1, &res );
		return;
	}
	
	res = objmgr.GetPlayerInfoByName(name.c_str()) == NULL ? CHAR_CREATE_SUCCESS : CHAR_CREATE_NAME_IN_USE;
	if( res != CHAR_CREATE_SUCCESS )
	{
		OutPacket( SMSG_CHAR_CREATE, 1, &res );
		return;
	}
	res = sHookInterface.OnNewCharacter( race, class_, this, name.c_str() ) ? CHAR_CREATE_SUCCESS : CHAR_CREATE_ERROR;
	if( res != CHAR_CREATE_SUCCESS )
	{
		OutPacket( SMSG_CHAR_CREATE, 1, &res );
		return;
	}

	QueryResult * result = CharacterDatabase.Query("SELECT COUNT(*) FROM banned_names WHERE name = '%s'", CharacterDatabase.EscapeString(name).c_str());
	if(result)
	{
		if(result->Fetch()[0].GetUInt32() > 0)
		{
			// That name is banned!
			res = CHAR_NAME_PROFANE;
			OutPacket( SMSG_CHAR_CREATE, 1, &res );
			delete result;
			return;
		}
		delete result;
	}
	// loading characters
	
	//checking number of chars is useless since client will not allow to create more than 10 chars
	//as the 'create' button will not appear (unless we want to decrease maximum number of characters)

	Player * pNewChar = objmgr.CreatePlayer();
	pNewChar->SetSession(this);
	if(!pNewChar->Create( recv_data ))
	{
		// failed.
		pNewChar->ok_to_remove = true;
		delete pNewChar;
		res = CHAR_CREATE_FAILED;
		OutPacket( SMSG_CHAR_CREATE, 1, &res );
		return;
	}

	//Same Faction limitation only applies to PVP and RPPVP realms :)
	uint32 realmType = sLogonCommHandler.GetRealmType();
	if( !HasGMPermissions() && realmType == REALMTYPE_PVP && _side >= 0 && !sWorld.crossover_chars) // ceberwow fixed bug
	{
		if( ((pNewChar->GetTeam()== 0) && (_side == 1)) || ((pNewChar->GetTeam()== 1) && (_side == 0)) )
		{
			pNewChar->ok_to_remove = true;
			delete pNewChar;
			res = CHAR_CREATE_PVP_TEAMS_VIOLATION;
			OutPacket( SMSG_CHAR_CREATE, 1, &res);
			return;
		}
	}
	pNewChar->UnSetBanned();
	pNewChar->addSpell(22027);	  // Remove Insignia

	if(pNewChar->getClass() == WARLOCK)
	{
		pNewChar->AddSummonSpell(416, 3110);		// imp fireball
		pNewChar->AddSummonSpell(417, 19505);
		pNewChar->AddSummonSpell(1860, 3716);
		pNewChar->AddSummonSpell(1863, 7814);
	}

	pNewChar->SaveToDB(true);	

	PlayerInfo *pn=new PlayerInfo ;
	pn->guid = pNewChar->GetLowGUID();
	pn->name = strdup(pNewChar->GetName());
	pn->cl = pNewChar->getClass();
	pn->race = pNewChar->getRace();
	pn->gender = pNewChar->getGender();
	pn->acct = GetAccountId();
	pn->m_Group=0;
	pn->subGroup=0;
	pn->m_loggedInPlayer=NULL;
	pn->team = pNewChar->GetTeam ();
	pn->guild=NULL;
	pn->guildRank=NULL;
	pn->guildMember=NULL;
#ifdef VOICE_CHAT
	pn->groupVoiceId = -1;
#endif
	objmgr.AddPlayerInfo(pn);

	pNewChar->ok_to_remove = true;
	delete  pNewChar;

	res = CHAR_CREATE_SUCCESS;
	OutPacket( SMSG_CHAR_CREATE, 1, &res );

	sLogonCommHandler.UpdateAccountCount( GetAccountId(), 1 );
}
Example #6
0
void WorldSession::HandleMirrrorImageDataRequest( WorldPacket & recv_data )
{
    sLog.outDebug("WORLD: CMSG_GET_MIRRORIMAGE_DATA");
    uint64 guid;
    recv_data >> guid;

    // Get unit for which data is needed by client
    Unit *unit = ObjectAccessor::GetObjectInWorld(guid, (Unit*)NULL);
    if(!unit)
        return;
    // Get creator of the unit
    Unit *creator = ObjectAccessor::GetObjectInWorld(unit->GetCreatorGUID(),(Unit*)NULL);
    if (!creator)
        return;
    WorldPacket data(SMSG_MIRRORIMAGE_DATA, 68);
    data << (uint64)guid;
    data << (uint32)creator->GetDisplayId();
    if (creator->GetTypeId()==TYPEID_PLAYER)
    {
        Player * pCreator = (Player *)creator;
        data << (uint8)pCreator->getRace();
        data << (uint8)pCreator->getGender();
        data << (uint8)pCreator->getClass();
        data << (uint8)pCreator->GetByteValue(PLAYER_BYTES, 0); // skin

        data << (uint8)pCreator->GetByteValue(PLAYER_BYTES, 1); // face
        data << (uint8)pCreator->GetByteValue(PLAYER_BYTES, 2); // hair
        data << (uint8)pCreator->GetByteValue(PLAYER_BYTES, 3); // haircolor
        data << (uint8)pCreator->GetByteValue(PLAYER_BYTES_2, 0); // facialhair

        data << (uint32)pCreator->GetGuildId();  // unk
        static const EquipmentSlots ItemSlots[] = 
        {
            EQUIPMENT_SLOT_HEAD,
            EQUIPMENT_SLOT_SHOULDERS,
            EQUIPMENT_SLOT_BODY,
            EQUIPMENT_SLOT_CHEST,
            EQUIPMENT_SLOT_WAIST,
            EQUIPMENT_SLOT_LEGS,
            EQUIPMENT_SLOT_FEET,
            EQUIPMENT_SLOT_WRISTS,
            EQUIPMENT_SLOT_HANDS,
            EQUIPMENT_SLOT_BACK,
            EQUIPMENT_SLOT_TABARD,
            EQUIPMENT_SLOT_END
        };
        // Display items in visible slots
        for (EquipmentSlots const* itr = &ItemSlots[0];*itr!=EQUIPMENT_SLOT_END;++itr)
        {
            if (*itr == EQUIPMENT_SLOT_HEAD && pCreator->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
                data << (uint32)0;
            else if (*itr == EQUIPMENT_SLOT_BACK && pCreator->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
                data << (uint32)0;
            else if (Item const *item = pCreator->GetItemByPos(INVENTORY_SLOT_BAG_0, *itr))
                data << (uint32)item->GetProto()->DisplayInfoID;
            else
                data << (uint32)0;
        }
    }
    else
    {
        // Skip player data for creatures
        data << (uint32)0;
        data << (uint32)0;
        data << (uint32)0;
        data << (uint32)0;
        data << (uint32)0;
        data << (uint32)0;
        data << (uint32)0;
        data << (uint32)0;
        data << (uint32)0;
        data << (uint32)0;
        data << (uint32)0;
        data << (uint32)0;
        data << (uint32)0;
        data << (uint32)0;
    }
    SendPacket( &data );
}
Example #7
0
void WorldSession::HandleCharCreateOpcode(WorldPacket & recv_data)
{
    CHECK_PACKET_SIZE(recv_data, 10);
    std::string name;
    uint8 race, class_;

    recv_data >> name >> race >> class_;
    recv_data.rpos(0);

    LoginErrorCode res = VerifyName(name.c_str(), name.length());
    if (res != E_CHAR_NAME_SUCCESS)
    {
        OutPacket(SMSG_CHAR_CREATE, 1, &res);
        return;
    }

    res = g_characterNameFilter->Parse(name, false) ? E_CHAR_NAME_PROFANE : E_CHAR_NAME_SUCCESS;
    if (res != E_CHAR_NAME_SUCCESS)
    {
        OutPacket(SMSG_CHAR_CREATE, 1, &res);
        return;
    }

    res = objmgr.GetPlayerInfoByName(name.c_str()) == NULL ? E_CHAR_CREATE_SUCCESS : E_CHAR_CREATE_NAME_IN_USE;
    if (res != E_CHAR_CREATE_SUCCESS)
    {
        OutPacket(SMSG_CHAR_CREATE, 1, &res);
        return;
    }

    res = sHookInterface.OnNewCharacter(race, class_, this, name.c_str()) ? E_CHAR_CREATE_SUCCESS : E_CHAR_CREATE_ERROR;
    if (res != E_CHAR_CREATE_SUCCESS)
    {
        OutPacket(SMSG_CHAR_CREATE, 1, &res);
        return;
    }

    QueryResult* result = CharacterDatabase.Query("SELECT COUNT(*) FROM banned_names WHERE name = '%s'", CharacterDatabase.EscapeString(name).c_str());
    if (result)
    {
        if (result->Fetch()[0].GetUInt32() > 0)
        {
            // That name is banned!
            OutPacket(SMSG_CHAR_CREATE, 1, CHAR_NAME_PROFANE);
            delete result;
            return;
        }
        delete result;
    }

    // Check if player got Death Knight already on this realm.
    if (Config.OptionalConfig.GetBoolDefault("ClassOptions", "DeathKnightLimit", true) && has_dk
        && (class_ == DEATHKNIGHT))
    {
        OutPacket(SMSG_CHAR_CREATE, 1, CHAR_CREATE_UNIQUE_CLASS_LIMIT);
        return;
    }

    // loading characters

    // Check the number of characters, so we can't make over 10.
    // They're able to manage to create >10 sometimes, not exactly sure how ..

    result = CharacterDatabase.Query("SELECT COUNT(*) FROM characters WHERE acct = %u", GetAccountId());
    if (result)
    {
        if (result->Fetch()[0].GetUInt32() >= 10)
        {
            // We can't make any more characters.
            OutPacket(SMSG_CHAR_CREATE, 1, CHAR_CREATE_SERVER_LIMIT);
            delete result;
            return;
        }
        delete result;
    }

    Player* pNewChar = objmgr.CreatePlayer(class_);
    pNewChar->SetSession(this);
    if (!pNewChar->Create(recv_data))
    {
        // failed.
        pNewChar->ok_to_remove = true;
        delete pNewChar;
        OutPacket(SMSG_CHAR_CREATE, 1, CHAR_CREATE_FAILED);
        return;
    }

    //Same Faction limitation only applies to PVP and RPPVP realms :)
    uint32 realmType = sLogonCommHandler.GetRealmType();
    if (!HasGMPermissions() && realmType == REALMTYPE_PVP && _side >= 0 && !sWorld.crossover_chars)  // ceberwow fixed bug
    {
        if ((pNewChar->IsTeamAlliance() && (_side == 1)) || (pNewChar->IsTeamHorde() && (_side == 0)))
        {
            pNewChar->ok_to_remove = true;
            delete pNewChar;
            OutPacket(SMSG_CHAR_CREATE, 1, CHAR_CREATE_PVP_TEAMS_VIOLATION);
            return;
        }
    }

    //Check if player has a level 55 or higher character on this realm and allow him to create DK.
    //This check can be turned off in optional.conf
    if (Config.OptionalConfig.GetBoolDefault("ClassOptions", "DeathKnightPreReq", false) && !has_level_55_char
        && (class_ == DEATHKNIGHT))
    {
        pNewChar->ok_to_remove = true;
        delete pNewChar;
        /*
        WorldPacket data(1);
        data.SetOpcode(SMSG_CHAR_CREATE);
        data << (uint8)56 + 1; // This errorcode is not the actual one. Need to find a real error code.
        SendPacket( &data );
        */
        OutPacket(SMSG_CHAR_CREATE, 1, CHAR_CREATE_LEVEL_REQUIREMENT);
        return;
    }

    pNewChar->UnSetBanned();
    pNewChar->addSpell(22027);      // Remove Insignia

    if (pNewChar->getClass() == WARLOCK)
    {
        pNewChar->AddSummonSpell(416, 3110);        // imp fireball
        pNewChar->AddSummonSpell(417, 19505);
        pNewChar->AddSummonSpell(1860, 3716);
        pNewChar->AddSummonSpell(1863, 7814);
    }

    pNewChar->SaveToDB(true);

    PlayerInfo* pn = new PlayerInfo;
    pn->guid = pNewChar->GetLowGUID();
    pn->name = strdup(pNewChar->GetName());
    pn->class_ = pNewChar->getClass();
    pn->race = pNewChar->getRace();
    pn->gender = pNewChar->getGender();
    pn->acct = GetAccountId();
    pn->m_Group = 0;
    pn->subGroup = 0;
    pn->m_loggedInPlayer = NULL;
    pn->team = pNewChar->GetTeam();
    pn->guild = NULL;
    pn->guildRank = NULL;
    pn->guildMember = NULL;
    pn->lastOnline = UNIXTIME;
    objmgr.AddPlayerInfo(pn);

    pNewChar->ok_to_remove = true;
    delete  pNewChar;

    OutPacket(SMSG_CHAR_CREATE, 1, CHAR_CREATE_SUCCESS);

    sLogonCommHandler.UpdateAccountCount(GetAccountId(), 1);
}
Example #8
0
//show info of player
bool ChatHandler::HandlePInfoCommand(const char* args)
{
    Player* target;
    uint64 target_guid;
    std::string target_name;
    if (!extractPlayerTarget((char*)args, &target, &target_guid, &target_name))
        return false;

    uint32 accId = 0;
    uint32 money = 0;
    uint32 total_player_time = 0;
    uint8 level = 0;
    uint32 latency = 0;
    uint8 race;
    uint8 Class;
    bool p_jail_isjailed;
    uint32 p_jail_guid;
    std::string p_jail_char;
    uint32 p_jail_release;
    bool p_jail_amnestietime;
    std::string p_jail_reason;
    uint32 p_jail_times;
    uint32 p_jail_gmacc;
    std::string p_jail_gmchar;
    std::string p_jail_lasttime;
    uint32 p_jail_duration;
    std::string gmname;
    int64 muteTime = 0;
    int64 banTime = -1;

    // get additional information from Player object
    if (target)
    {
        // check online security
        if (HasLowerSecurity(target, 0))
            return false;

        accId = target->GetSession()->GetAccountId();
        money = target->GetMoney();
        total_player_time = target->GetTotalPlayedTime();
        level = target->getLevel();
        latency = target->GetSession()->GetLatency();
        race = target->getRace();
        Class = target->getClass();
        p_jail_isjailed = target->m_jail_isjailed;
        p_jail_guid = target->m_jail_guid;
        p_jail_char = target->m_jail_char;
        p_jail_release = target->m_jail_release;
        p_jail_amnestietime = target->m_jail_amnestietime;
        p_jail_reason = target->m_jail_reason;
        p_jail_times =  target->m_jail_times;
        p_jail_gmacc =  target->m_jail_gmacc;
        p_jail_gmchar = target->m_jail_gmchar;
        p_jail_lasttime = target->m_jail_lasttime;
        p_jail_duration = target->m_jail_duration;
        gmname = target->GetName();
        muteTime = target->GetSession()->m_muteTime;
    }
    // get additional information from DB
    else
    {
        // check offline security
        if (HasLowerSecurity(NULL, target_guid))
            return false;

        //                                                     0          1      2      3        4     5
        QueryResult result = CharacterDatabase.PQuery("SELECT totaltime, level, money, account, race, class FROM characters WHERE guid = '%u'", GUID_LOPART(target_guid));
        if (!result)
        {
            return false;
		}
		else
		{
            Field *fields = result->Fetch();
            total_player_time = fields[0].GetUInt32();
            level = fields[1].GetUInt32();
            money = fields[2].GetUInt32();
            accId = fields[3].GetUInt32();
            race = fields[4].GetUInt8();
            Class = fields[5].GetUInt8();
        }

		QueryResult row = CharacterDatabase.PQuery("SELECT * FROM `jail` WHERE `guid`='%u' LIMIT 1", GUID_LOPART(target_guid));

        if (!row)
        {
            p_jail_isjailed = false;
        }
        else
        {
            Field *data = row->Fetch();
            p_jail_isjailed = true;
            p_jail_guid = data[0].GetUInt32();
            p_jail_char = data[1].GetString();
            p_jail_release = data[2].GetUInt32();
            p_jail_amnestietime = data[3].GetUInt32();
            p_jail_reason = data[4].GetString();
            p_jail_times = data[5].GetUInt32();
            p_jail_gmacc = data[6].GetUInt32();
            p_jail_gmchar = data[7].GetString();
            p_jail_lasttime = data[8].GetString();
            p_jail_duration = data[9].GetUInt32();
            gmname = "";
        }
    }

    std::string username = GetTrinityString(LANG_ERROR);
    std::string email = GetTrinityString(LANG_ERROR);
    std::string last_ip = GetTrinityString(LANG_ERROR);
    uint32 security = 0;
    std::string last_login = GetTrinityString(LANG_ERROR);

    QueryResult result = LoginDatabase.PQuery("SELECT a.username, aa.gmlevel, a.email, a.last_ip, a.last_login, a.mutetime "
                                                "FROM account a "
                                                "LEFT JOIN account_access aa "
                                                "ON (a.id = aa.id) "
                                                "WHERE a.id = '%u'", accId);
    if (result)
    {
        Field* fields = result->Fetch();
        username = fields[0].GetString();
        security = fields[1].GetUInt32();
        email = fields[2].GetString();
        muteTime = fields[5].GetUInt64();

        if (email.empty())
            email = "-";

        if (!m_session || m_session->GetSecurity() >= AccountTypes(security))
        {
            last_ip = fields[3].GetString();
            last_login = fields[4].GetString();
        }
        else
        {
            last_ip = "-";
            last_login = "******";
        }
    }

    std::string nameLink = playerLink(target_name);

    PSendSysMessage(LANG_PINFO_ACCOUNT, (target?"":GetTrinityString(LANG_OFFLINE)), nameLink.c_str(), GUID_LOPART(target_guid), username.c_str(), accId, email.c_str(), security, last_ip.c_str(), last_login.c_str(), latency);

    if (QueryResult result = LoginDatabase.PQuery("SELECT unbandate, bandate = unbandate FROM account_banned WHERE id = '%u' AND active ORDER BY bandate ASC LIMIT 1", accId))
    {
        Field * fields = result->Fetch();
        banTime = fields[1].GetBool() ? 0 : fields[0].GetUInt64();
    }
    else if (QueryResult result = CharacterDatabase.PQuery("SELECT unbandate, bandate = unbandate FROM character_banned WHERE guid = '%u' AND active ORDER BY bandate ASC LIMIT 1", GUID_LOPART(target_guid)))
    {
        Field * fields = result->Fetch();
        banTime = fields[1].GetBool() ? 0 : fields[0].GetUInt64();
    }

    muteTime = muteTime - time(NULL);
    if (muteTime > 0 || banTime >= 0)
        PSendSysMessage(LANG_PINFO_MUTE_BAN, muteTime > 0 ? secsToTimeString(muteTime, true).c_str() : "---", !banTime ? "perm." : (banTime > 0 ? secsToTimeString(banTime - time(NULL), true).c_str() : "---"));

    std::string race_s, Class_s;
    switch(race)
    {
        case RACE_HUMAN:            race_s = "Human";       break;
        case RACE_ORC:              race_s = "Orc";         break;
        case RACE_DWARF:            race_s = "Dwarf";       break;
        case RACE_NIGHTELF:         race_s = "Night Elf";   break;
        case RACE_UNDEAD_PLAYER:    race_s = "Undead";      break;
        case RACE_TAUREN:           race_s = "Tauren";      break;
        case RACE_GNOME:            race_s = "Gnome";       break;
        case RACE_TROLL:            race_s = "Troll";       break;
        case RACE_BLOODELF:         race_s = "Blood Elf";   break;
        case RACE_DRAENEI:          race_s = "Draenei";     break;
    }
    switch(Class)
    {
        case CLASS_WARRIOR:         Class_s = "Warrior";        break;
        case CLASS_PALADIN:         Class_s = "Paladin";        break;
        case CLASS_HUNTER:          Class_s = "Hunter";         break;
        case CLASS_ROGUE:           Class_s = "Rogue";          break;
        case CLASS_PRIEST:          Class_s = "Priest";         break;
        case CLASS_DEATH_KNIGHT:    Class_s = "Death Knight";   break;
        case CLASS_SHAMAN:          Class_s = "Shaman";         break;
        case CLASS_MAGE:            Class_s = "Mage";           break;
        case CLASS_WARLOCK:         Class_s = "Warlock";        break;
        case CLASS_DRUID:           Class_s = "Druid";          break;
    }

    std::string timeStr = secsToTimeString(total_player_time, true, true);
    uint32 gold = money /GOLD;
    uint32 silv = (money % GOLD) / SILVER;
    uint32 copp = (money % GOLD) % SILVER;
    PSendSysMessage(LANG_PINFO_LEVEL, race_s.c_str(), Class_s.c_str(), timeStr.c_str(), level, gold, silv, copp);

	if (p_jail_times > 0)
    {
        if(p_jail_release > 0)
        {
            time_t localtime;
            localtime = time(NULL);
            uint32 min_left = (uint32)floor(float(p_jail_release - localtime) / 60);

            if (min_left <= 0)
            {
                p_jail_release = 0;
                CharacterDatabase.PExecute("UPDATE `jail` SET `release`='%u' WHERE `guid`='%u' LIMIT 1", p_jail_release, p_jail_guid);
                PSendSysMessage(LANG_JAIL_GM_INFO, p_jail_char.c_str(), p_jail_times, 0, p_jail_gmchar.c_str(), p_jail_reason.c_str());
                return true;
            }
            else
            {
                PSendSysMessage(LANG_JAIL_GM_INFO, p_jail_char.c_str(), p_jail_times, min_left, p_jail_gmchar.c_str(), p_jail_reason.c_str());
                return true;
            }
        }
        else
        {
            PSendSysMessage(LANG_JAIL_GM_INFO, p_jail_char.c_str(), p_jail_times, 0, p_jail_gmchar.c_str(), p_jail_reason.c_str());
            return true;
        }
    }
    else
    {
        PSendSysMessage(LANG_JAIL_GM_NOINFO, gmname.c_str());
        return true;
    }

    return true;
}
Example #9
0
void Lacrimi::DumpStats()
{
    if( Filename[0] == '\0' )
        return;
    FILE* f = fopen( Filename, "w" );
    if( !f )
        return;

    sLog.Debug("Lacrimi", "Dumping stats...");

    // Dump Header
    fprintf(f, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    fprintf(f, "<?xml-stylesheet type=\"text/xsl\" href=\"server_stats.xsl\"?>\n");
    fprintf(f, "<serverpage>\n");
    fprintf(f, "  <status>\n");

    uint32* races = new uint32[RACE_WORGEN+1];
    uint32* classes = new uint32[DRUID+1];
    memset(races, 0, sizeof(uint32)*(RACE_WORGEN+1));
    memset(classes, 0, sizeof(uint32)*(DRUID+1));
    std::deque<Player*> gms;
    {
        // Dump server information.
        fprintf(f, "    <platform>Sandshroud Hearthstone(%s::%s) r%u %s-%s</platform>\n", BUILD_TAG, BUILD_HASH_STR, BUILD_REVISION, CONFIG, ARCH);

        char *uptime = new char[80];
        GenerateUptimeString(uptime);
        time_t t = (time_t)UNIXTIME;
        float AvgLat;
        uint32 GMCount;
        int gm = 0;
        int count = 0;
        int avg = 0;

        // lock players reader
        objmgr._playerslock.AcquireReadLock();

        HM_NAMESPACE::hash_map<uint32, Player*>::const_iterator itr;
        for (itr = objmgr._players.begin(); itr != objmgr._players.end(); itr++)
        {
            if(itr->second->GetSession() && itr->second->IsInWorld())
            {
                count++;
                avg += itr->second->GetSession()->GetLatency();
                if(itr->second->GetSession()->GetPermissionCount())
                {
                    gm++;
                    gms.push_back(itr->second);
                }
                classes[itr->second->getClass()]++;
                races[itr->second->getRace()]++;
            }           
        }
        objmgr._playerslock.ReleaseReadLock();

        AvgLat = count ? (float)((float)avg / (float)count) : 0;
        GMCount = gm;

        fprintf(f, "    <servername>%s</servername>\n", mainIni->ReadString("RealmData", "RealmName", "Test Realm").c_str());
        fprintf(f, "    <uptime>%s</uptime>\n", uptime);
        fprintf(f, "    <oplayers>%u</oplayers>\n", (unsigned int)sWorld.GetSessionCount());
        fprintf(f, "    <cpu>%2.2f</cpu>\n", sWorld.GetCPUUsage(true));
        fprintf(f, "    <qplayers>%u</qplayers>\n", (unsigned int)sWorld.GetQueueCount());
        fprintf(f, "    <ram>%.3f</ram>\n", sWorld.GetRAMUsage(true));
        fprintf(f, "    <avglat>%.3f</avglat>\n", AvgLat);
        fprintf(f, "    <threads>%u</threads>\n", (unsigned int)ThreadPool.GetActiveThreadCount());
        fprintf(f, "    <gmcount>%u</gmcount>\n", (unsigned int)GMCount);
        fprintf(f, "    <lastupdate>%s</lastupdate>\n", asctime(localtime(&t)));
        fprintf(f, "    <alliance>%u</alliance>\n", (unsigned int)sWorld.AlliancePlayers);
        fprintf(f, "    <horde>%u</horde>\n", (unsigned int)sWorld.HordePlayers);
        fprintf(f, "    <acceptedconns>%u</acceptedconns>\n", (unsigned int)sWorld.mAcceptedConnections);
        fprintf(f, "    <peakcount>%u</peakcount>\n", (unsigned int)sWorld.PeakSessionCount);
        fprintf(f, "    <wdbquerysize>%u</wdbquerysize>\n", WorldDatabase.GetQueueSize());
        fprintf(f, "    <cdbquerysize>%u</cdbquerysize>\n", CharacterDatabase.GetQueueSize());
        delete [] uptime;
    }

    fprintf(f, "  </status>\n");
    
    fprintf(f, "  <statsummary>\n");
    uint32 i;
    for(i = 0; i <= RACE_WORGEN; ++i)
    {
        if( race_names[i] != NULL )
            fprintf(f, "    <%s>%u</%s>\n", race_names[i], races[i], race_names[i]);
    }

    for(i = 0; i <= DRUID; ++i)
    {
        if( class_names[i] != NULL )
            fprintf(f, "    <%s>%u</%s>\n", class_names[i], classes[i], class_names[i]);
    }
    fprintf(f, "  </statsummary>\n");

    Player*  plr;
    uint32 t = (uint32)time(NULL);

    char otime[100];
    {
        fprintf(f, "  <instances>\n");
        
        // need a big buffer..
        char *buf = new char[500000];
        memset(buf, 0, 500000);

        // Dump Instance Information
        //sWorldCreator.BuildXMLStats(buf);
        sInstanceMgr.BuildXMLStats(buf);
        fprintf(f, buf);
        fprintf(f, "  </instances>\n");
        delete [] buf;
    }

    {
        // GM Information
        fprintf(f, "  <gms>\n");
        while(!gms.empty())
        {
            plr = gms.front();
            gms.pop_front();

            if(plr->bGMTagOn)
            {
                FillOnlineTime(t - plr->OnlineTime, otime);
                fprintf(f, "    <gmplr>\n");
                fprintf(f, "      <name>%s%s</name>\n", (plr->bGMTagOn ? "{GM}" : ""), plr->GetName());
                fprintf(f, "      <race>%u</race>\n", plr->getRace());
                fprintf(f, "      <class>%u</class>\n", (unsigned int)plr->getClass());
                fprintf(f, "      <gender>%u</gender>\n", (unsigned int)plr->getGender());
                fprintf(f, "      <pvprank>%u</pvprank>\n", (unsigned int)plr->GetPVPRank());
                fprintf(f, "      <level>%u</level>\n", (unsigned int)plr->GetUInt32Value(UNIT_FIELD_LEVEL));
                fprintf(f, "      <map>%u</map>\n", (unsigned int)plr->GetMapId());
                fprintf(f, "      <areaid>%u</areaid>\n", (unsigned int)plr->GetAreaId());
                fprintf(f, "      <ontime>%s</ontime>\n", otime);
                fprintf(f, "      <latency>%u</latency>\n", (unsigned int)plr->GetSession()->GetLatency());
                fprintf(f, "      <permissions>%s</permissions>\n", plr->GetSession()->GetPermissions());
                fprintf(f, "    </gmplr>\n");
            }
        }

        fprintf(f, "  </gms>\n");
    }

    {
        fprintf(f, "  <sessions>\n");

        // Dump Player Information
        objmgr._playerslock.AcquireReadLock();
        HM_NAMESPACE::hash_map<uint32, Player*>::const_iterator itr;

        for (itr = objmgr._players.begin(); itr != objmgr._players.end(); itr++)
        {
            plr = itr->second;
            if(itr->second->GetSession() && itr->second->IsInWorld())
            {
                FillOnlineTime(t - plr->OnlineTime, otime);

                fprintf(f, "    <plr>\n");
                fprintf(f, "      <name>%s</name>\n", plr->GetName());
                fprintf(f, "      <race>%u</race>\n", (unsigned int)plr->getRace());
                fprintf(f, "      <class>%u</class>\n", (unsigned int)plr->getClass());
                fprintf(f, "      <gender>%u</gender>\n", (unsigned int)plr->getGender());
                fprintf(f, "      <pvprank>%u</pvprank>\n", (unsigned int)plr->GetPVPRank());
                fprintf(f, "      <level>%u</level>\n", (unsigned int)plr->GetUInt32Value(UNIT_FIELD_LEVEL));
                fprintf(f, "      <map>%u</map>\n", (unsigned int)plr->GetMapId());
                fprintf(f, "      <areaid>%u</areaid>\n", (unsigned int)plr->GetAreaId());
                //requested by Zdarkside for he's online map. I hope it does not screw up any parser. If so, then make a better one :P
                fprintf(f, "      <xpos>%f</xpos>\n", plr->GetPositionX ());
                fprintf(f, "      <ypos>%f</ypos>\n", plr->GetPositionY());
                fprintf(f, "      <ontime>%s</ontime>\n", otime);
                fprintf(f, "      <latency>%u</latency>\n", (unsigned int)plr->GetSession()->GetLatency());
                fprintf(f, "    </plr>\n");
                if(plr->GetSession()->GetPermissionCount() > 0)
                    gms.push_back(plr);
            }
        }

        objmgr._playerslock.ReleaseReadLock();
        fprintf(f, "  </sessions>\n");

        
    }

    delete [] races;
    delete [] classes;
    fprintf(f, "</serverpage>\n");
    fclose(f);
}
Example #10
0
void WorldSession::HandlePlayerLogin(LoginQueryHolder *holder)
{
    uint64 playerGuid = holder->GetGuid();

    Player *pCurrChar = new Player(this);
    pCurrChar->GetMotionMaster()->Initialize();

    // "GetAccountId()==db stored account id" checked in LoadFromDB (prevent login not own character using cheating tools)
    if(!pCurrChar->LoadFromDB(GUID_LOPART(playerGuid), holder))
    {
        KickPlayer();                                       // disconnect client, player no set to session and it will not deleted or saved at kick
        delete pCurrChar;                                   // delete it manually
        delete holder;                                      // delete all unprocessed queries
        m_playerLoading = false;
        return;
    }

    SetPlayer(pCurrChar);

    WorldPacket data( SMSG_LOGIN_VERIFY_WORLD, 20 );
    data << pCurrChar->GetMapId();
    data << pCurrChar->GetPositionX();
    data << pCurrChar->GetPositionY();
    data << pCurrChar->GetPositionZ();
    data << pCurrChar->GetOrientation();
    SendPacket(&data);

    data.Initialize( SMSG_ACCOUNT_DATA_TIMES, 128 );
    for(int i = 0; i < 32; ++i)
        data << uint32(0);
    SendPacket(&data);

    // Send MOTD (1.12.1 not have SMSG_MOTD, so do it in another way)
    {
        uint32 linecount=0;
        std::string str_motd = sWorld.GetMotd();
        std::string::size_type pos, nextpos;
        std::string motd;

        pos = 0;
        while ( (nextpos= str_motd.find('@',pos)) != std::string::npos )
        {
            if (nextpos != pos)
            {
                ChatHandler(pCurrChar).PSendSysMessage(str_motd.substr(pos,nextpos-pos).c_str());
                ++linecount;
            }
            pos = nextpos + 1;
        }

        if (pos < str_motd.length())
        {
            ChatHandler(pCurrChar).PSendSysMessage(str_motd.substr(pos).c_str());
            ++linecount;
        }

        DEBUG_LOG( "WORLD: Sent motd (SMSG_MOTD)" );
    }

    //QueryResult *result = CharacterDatabase.PQuery("SELECT guildid,rank FROM guild_member WHERE guid = '%u'",pCurrChar->GetGUIDLow());
    QueryResult *resultGuild = holder->GetResult(PLAYER_LOGIN_QUERY_LOADGUILD);

    if(resultGuild)
    {
        Field *fields = resultGuild->Fetch();
        pCurrChar->SetInGuild(fields[0].GetUInt32());
        pCurrChar->SetRank(fields[1].GetUInt32());
        delete resultGuild;
    }
    else if(pCurrChar->GetGuildId())                        // clear guild related fields in case wrong data about nonexistent membership
    {
        pCurrChar->SetInGuild(0);
        pCurrChar->SetRank(0);
    }

    if(pCurrChar->GetGuildId() != 0)
    {
        Guild* guild = sObjectMgr.GetGuildById(pCurrChar->GetGuildId());
        if(guild)
        {
            data.Initialize(SMSG_GUILD_EVENT, (2+guild->GetMOTD().size()+1));
            data << uint8(GE_MOTD);
            data << uint8(1);
            data << guild->GetMOTD();
            SendPacket(&data);
            DEBUG_LOG( "WORLD: Sent guild-motd (SMSG_GUILD_EVENT)" );

            guild->BroadcastEvent(GE_SIGNED_ON, pCurrChar->GetObjectGuid(), pCurrChar->GetName());
        }
        else
        {
            // remove wrong guild data
            sLog.outError("Player %s (GUID: %u) marked as member of nonexistent guild (id: %u), removing guild membership for player.",pCurrChar->GetName(),pCurrChar->GetGUIDLow(),pCurrChar->GetGuildId());
            pCurrChar->SetInGuild(0);
        }
    }

    if(!pCurrChar->isAlive())
        pCurrChar->SendCorpseReclaimDelay(true);

    pCurrChar->SendInitialPacketsBeforeAddToMap();

    //Show cinematic at the first time that player login
    if( !pCurrChar->getCinematic() )
    {
        pCurrChar->setCinematic(1);

        if(ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(pCurrChar->getRace()))
            pCurrChar->SendCinematicStart(rEntry->CinematicSequence);
    }

    if (!pCurrChar->GetMap()->Add(pCurrChar))
    {
        // normal delayed teleport protection not applied (and this correct) for this case (Player object just created)
        AreaTrigger const* at = sObjectMgr.GetGoBackTrigger(pCurrChar->GetMapId());
        if(at)
            pCurrChar->TeleportTo(at->target_mapId, at->target_X, at->target_Y, at->target_Z, pCurrChar->GetOrientation());
        else
            pCurrChar->TeleportToHomebind();
    }

    sObjectAccessor.AddObject(pCurrChar);
    //DEBUG_LOG("Player %s added to Map.",pCurrChar->GetName());
    pCurrChar->GetSocial()->SendFriendList();
    pCurrChar->GetSocial()->SendIgnoreList();

    pCurrChar->SendInitialPacketsAfterAddToMap();

    CharacterDatabase.PExecute("UPDATE characters SET online = 1 WHERE guid = '%u'", pCurrChar->GetGUIDLow());
    LoginDatabase.PExecute("UPDATE account SET active_realm_id = %u WHERE id = '%u'", realmID, GetAccountId());
    pCurrChar->SetInGameTime( getMSTime() );

    // announce group about member online (must be after add to player list to receive announce to self)
    if (Group *group = pCurrChar->GetGroup())
        group->SendUpdate();

    // friend status
    sSocialMgr.SendFriendStatus(pCurrChar, FRIEND_ONLINE, pCurrChar->GetObjectGuid(), true);

    // Place character in world (and load zone) before some object loading
    pCurrChar->LoadCorpse();

    // setting Ghost+speed if dead
    if (pCurrChar->m_deathState != ALIVE)
    {
        // not blizz like, we must correctly save and load player instead...
        if(pCurrChar->getRace() == RACE_NIGHTELF)
            pCurrChar->CastSpell(pCurrChar, 20584, true);   // 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)
        pCurrChar->CastSpell(pCurrChar, 8326, true);        // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)

        pCurrChar->SetMovement(MOVE_WATER_WALK);
    }

    pCurrChar->ContinueTaxiFlight();

    // Load pet if any (if player not alive and in taxi flight or another then pet will remember as temporary unsummoned)
    pCurrChar->LoadPet();

    // Set FFA PvP for non GM in non-rest mode
    if(sWorld.IsFFAPvPRealm() && !pCurrChar->isGameMaster() && !pCurrChar->HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_RESTING) )
        pCurrChar->SetFFAPvP(true);

    if(pCurrChar->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP))
        pCurrChar->SetContestedPvP();

    // Apply at_login requests
    if(pCurrChar->HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
    {
        pCurrChar->resetSpells();
        SendNotification(LANG_RESET_SPELLS);
    }

    if(pCurrChar->HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
    {
        pCurrChar->resetTalents(true);
        SendNotification(LANG_RESET_TALENTS);               // we can use SMSG_TALENTS_INVOLUNTARILY_RESET here
    }

    // show time before shutdown if shutdown planned.
    if (sWorld.IsShutdowning())
        sWorld.ShutdownMsg(true,pCurrChar);

    if (sWorld.getConfig(CONFIG_BOOL_ALL_TAXI_PATHS))
        pCurrChar->SetTaxiCheater(true);

    if (pCurrChar->isGameMaster())
        SendNotification(LANG_GM_ON);

    if (!pCurrChar->isGMVisible())
        SendNotification(LANG_INVISIBLE_INVISIBLE);

    std::string IP_str = GetRemoteAddress();
    sLog.outChar("Account: %d (IP: %s) Login Character:[%s] (guid: %u)",
        GetAccountId(), IP_str.c_str(), pCurrChar->GetName(), pCurrChar->GetGUIDLow());

    if(!pCurrChar->IsStandState() && !pCurrChar->hasUnitState(UNIT_STAT_STUNNED))
        pCurrChar->SetStandState(UNIT_STAND_STATE_STAND);

    m_playerLoading = false;
    delete holder;
}
Example #11
0
bool ChatHandler::HandleUnFreezeCommand(char *args)
{
    std::string name;
    Player* player;
    char* TargetName = strtok((char*)args, " "); //get entered #name
    if (!TargetName) //if no #name entered use target
    {
        player = getSelectedPlayer();
        if (player) //prevent crash with creature as target
        {
            name = player->GetName();
        }
    }

    else // if #name entered
    {
        name = TargetName;
        normalizePlayerName(name);
        player = sObjectMgr.GetPlayer(name.c_str()); //get player by #name
    }

    //effect
    if (player)
    {
        PSendSysMessage(LANG_COMMAND_UNFREEZE, name.c_str());

        //Reset player faction + allow combat + allow duels
        player->setFactionForRace(player->getRace());
        player->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);

        //allow movement and spells
        uint32 spellID = 9454; // uint32 spellID1 = 23775;
        player->RemoveAurasDueToSpell(spellID);

        //save player
        player->SaveToDB();
    }

    if (!player)
    {
        if (TargetName)
        {
            //check for offline players
            QueryResult *result = CharacterDatabase.PQuery("SELECT characters.guid FROM `characters` WHERE characters.name = '%s'", name.c_str());
            if (!result)
            {
                SendSysMessage(LANG_COMMAND_FREEZE_WRONG);
                return true;
            }
            //if player found: delete his freeze aura
            Field *fields = result->Fetch();
            uint64 pguid = fields[0].GetUInt64();
            delete result;
            CharacterDatabase.PQuery("DELETE FROM `character_aura` WHERE character_aura.spell = 9454 AND character_aura.guid = '%u'", pguid);
            PSendSysMessage(LANG_COMMAND_UNFREEZE, name.c_str());
            return true;
        }
        else
        {
            SendSysMessage(LANG_COMMAND_FREEZE_WRONG);
            return true;
        }
    }

    return true;
}
void RandomPlayerbotMgr::PrintStats()
{
    sLog.outString("%d Random Bots online", playerBots.size());

    map<uint32, int> alliance, horde;
    for (uint32 i = 0; i < 10; ++i)
    {
        alliance[i] = 0;
        horde[i] = 0;
    }

    map<uint8, int> perRace, perClass;
    for (uint8 race = RACE_HUMAN; race < MAX_RACES; ++race)
    {
        perRace[race] = 0;
    }
    for (uint8 cls = CLASS_WARRIOR; cls < MAX_CLASSES; ++cls)
    {
        perClass[cls] = 0;
    }

    int dps = 0, heal = 0, tank = 0;
    for (PlayerBotMap::iterator i = playerBots.begin(); i != playerBots.end(); ++i)
    {
        Player* bot = i->second;
        if (IsAlliance(bot->getRace()))
            alliance[bot->getLevel() / 10]++;
        else
            horde[bot->getLevel() / 10]++;

        perRace[bot->getRace()]++;
        perClass[bot->getClass()]++;

        int spec = AiFactory::GetPlayerSpecTab(bot);
        switch (bot->getClass())
        {
        case CLASS_DRUID:
            if (spec == 2)
                heal++;
            else
                dps++;
            break;
        case CLASS_PALADIN:
            if (spec == 1)
                tank++;
            else if (spec == 0)
                heal++;
            else
                dps++;
            break;
        case CLASS_PRIEST:
            if (spec != 2)
                heal++;
            else
                dps++;
            break;
        case CLASS_SHAMAN:
            if (spec == 2)
                heal++;
            else
                dps++;
            break;
        case CLASS_WARRIOR:
            if (spec == 2)
                tank++;
            else
                dps++;
            break;
        default:
            dps++;
            break;
        }
    }

    sLog.outString("Per level:");
    uint32 maxLevel = sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL);
    for (uint32 i = 0; i < 10; ++i)
    {
        if (!alliance[i] && !horde[i])
            continue;

        uint32 from = i*10;
        uint32 to = min(from + 9, maxLevel);
        if (!from) from = 1;
        sLog.outString("    %d..%d: %d alliance, %d horde", from, to, alliance[i], horde[i]);
    }
    sLog.outString("Per race:");
    for (uint8 race = RACE_HUMAN; race < MAX_RACES; ++race)
    {
        if (perRace[race])
            sLog.outString("    %s: %d", ChatHelper::formatRace(race).c_str(), perRace[race]);
    }
    sLog.outString("Per class:");
    for (uint8 cls = CLASS_WARRIOR; cls < MAX_CLASSES; ++cls)
    {
        if (perClass[cls])
            sLog.outString("    %s: %d", ChatHelper::formatClass(cls).c_str(), perClass[cls]);
    }
    sLog.outString("Per role:");
    sLog.outString("    tank: %d", tank);
    sLog.outString("    heal: %d", heal);
    sLog.outString("    dps: %d", dps);
}
Example #13
0
void WorldSession::HandlePlayerLoginOpcode( WorldPacket & recv_data )
{
    CHECK_PACKET_SIZE(recv_data,8);

    m_playerLoading = true;
    uint64 playerGuid = 0;

    DEBUG_LOG( "WORLD: Recvd Player Logon Message" );

    recv_data >> playerGuid;

    Player* plr = new Player(this);

    // "GetAccountId()==db stored account id" checked in LoadFromDB (prevent login not own character using cheating tools)
    if(!plr->LoadFromDB(GUID_LOPART(playerGuid)))
    {
        KickPlayer();                                       // disconnect client, player no set to session and it will not deleted or saved at kick
        delete plr;                                         // delete it manually
        m_playerLoading = false;
        return;
    }
    //plr->_RemoveAllItemMods();

    //set a count of unread mails
    time_t cTime = time(NULL);
    QueryResult *resultMails = sDatabase.PQuery("SELECT COUNT(id) FROM `mail` WHERE `receiver` = '%u' AND `checked` = 0 AND `deliver_time` <= '" I64FMTD "'", GUID_LOPART(playerGuid),(uint64)cTime);
    if (resultMails)
    {
        Field *fieldMail = resultMails->Fetch();
        plr->unReadMails = fieldMail[0].GetUInt8();
        delete resultMails;
    }

    // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
    resultMails = sDatabase.PQuery("SELECT MIN(`deliver_time`) FROM `mail` WHERE `receiver` = '%u' AND `checked` = 0", GUID_LOPART(playerGuid));
    if (resultMails)
    {
        Field *fieldMail = resultMails->Fetch();
        plr->m_nextMailDelivereTime = (time_t)fieldMail[0].GetUInt64();
        delete resultMails;
    }

    SetPlayer(plr);

    Player *pCurrChar = GetPlayer();

    pCurrChar->SendDungeonDifficulty();

    WorldPacket data( SMSG_LOGIN_VERIFY_WORLD, 20 );
    data << plr->GetMapId();
    data << plr->GetPositionX();
    data << plr->GetPositionY();
    data << plr->GetPositionZ();
    data << plr->GetOrientation();
    SendPacket(&data);

    data.Initialize( SMSG_ACCOUNT_DATA_MD5, 128 );
    for(int i = 0; i < 32; i++)
        data << uint32(0);
    SendPacket(&data);

    pCurrChar->LoadIgnoreList();
    pCurrChar->SendFriendlist();
    pCurrChar->SendIgnorelist();

    // Send MOTD
    {
        data.Initialize(SMSG_MOTD, 50);                     // new in 2.0.1
        data << (uint32)0;

        uint32 linecount=0;
        string str_motd = sWorld.GetMotd();
        string::size_type pos, nextpos;

        pos = 0;
        while ( (nextpos= str_motd.find('@',pos)) != string::npos )
        {
            if (nextpos != pos)
            {
                data << str_motd.substr(pos,nextpos-pos);
                linecount++;
            }
            pos = nextpos+1;
        }

        if (pos<str_motd.length())
        {
            data << str_motd.substr(pos);
            linecount++;
        }

        data.put(0, linecount);

        SendPacket( &data );
        DEBUG_LOG( "WORLD: Sent motd (SMSG_MOTD)" );
    }

    if(pCurrChar->GetGuildId() != 0)
    {
        Guild* guild = objmgr.GetGuildById(pCurrChar->GetGuildId());
        if(guild)
        {
            data.Initialize(SMSG_GUILD_EVENT, (2+guild->GetMOTD().size()+1));
            data << (uint8)GE_MOTD;
            data << (uint8)1;
            data << guild->GetMOTD();
            SendPacket(&data);
            DEBUG_LOG( "WORLD: Sent guild-motd (SMSG_GUILD_EVENT)" );

            data.Initialize(SMSG_GUILD_EVENT, (5+10));      // we guess size
            data<<(uint8)GE_SIGNED_ON;
            data<<(uint8)1;
            data<<pCurrChar->GetName();
            data<<pCurrChar->GetGUID();
            guild->BroadcastPacket(&data);
            DEBUG_LOG( "WORLD: Sent guild-signed-on (SMSG_GUILD_EVENT)" );
        }
        else
        {
            // remove wrong guild data
            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());
            pCurrChar->SetUInt32Value(PLAYER_GUILDID,0);
            pCurrChar->SetUInt32ValueInDB(PLAYER_GUILDID,0,pCurrChar->GetGUID());
        }
    }

    // rest_start

    // home bind stuff
    {
        QueryResult *result4 = sDatabase.PQuery("SELECT `map`,`zone`,`position_x`,`position_y`,`position_z` FROM `character_homebind` WHERE `guid` = '%u'", GUID_LOPART(playerGuid));
        if (result4)
        {
            Field *fields = result4->Fetch();
            _player->m_homebindMapId = fields[0].GetUInt32();
            _player->m_homebindZoneId = fields[1].GetUInt16();
            _player->m_homebindX = fields[2].GetFloat();
            _player->m_homebindY = fields[3].GetFloat();
            _player->m_homebindZ = fields[4].GetFloat();
            delete result4;
        }
        else
        {
            int plrace = GetPlayer()->getRace();
            int plclass = GetPlayer()->getClass();
            QueryResult *result5 = sDatabase.PQuery("SELECT `map`,`zone`,`position_x`,`position_y`,`position_z` FROM `playercreateinfo` WHERE `race` = '%u' AND `class` = '%u'", plrace, plclass);

            if(!result5)
            {
                sLog.outErrorDb("Table `playercreateinfo` not have data for race %u class %u , character can't be loaded.",plrace, plclass);
                LogoutPlayer(false);                        // without save
                return;
            }

            Field *fields = result5->Fetch();
            // store and send homebind for player
            _player->m_homebindMapId = fields[0].GetUInt32();
            _player->m_homebindZoneId = fields[1].GetUInt16();
            _player->m_homebindX = fields[2].GetFloat();
            _player->m_homebindY = fields[3].GetFloat();
            _player->m_homebindZ = fields[4].GetFloat();
            sDatabase.PExecute("INSERT INTO `character_homebind` (`guid`,`map`,`zone`,`position_x`,`position_y`,`position_z`) VALUES ('%u', '%u', '%u', '%f', '%f', '%f')", GUID_LOPART(playerGuid), _player->m_homebindMapId, (uint32)_player->m_homebindZoneId, _player->m_homebindX, _player->m_homebindY, _player->m_homebindZ);
            delete result5;
        }

        data.Initialize (SMSG_BINDPOINTUPDATE, 5*4);
        data << _player->m_homebindX << _player->m_homebindY << _player->m_homebindZ;
        data << (uint32) _player->m_homebindMapId;
        data << (uint32) _player->m_homebindZoneId;
        SendPacket (&data);

        DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f\n",
            _player->m_homebindMapId,_player->m_homebindZoneId,_player->m_homebindX,_player->m_homebindY, _player->m_homebindZ);
    }

    data.Initialize( SMSG_TUTORIAL_FLAGS, 8*32 );
    for (int i = 0; i < 8; i++)
        data << uint32( GetPlayer()->GetTutorialInt(i) );
    SendPacket(&data);
    //sLog.outDebug( "WORLD: Sent tutorial flags." );

    pCurrChar->_LoadSpellCooldowns();
    GetPlayer()->SendInitialSpells();
    GetPlayer()->SendInitialActionButtons();
    GetPlayer()->SendInitialReputations();

    /*if(GetPlayer()->getClass() == CLASS_HUNTER || GetPlayer()->getClass() == CLASS_ROGUE)
    {
        uint32 shiftdata=0x01;
        for(uint8 i=0;i<32;i++)
        {
            if ( 522753 & shiftdata )
            {
                data.Initialize(SMSG_SET_FLAT_SPELL_MODIFIER);
                data << uint8(i);
                data << uint8(5);
                data << uint16(1);
                data << uint16(0);
                SendPacket(&data);
            }
            shiftdata=shiftdata<<1;
        }
    }*/

    //Show cinematic at the first time that player login
    if( !GetPlayer()->getCinematic() )
    {
        GetPlayer()->setCinematic(1);

        ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(GetPlayer()->getRace());
        if(rEntry)
        {
            data.Initialize( SMSG_TRIGGER_CINEMATIC,4 );
            data << uint32(rEntry->startmovie);
            SendPacket( &data );
        }
    }

    pCurrChar->SendInitWorldStates();

    pCurrChar->CastSpell(pCurrChar, 836, true);             // LOGINEFFECT

    data.Initialize(SMSG_LOGIN_SETTIMESPEED, 8);
    time_t gameTime = sWorld.GetGameTime();
    struct tm *lt = localtime(&gameTime);
    uint32 xmitTime = (lt->tm_year - 100) << 24 | lt->tm_mon  << 20 |
        (lt->tm_mday - 1) << 14 | lt->tm_wday << 11 |
        lt->tm_hour << 6 | lt->tm_min;
    data << xmitTime;
    data << (float)0.017f;                                  // game speed
    SendPacket( &data );

    GetPlayer()->UpdateHonorFields();

    QueryResult *result = sDatabase.PQuery("SELECT `guildid`,`rank` FROM `guild_member` WHERE `guid` = '%u'",pCurrChar->GetGUIDLow());

    if(result)
    {
        Field *fields = result->Fetch();
        pCurrChar->SetInGuild(fields[0].GetUInt32());
        pCurrChar->SetRank(fields[1].GetUInt32());
        delete result;
    }
    else if(pCurrChar->GetGuildId())                        // clear guild related fields in case wrong data about non existed membership
    {
        pCurrChar->SetInGuild(0);
        pCurrChar->SetRank(0);
    }

    if (!MapManager::Instance().GetMap(pCurrChar->GetMapId(), pCurrChar)->AddInstanced(pCurrChar))
    {
        // TODO : Teleport to zone-in area
    }

    MapManager::Instance().GetMap(pCurrChar->GetMapId(), pCurrChar)->Add(pCurrChar);
    ObjectAccessor::Instance().InsertPlayer(pCurrChar);
    //sLog.outDebug("Player %s added to Map.",pCurrChar->GetName());

    if (pCurrChar->m_transport)
    {
        Transport* curTrans = pCurrChar->m_transport;
        pCurrChar->TeleportTo(curTrans->GetMapId(), curTrans->GetPositionX(), curTrans->GetPositionY(), curTrans->GetPositionZ(), curTrans->GetOrientation(), true, false);
    }

    sDatabase.PExecute("UPDATE `character` SET `online` = 1 WHERE `guid` = '%u'", pCurrChar->GetGUIDLow());
    loginDatabase.PExecute("UPDATE `account` SET `online` = 1 WHERE `id` = '%u'", GetAccountId());
    plr->SetInGameTime( getMSTime() );

    // set some aura effects after add player to map
    if(pCurrChar->HasAuraType(SPELL_AURA_MOD_STUN))
        pCurrChar->SetMovement(MOVE_ROOT);

    if(pCurrChar->HasAuraType(SPELL_AURA_MOD_ROOT))
    {
        WorldPacket data(SMSG_FORCE_MOVE_ROOT, 10);
        data.append(pCurrChar->GetPackGUID());
        data << (uint32)2;
        pCurrChar->SendMessageToSet(&data,true);
    }

    // announce group about member online (must be after add to player list to receive announce to self)
    if(pCurrChar->groupInfo.group)
    {
        //pCurrChar->groupInfo.group->SendInit(this); // useless
        pCurrChar->groupInfo.group->SendUpdate();
    }

    // friend status
    data.Initialize(SMSG_FRIEND_STATUS, 19);
    data<<uint8(FRIEND_ONLINE);
    data<<pCurrChar->GetGUID();
    data<<uint8(1);
    data<<pCurrChar->GetAreaId();
    data<<pCurrChar->getLevel();
    data<<pCurrChar->getClass();
    pCurrChar->BroadcastPacketToFriendListers(&data);

    pCurrChar->SendEnchantmentDurations();                  // must be after add to map

    // Place character in world (and load zone) before some object loading
    pCurrChar->LoadCorpse();

    // setting Ghost+speed if dead
    //if ( pCurrChar->m_deathState == DEAD )
    if ( pCurrChar->m_deathState != ALIVE )
    {
        // not blizz like, we must correctly save and load player instead...
        if(pCurrChar->getRace() == RACE_NIGHTELF)
            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)
        pCurrChar->CastSpell(pCurrChar, 8326, true, 0);     // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)

        //pCurrChar->SetUInt32Value(UNIT_FIELD_AURA+41, 8326);
        //pCurrChar->SetUInt32Value(UNIT_FIELD_AURA+42, 20584);
        //pCurrChar->SetUInt32Value(UNIT_FIELD_AURAFLAGS+6, 238);
        //pCurrChar->SetUInt32Value(UNIT_FIELD_AURALEVELS+11, 514);
        //pCurrChar->SetUInt32Value(UNIT_FIELD_AURAAPPLICATIONS+11, 65535);
        //pCurrChar->SetUInt32Value(UNIT_FIELD_DISPLAYID, 1825);
        //if (pCurrChar->getRace() == RACE_NIGHTELF)
        //{
        //    pCurrChar->SetSpeed(MOVE_RUN,  1.5f*1.2f, true);
        //    pCurrChar->SetSpeed(MOVE_SWIM, 1.5f*1.2f, true);
        //}
        //else
        //{
        //    pCurrChar->SetSpeed(MOVE_RUN,  1.5f, true);
        //    pCurrChar->SetSpeed(MOVE_SWIM, 1.5f, true);
        //}
        pCurrChar->SetMovement(MOVE_WATER_WALK);
    }

    // Load pet if any and player is alive
    if(pCurrChar->isAlive())
        pCurrChar->LoadPet();

    // show time before shutdown if shutdown planned.
    if(sWorld.IsShutdowning())
        sWorld.ShutdownMsg(true,pCurrChar);

    if(pCurrChar->isGameMaster())
        SendNotification("GM mode is ON");
    m_playerLoading = false;
    pCurrChar->SendAllowMove();

    data.Initialize(SMSG_UNKNOWN_811, 4);
    data << uint32(0);
    SendPacket(&data);
}
Example #14
0
void WorldSession::SendLfgUpdateList(uint32 dungeonID)
{
    if (!sWorld.getConfig(CONFIG_BOOL_LFR_ENABLE))
    {
        DEBUG_LOG("SendLfgUpdateList %u failed - Raid finder disabled", GetPlayer()->GetObjectGuid().GetCounter());
        return;
    }

    DEBUG_LOG("SMSG_LFG_SEARCH_RESULTS %u dungeonentry: %u ", GetPlayer()->GetObjectGuid().GetCounter(), dungeonID);

    LFGDungeonEntry const* dungeon = sLFGMgr.GetDungeon(dungeonID);

    if (!dungeon)
        return;

    Team team = sWorld.getConfig(CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_GROUP) ? TEAM_NONE : GetPlayer()->GetTeam();

    GuidSet groups = sLFGMgr.GetDungeonGroupQueue(dungeon, team);
    GuidSet players = sLFGMgr.GetDungeonPlayerQueue(dungeon, team);

    uint32 groupCount = groups.size();
    uint32 groupSize = 4+4;

    for (GuidSet::const_iterator itr = groups.begin(); itr != groups.end(); ++itr)
    {
        Group* pGroup   = sObjectMgr.GetGroup(*itr);
        if (!pGroup)
            continue;

        Player* pLeader = sObjectMgr.GetPlayer(pGroup->GetLeaderGuid());
        if (!pLeader)
            continue;

        sLFGMgr.GetLFGPlayerState(pLeader->GetObjectGuid())->AddFlags(LFG_MEMBER_FLAG_CHARINFO |
                                        LFG_MEMBER_FLAG_COMMENT |
                                        LFG_MEMBER_FLAG_GROUPLEADER |
                                        LFG_MEMBER_FLAG_GROUPGUID |
                                        LFG_MEMBER_FLAG_ROLES |
                                        LFG_MEMBER_FLAG_AREA  |
                                        LFG_MEMBER_FLAG_STATUS  |
                                        LFG_MEMBER_FLAG_BIND);

        uint32 flags = sLFGMgr.GetLFGPlayerState(pLeader->GetObjectGuid())->GetFlags();

        if (flags & LFG_MEMBER_FLAG_COMMENT)
            groupSize += sLFGMgr.GetLFGPlayerState(pLeader->GetObjectGuid())->GetComment().size()+1;
        if (flags & LFG_MEMBER_FLAG_ROLES)
            groupSize +=3;
        if (flags & LFG_MEMBER_FLAG_BIND)
            groupSize += (8+4);

        players.insert(*itr);

        for (GroupReference *itr2 = pGroup->GetFirstMember(); itr2 != NULL; itr2 = itr2->next())
        {
            Player* player = itr2->getSource();

            if (!player || player == pLeader)
                continue;

            sLFGMgr.GetLFGPlayerState(player->GetObjectGuid())->AddFlags(LFG_MEMBER_FLAG_GROUPLEADER |
                                        LFG_MEMBER_FLAG_GROUPGUID |
                                        LFG_MEMBER_FLAG_STATUS);

            sLFGMgr.GetLFGPlayerState(player->GetObjectGuid())->RemoveFlags(LFG_MEMBER_FLAG_CHARINFO |
                                        LFG_MEMBER_FLAG_COMMENT |
                                        LFG_MEMBER_FLAG_ROLES |
                                        LFG_MEMBER_FLAG_AREA  |
                                        LFG_MEMBER_FLAG_BIND);
            players.insert(player->GetObjectGuid());
        }

    }

    uint32 playerCount = players.size();
    uint32 playerSize = 4+4;

    uint32 guidsSize = 0;
    GuidSet playersUpdated;
    playersUpdated.clear();

    for(GuidSet::const_iterator itr = players.begin(); itr != players.end(); ++itr)
    {
        Player* player   = sObjectMgr.GetPlayer(*itr);

        if (!player || !player->IsInWorld())
            continue;

        uint32 flags = sLFGMgr.GetLFGPlayerState(player->GetObjectGuid())->GetFlags();

        playerSize += (8+4);

        if (flags &  LFG_MEMBER_FLAG_CHARINFO)
            playerSize += (1+1+1+3+4+4+4+4+4+4+4+4+4+4+4+4+4+4+4+4+4+4+4+4);

        if (flags & LFG_MEMBER_FLAG_COMMENT)
            playerSize += sLFGMgr.GetLFGPlayerState(player->GetObjectGuid())->GetComment().size()+1;         // comment

        if (flags & LFG_MEMBER_FLAG_GROUPLEADER)
            playerSize += 1;

        if (flags & LFG_MEMBER_FLAG_GROUPGUID)
            playerSize += 8;

        if (flags & LFG_MEMBER_FLAG_ROLES)
            playerSize += 1;

        if (flags & LFG_MEMBER_FLAG_AREA)
            playerSize += 4;

        if (flags & LFG_MEMBER_FLAG_STATUS)
            playerSize += 1;

        if (flags & LFG_MEMBER_FLAG_BIND)
            playerSize += (8+4);

        if (flags & LFG_MEMBER_FLAG_UPDATE)
        {
            sLFGMgr.GetLFGPlayerState(player->GetObjectGuid())->RemoveFlags(LFG_MEMBER_FLAG_UPDATE);
            playersUpdated.insert(player->GetObjectGuid());
            guidsSize += 8;
        }

    }

    WorldPacket data(SMSG_LFG_SEARCH_RESULTS, 4 + 4 + 1 + groupSize + playerSize + guidsSize);

    data << uint32(dungeon->type);                           // type
    data << uint32(dungeon->Entry());                        // entry from LFGDungeons.dbc

    if (!playersUpdated.empty())
    {
        data << uint8(playersUpdated.size());
        for (GuidSet::const_iterator itr = playersUpdated.begin(); itr != playersUpdated.end(); ++itr)
        {
            data << *itr;                                 // player guid
        }
    }
    else
        data << uint8(0);


    if (!groups.empty())
    {
        data << uint32(groupCount);                          // groups count
        data << uint32(groupCount);                          // groups count2

        for (GuidSet::const_iterator itr = groups.begin(); itr != groups.end(); ++itr)
        {
            Group* group   = sObjectMgr.GetGroup(*itr);
            if (!group)
                continue;

            Player* leader = sObjectMgr.GetPlayer(group->GetLeaderGuid());

            uint32 flags = sLFGMgr.GetLFGPlayerState(leader->GetObjectGuid())->GetFlags();

            data << group->GetObjectGuid();

            data << flags;

            if (flags & LFG_MEMBER_FLAG_COMMENT)
            {
                data << sLFGMgr.GetLFGPlayerState(leader->GetObjectGuid())->GetComment().c_str();
            }

            if (flags & LFG_MEMBER_FLAG_ROLES)
            {
                for (int i = 0; i < 3; ++i)
                {
                // need implement function for roles count calculation. or not need?
                    data << uint8(0);
                }
            }

            if (flags & LFG_MEMBER_FLAG_BIND)
            {
                ObjectGuid instanceGuid;
                uint32 encounters = 0;
                if (InstancePlayerBind* bind = leader->GetBoundInstance(dungeon->map, Difficulty(dungeon->difficulty)))
                {
                    if (DungeonPersistentState* state = bind->state)
                    {
                        instanceGuid = state->GetInstanceGuid();
                        encounters = state->GetCompletedEncountersMask();
                    }
                }
                data << instanceGuid;
                data << encounters;
            }
        }
    }
    else
    {
        data << uint32(0);
        data << uint32(0);                                       // groups count2
    }


    if (!players.empty())
    {
        data << uint32(playerCount);                           // players count
        data << uint32(playerCount);                           // players count 2

        for(GuidSet::const_iterator itr = players.begin(); itr != players.end(); ++itr)
        {
            Player* player   = sObjectMgr.GetPlayer(*itr);

            if (!player || !player->IsInWorld())
                continue;

            uint32 flags = sLFGMgr.GetLFGPlayerState(player->GetObjectGuid())->GetFlags();

            data << *itr;                                         // guid

            data << flags;                                        // flags

            if (flags &  LFG_MEMBER_FLAG_CHARINFO)                // charinfo
            {
                data << uint8(player->getLevel());
                data << uint8(player->getClass());
                data << uint8(player->getRace());

                for(int i = 0; i < 3; ++i)
                    data << uint8(player->GetTalentsCount(i));                                      // spent talents count in specific tab

                data << uint32(player->GetArmor());                                                 // armor
                data << uint32(player->SpellBaseDamageBonusDone(SPELL_SCHOOL_MASK_SPELL));          // spd
                data << uint32(player->SpellBaseHealingBonusDone(SPELL_SCHOOL_MASK_SPELL));         // heal
                data << uint32(player->GetRatingBonusValue(CR_CRIT_MELEE));                         // crit rating melee
                data << uint32(player->GetRatingBonusValue(CR_CRIT_RANGED));                        // crit rating ranged
                data << uint32(player->GetRatingBonusValue(CR_CRIT_SPELL));                         // crit rating spell
                data << float(player->GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER)*5);                             // mp5
                data << float(player->GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER)*5);                 // unk
                data << uint32(player->GetTotalAttackPowerValue(BASE_ATTACK));                      // attack power
                data << uint32(player->GetTotalStatValue(STAT_AGILITY));                            // agility
                data << uint32(player->GetMaxHealth());                                             // health
                data << uint32(player->GetMaxPower(player->GetPowerType()));                        // power
                data << uint32(player->GetFreeTalentPoints());                                      // free talent points (TOM_RUS)
                data << float(0);                                                                   // unk
                data << uint32(player->GetRatingBonusValue(CR_DEFENSE_SKILL));                      // defence rating
                data << uint32(player->GetRatingBonusValue(CR_DODGE));                              // dodge rating
                data << uint32(player->GetRatingBonusValue(CR_BLOCK));                              // block rating
                data << uint32(player->GetRatingBonusValue(CR_PARRY));                              // parry rating
                data << uint32(player->GetRatingBonusValue(CR_HASTE_MELEE));                        // crit rating
                data << uint32(player->GetRatingBonusValue(CR_EXPERTISE));                          // expertize
            }

            if (flags & LFG_MEMBER_FLAG_COMMENT)
                data << sLFGMgr.GetLFGPlayerState(player->GetObjectGuid())->GetComment().c_str();         // comment

            if (flags & LFG_MEMBER_FLAG_GROUPLEADER)                         // Group leader flag
            {
                bool isLeader = false;
                if (Group* group = player->GetGroup())
                    if (player->GetObjectGuid() == group->GetLeaderGuid())
                        isLeader = true;

                data << uint8(isLeader);
            }

            if (flags & LFG_MEMBER_FLAG_GROUPGUID)                          // Group guid
            {
                ObjectGuid groupGuid = ObjectGuid();
                if (Group* group = player->GetGroup())
                    groupGuid = group->GetObjectGuid();

                data << groupGuid;
            }

            if (flags & LFG_MEMBER_FLAG_ROLES)                              // rolesMask
                data << uint8(sLFGMgr.GetLFGPlayerState(player->GetObjectGuid())->GetRoles());

            if (flags & LFG_MEMBER_FLAG_AREA)                               // Area
                data << uint32(player->GetAreaId());

            if (flags & LFG_MEMBER_FLAG_STATUS)                             // status
                data << uint8(0);

            if (flags & LFG_MEMBER_FLAG_BIND)
            {
                ObjectGuid instanceGuid;
                uint32 encounters = 0;
                if (InstancePlayerBind* bind = player->GetBoundInstance(dungeon->map, Difficulty(dungeon->difficulty)))
                {
                    if (DungeonPersistentState* state = bind->state)
                    {
                        instanceGuid = state->GetInstanceGuid();
                        encounters = state->GetCompletedEncountersMask();
                    }
                }
                data << instanceGuid;
                data << encounters;
            }

        }
    }
    else
    {
        data << uint32(0);                                          // players count
        data << uint32(0);                                          // unk
    }
    SendPacket(&data);
}
Example #15
0
//show info of player
bool ChatHandler::HandlePInfoCommand(const char* args)
{
    Player* target;
    uint64 target_guid;
    std::string target_name;

    uint32 parseGUID = MAKE_NEW_GUID(atol((char*)args), 0, HIGHGUID_PLAYER);

    if (sObjectMgr->GetPlayerNameByGUID(parseGUID, target_name))
    {
        target = sObjectMgr->GetPlayerByLowGUID(parseGUID);
        target_guid = parseGUID;
    }
    else if (!extractPlayerTarget((char*)args, &target, &target_guid, &target_name))
        return false;

    uint32 accId             = 0;
    uint32 money             = 0;
    uint32 total_player_time = 0;
    uint8 level              = 0;
    uint32 latency           = 0;
    uint8 race;
    uint8 Class;
    int64 muteTime           = 0;
    int64 banTime            = -1;
    uint32 mapId;
    uint32 areaId;
    uint32 phase             = 0;

    // get additional information from Player object
    if (target)
    {
        // check online security
        if (HasLowerSecurity(target, 0))
            return false;

        accId             = target->GetSession()->GetAccountId();
        money             = target->GetMoney();
        total_player_time = target->GetTotalPlayedTime();
        level             = target->getLevel();
        latency           = target->GetSession()->GetLatency();
        race              = target->getRace();
        Class             = target->getClass();
        muteTime          = target->GetSession()->m_muteTime;
        mapId             = target->GetMapId();
        areaId            = target->GetAreaId();
        phase             = target->GetPhaseMask();
    }
    // get additional information from DB
    else
    {
        // check offline security
        if (HasLowerSecurity(NULL, target_guid))
            return false;

        PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_PINFO);
        stmt->setUInt32(0, GUID_LOPART(target_guid));
        PreparedQueryResult result = CharacterDatabase.Query(stmt);

        if (!result)
            return false;

        Field* fields     = result->Fetch();
        total_player_time = fields[0].GetUInt32();
        level             = fields[1].GetUInt8();
        money             = fields[2].GetUInt32();
        accId             = fields[3].GetUInt32();
        race              = fields[4].GetUInt8();
        Class             = fields[5].GetUInt8();
        mapId             = fields[6].GetUInt16();
        areaId            = fields[7].GetUInt16();
    }

    std::string username   = GetTrinityString(LANG_ERROR);
    std::string email      = GetTrinityString(LANG_ERROR);
    std::string last_ip    = GetTrinityString(LANG_ERROR);
    uint32 security        = 0;
    std::string last_login = GetTrinityString(LANG_ERROR);

    PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_PINFO);
    stmt->setInt32(0, int32(realmID));
    stmt->setUInt32(1, accId);
    PreparedQueryResult result = LoginDatabase.Query(stmt);

    if (result)
    {
        Field* fields = result->Fetch();
        username      = fields[0].GetString();
        security      = fields[1].GetUInt8();
        email         = fields[2].GetString();
        muteTime      = fields[5].GetUInt64();

        if (email.empty())
            email = "-";

        if (!m_session || m_session->GetSecurity() >= AccountTypes(security))
        {
            last_ip = fields[3].GetString();
            last_login = fields[4].GetString();

            uint32 ip = inet_addr(last_ip.c_str());
#if TRINITY_ENDIAN == BIGENDIAN
            EndianConvertReverse(ip);
#endif

            PreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_IP2NATION_COUNTRY);

            stmt->setUInt32(0, ip);

            PreparedQueryResult result2 = WorldDatabase.Query(stmt);

            if (result2)
            {
                Field* fields2 = result2->Fetch();
                last_ip.append(" (");
                last_ip.append(fields2[0].GetString());
                last_ip.append(")");
            }
        }
        else
        {
            last_ip = "-";
            last_login = "******";
        }
    }

    std::string nameLink = playerLink(target_name);

    PSendSysMessage(LANG_PINFO_ACCOUNT, (target?"":GetTrinityString(LANG_OFFLINE)), nameLink.c_str(), GUID_LOPART(target_guid), username.c_str(), accId, email.c_str(), security, last_ip.c_str(), last_login.c_str(), latency);

    std::string bannedby = "unknown";
    std::string banreason = "";

    stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_PINFO_BANS);
    stmt->setUInt32(0, accId);
    PreparedQueryResult result2 = LoginDatabase.Query(stmt);
    if (!result2)
    {
        stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_PINFO_BANS);
        stmt->setUInt32(0, GUID_LOPART(target_guid));
        result2 = CharacterDatabase.Query(stmt);
    }

    if (result2)
    {
        Field* fields = result2->Fetch();
        banTime       = int64(fields[1].GetBool() ? 0 : fields[0].GetUInt32());
        bannedby      = fields[2].GetString();
        banreason     = fields[3].GetString();
    }

    if (muteTime > 0)
        PSendSysMessage(LANG_PINFO_MUTE, secsToTimeString(muteTime - time(NULL), true).c_str());

    if (banTime >= 0)
        PSendSysMessage(LANG_PINFO_BAN, banTime > 0 ? secsToTimeString(banTime - time(NULL), true).c_str() : "permanently", bannedby.c_str(), banreason.c_str());

    std::string race_s, Class_s;
    switch (race)
    {
        case RACE_HUMAN:            race_s = "Human";       break;
        case RACE_ORC:              race_s = "Orc";         break;
        case RACE_DWARF:            race_s = "Dwarf";       break;
        case RACE_NIGHTELF:         race_s = "Night Elf";   break;
        case RACE_UNDEAD_PLAYER:    race_s = "Undead";      break;
        case RACE_TAUREN:           race_s = "Tauren";      break;
        case RACE_GNOME:            race_s = "Gnome";       break;
        case RACE_TROLL:            race_s = "Troll";       break;
        case RACE_BLOODELF:         race_s = "Blood Elf";   break;
        case RACE_DRAENEI:          race_s = "Draenei";     break;
    }
    switch (Class)
    {
        case CLASS_WARRIOR:         Class_s = "Warrior";        break;
        case CLASS_PALADIN:         Class_s = "Paladin";        break;
        case CLASS_HUNTER:          Class_s = "Hunter";         break;
        case CLASS_ROGUE:           Class_s = "Rogue";          break;
        case CLASS_PRIEST:          Class_s = "Priest";         break;
        case CLASS_DEATH_KNIGHT:    Class_s = "Death Knight";   break;
        case CLASS_SHAMAN:          Class_s = "Shaman";         break;
        case CLASS_MAGE:            Class_s = "Mage";           break;
        case CLASS_WARLOCK:         Class_s = "Warlock";        break;
        case CLASS_DRUID:           Class_s = "Druid";          break;
    }

    std::string timeStr = secsToTimeString(total_player_time, true, true);
    uint32 gold = money /GOLD;
    uint32 silv = (money % GOLD) / SILVER;
    uint32 copp = (money % GOLD) % SILVER;
    PSendSysMessage(LANG_PINFO_LEVEL, race_s.c_str(), Class_s.c_str(), timeStr.c_str(), level, gold, silv, copp);

    // Add map, zone, subzone and phase to output
    int locale = GetSessionDbcLocale();
    std::string areaName = "<unknown>";
    std::string zoneName = "";

    MapEntry const* map = sMapStore.LookupEntry(mapId);

    AreaTableEntry const* area = GetAreaEntryByAreaID(areaId);
    if (area)
    {
        areaName = area->area_name[locale];

        AreaTableEntry const* zone = GetAreaEntryByAreaID(area->zone);

        if (zone)
            zoneName = zone->area_name[locale];
    }

    if (target)
    {
        if (!zoneName.empty())
            PSendSysMessage(LANG_PINFO_MAP_ONLINE, map->name[locale], zoneName.c_str(), areaName.c_str(), phase);
        else
            PSendSysMessage(LANG_PINFO_MAP_ONLINE, map->name[locale], areaName.c_str(), "<unknown>", phase);
    }
    else
        PSendSysMessage(LANG_PINFO_MAP_OFFLINE, map->name[locale], areaName.c_str());

    return true;
}
Example #16
0
void WorldSession::HandlePlayerLogin(LoginQueryHolder *holder)
{
    uint64 playerGuid = holder->GetGuid();

    Player *pCurrChar = new Player(this);
    pCurrChar->GetMotionMaster()->Initialize();

    // "GetAccountId()==db stored account id" checked in LoadFromDB (prevent login not own character using cheating tools)
    if(!pCurrChar->LoadFromDB(GUID_LOPART(playerGuid), holder))
    {
        KickPlayer();                                       // disconnect client, player no set to session and it will not deleted or saved at kick
        delete pCurrChar;                                   // delete it manually
        delete holder;                                      // delete all unprocessed queries
        m_playerLoading = false;
        return;
    }

    SetPlayer(pCurrChar);

    pCurrChar->SendDungeonDifficulty(false);

    WorldPacket data( SMSG_LOGIN_VERIFY_WORLD, 20 );
    data << pCurrChar->GetMapId();
    data << pCurrChar->GetPositionX();
    data << pCurrChar->GetPositionY();
    data << pCurrChar->GetPositionZ();
    data << pCurrChar->GetOrientation();
    SendPacket(&data);

    // load player specific part before send times
    LoadAccountData(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACCOUNTDATA),PER_CHARACTER_CACHE_MASK);
    SendAccountDataTimes(PER_CHARACTER_CACHE_MASK);

    data.Initialize(SMSG_FEATURE_SYSTEM_STATUS, 2);         // added in 2.2.0
    data << uint8(2);                                       // unknown value
    data << uint8(0);                                       // enable(1)/disable(0) voice chat interface in client
    SendPacket(&data);

    // Send MOTD
    {
        data.Initialize(SMSG_MOTD, 50);                     // new in 2.0.1
        data << (uint32)0;

        uint32 linecount=0;
        std::string str_motd = sWorld.GetMotd();
        std::string::size_type pos, nextpos;

        pos = 0;
        while ( (nextpos= str_motd.find('@',pos)) != std::string::npos )
        {
            if (nextpos != pos)
            {
                data << str_motd.substr(pos, nextpos-pos);
                ++linecount;
            }
            pos = nextpos + 1;
        }

        if (pos < str_motd.length())
        {
            data << str_motd.substr(pos);
            ++linecount;
        }

        data.put(0, linecount);

        SendPacket( &data );
        DEBUG_LOG( "WORLD: Sent motd (SMSG_MOTD)" );
    }

    //QueryResult *result = CharacterDatabase.PQuery("SELECT guildid,rank FROM guild_member WHERE guid = '%u'",pCurrChar->GetGUIDLow());
    QueryResult *resultGuild = holder->GetResult(PLAYER_LOGIN_QUERY_LOADGUILD);

    if(resultGuild)
    {
        Field *fields = resultGuild->Fetch();
        pCurrChar->SetInGuild(fields[0].GetUInt32());
        pCurrChar->SetRank(fields[1].GetUInt32());
        delete resultGuild;
    }
    else if(pCurrChar->GetGuildId())                        // clear guild related fields in case wrong data about non existed membership
    {
        pCurrChar->SetInGuild(0);
        pCurrChar->SetRank(0);
    }

    if(pCurrChar->GetGuildId() != 0)
    {
        Guild* guild = objmgr.GetGuildById(pCurrChar->GetGuildId());
        if(guild)
        {
            data.Initialize(SMSG_GUILD_EVENT, (2+guild->GetMOTD().size()+1));
            data << (uint8)GE_MOTD;
            data << (uint8)1;
            data << guild->GetMOTD();
            SendPacket(&data);
            DEBUG_LOG( "WORLD: Sent guild-motd (SMSG_GUILD_EVENT)" );

            data.Initialize(SMSG_GUILD_EVENT, (5+10));      // we guess size
            data<<(uint8)GE_SIGNED_ON;
            data<<(uint8)1;
            data<<pCurrChar->GetName();
            data<<pCurrChar->GetGUID();
            guild->BroadcastPacket(&data);
            DEBUG_LOG( "WORLD: Sent guild-signed-on (SMSG_GUILD_EVENT)" );

            // Increment online members of the guild
            guild->IncOnlineMemberCount();
        }
        else
        {
            // remove wrong guild data
            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());
            pCurrChar->SetInGuild(0);
        }
    }

    data.Initialize(SMSG_LEARNED_DANCE_MOVES, 4+4);
    data << uint32(0);
    data << uint32(0);
    SendPacket(&data);

    if(!pCurrChar->isAlive())
        pCurrChar->SendCorpseReclaimDelay(true);

    pCurrChar->SendInitialPacketsBeforeAddToMap();

    //Show cinematic at the first time that player login
    if( !pCurrChar->getCinematic() )
    {
        pCurrChar->setCinematic(1);

        if(ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(pCurrChar->getClass()))
        {
            if (cEntry->CinematicSequence)
                pCurrChar->SendCinematicStart(cEntry->CinematicSequence);
            else if (ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(pCurrChar->getRace()))
                pCurrChar->SendCinematicStart(rEntry->CinematicSequence);
        }
    }

    if (!pCurrChar->GetMap()->Add(pCurrChar))
    {
        AreaTrigger const* at = objmgr.GetGoBackTrigger(pCurrChar->GetMapId());
        if(at)
            pCurrChar->TeleportTo(at->target_mapId, at->target_X, at->target_Y, at->target_Z, pCurrChar->GetOrientation());
        else
            pCurrChar->TeleportTo(pCurrChar->m_homebindMapId, pCurrChar->m_homebindX, pCurrChar->m_homebindY, pCurrChar->m_homebindZ, pCurrChar->GetOrientation());
    }

    ObjectAccessor::Instance().AddObject(pCurrChar);
    //sLog.outDebug("Player %s added to Map.",pCurrChar->GetName());

    pCurrChar->SendInitialPacketsAfterAddToMap();

    CharacterDatabase.PExecute("UPDATE characters SET online = 1 WHERE guid = '%u'", pCurrChar->GetGUIDLow());
    loginDatabase.PExecute("UPDATE account SET active_realm_id = %d WHERE id = '%u'", realmID, GetAccountId());
    pCurrChar->SetInGameTime( getMSTime() );

    // announce group about member online (must be after add to player list to receive announce to self)
    if(Group *group = pCurrChar->GetGroup())
    {
        //pCurrChar->groupInfo.group->SendInit(this); // useless
        group->SendUpdate();
    }

    // friend status
    sSocialMgr.SendFriendStatus(pCurrChar, FRIEND_ONLINE, pCurrChar->GetGUIDLow(), true);

    // Place character in world (and load zone) before some object loading
    pCurrChar->LoadCorpse();

    // setting Ghost+speed if dead
    if (pCurrChar->m_deathState != ALIVE)
    {
        // not blizz like, we must correctly save and load player instead...
        if(pCurrChar->getRace() == RACE_NIGHTELF)
            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)
        pCurrChar->CastSpell(pCurrChar, 8326, true, 0);     // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)

        pCurrChar->SetMovement(MOVE_WATER_WALK);
    }

    pCurrChar->ContinueTaxiFlight();

    // reset for all pets before pet loading
    if(pCurrChar->HasAtLoginFlag(AT_LOGIN_RESET_PET_TALENTS))
        Pet::resetTalentsForAllPetsOf(pCurrChar);

    // Load pet if any (if player not alive and in taxi flight or another then pet will remember as temporary unsummoned)
    pCurrChar->LoadPet();

    // Set FFA PvP for non GM in non-rest mode
    if(sWorld.IsFFAPvPRealm() && !pCurrChar->isGameMaster() && !pCurrChar->HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_RESTING) )
        pCurrChar->SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);

    if(pCurrChar->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP))
        pCurrChar->SetContestedPvP();

    // Apply at_login requests
    if(pCurrChar->HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
    {
        pCurrChar->resetSpells();
        SendNotification(LANG_RESET_SPELLS);
    }

    if(pCurrChar->HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
    {
        pCurrChar->resetTalents(true);
        pCurrChar->SendTalentsInfoData(false);              // original talents send already in to SendInitialPacketsBeforeAddToMap, resend reset state
        SendNotification(LANG_RESET_TALENTS);
    }

    // show time before shutdown if shutdown planned.
    if(sWorld.IsShutdowning())
        sWorld.ShutdownMsg(true,pCurrChar);

    if(sWorld.getConfig(CONFIG_ALL_TAXI_PATHS))
        pCurrChar->SetTaxiCheater(true);

    if(pCurrChar->isGameMaster())
        SendNotification(LANG_GM_ON);

    std::string IP_str = GetRemoteAddress();
    sLog.outChar("Account: %d (IP: %s) Login Character:[%s] (guid:%u)",
                 GetAccountId(), IP_str.c_str(), pCurrChar->GetName(), pCurrChar->GetGUIDLow());

    if(!pCurrChar->IsStandState() && !pCurrChar->hasUnitState(UNIT_STAT_STUNNED))
        pCurrChar->SetStandState(UNIT_STAND_STATE_STAND);

    m_playerLoading = false;
    delete holder;
}
Example #17
0
void WorldSession::HandlePlayerLoginOpcode( WorldPacket & recv_data )
{
    m_playerLoading = true;
    uint64 playerGuid = 0;

    DEBUG_LOG( "WORLD: Recvd Player Logon Message" );

    recv_data >> playerGuid;

    Player* plr = new Player(this);
    ASSERT(plr);

    plr->SetSession(this);
    // "GetAccountId()==db stored account id" checked in LoadFromDB (prevent login not own character using cheating tools)
    if(!plr->LoadFromDB(GUID_LOPART(playerGuid)))
    {
        m_playerLoading = false;
        return;
    }
    //plr->_RemoveAllItemMods();

    //set a count of unread mails:
    QueryResult *resultMails = sDatabase.PQuery("SELECT COUNT(id) FROM `mail` WHERE `receiver` = '%u' AND `checked` = 0", GUID_LOPART(playerGuid));
    if (resultMails)
    {
        Field *fieldMail = resultMails->Fetch();
        plr->unReadMails = fieldMail[0].GetUInt8();
        delete resultMails;
    }
    else
        plr->unReadMails = 0;

    SetPlayer(plr);

    WorldPacket data( SMSG_ACCOUNT_DATA_MD5, (80) );

    for(int i = 0; i < 80; i++)
        data << uint8(0);

    SendPacket(&data);

    Player *pCurrChar = GetPlayer();

    pCurrChar->LoadIgnoreList();
    pCurrChar->SendFriendlist();
    pCurrChar->SendIgnorelist();

    sChatHandler.FillSystemMessageData(&data, this, sWorld.GetMotd());
    SendPacket( &data );

    DEBUG_LOG( "WORLD: Sent motd (SMSG_MESSAGECHAT)" );

    if(pCurrChar->GetGuildId() != 0)
    {
        Guild* guild = objmgr.GetGuildById(pCurrChar->GetGuildId());
        if(guild)
        {
            data.Initialize(SMSG_GUILD_EVENT, (2+guild->GetMOTD().size()+1));
            data << (uint8)GE_MOTD;
            data << (uint8)1;
            data << guild->GetMOTD();
            SendPacket(&data);
            DEBUG_LOG( "WORLD: Sent guild-motd (SMSG_GUILD_EVENT)" );

            data.Initialize(SMSG_GUILD_EVENT, (5+10));      // we guess size
            data<<(uint8)GE_SIGNED_ON;
            data<<(uint8)1;
            data<<pCurrChar->GetName();
            data<<(uint8)0<<(uint8)0<<(uint8)0;
            guild->BroadcastPacket(&data);
            DEBUG_LOG( "WORLD: Sent guild-signed-on (SMSG_GUILD_EVENT)" );
        }
        else
        {
            // remove wrong guild data
            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());
            pCurrChar->SetUInt32Value(PLAYER_GUILDID,0);
            pCurrChar->SetUInt32ValueInDB(PLAYER_GUILDID,0,pCurrChar->GetGUID());
        }
    }

    // home bind stuff
    Field *fields;
    QueryResult *result7 = sDatabase.PQuery("SELECT COUNT(`guid`) FROM `character_homebind` WHERE `guid` = '%u'", GUID_LOPART(playerGuid));
    if (result7)
    {
        int cnt;
        fields = result7->Fetch();
        cnt = fields[0].GetUInt32();

        if ( cnt > 0 )
        {
            QueryResult *result4 = sDatabase.PQuery("SELECT `map`,`zone`,`position_x`,`position_y`,`position_z` FROM `character_homebind` WHERE `guid` = '%u'", GUID_LOPART(playerGuid));
            assert(result4);
            fields = result4->Fetch();
            data.Initialize (SMSG_BINDPOINTUPDATE, 5*4);
            data << fields[2].GetFloat() << fields[3].GetFloat() << fields[4].GetFloat();
            data << fields[0].GetUInt32();
            data << fields[1].GetUInt32();
            SendPacket (&data);
            DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f\n",fields[0].GetUInt32(),fields[1].GetUInt32(),fields[2].GetFloat(), fields[3].GetFloat(), fields[4].GetFloat());
            delete result4;
        }
        else
        {
            int plrace = GetPlayer()->getRace();
            int plclass = GetPlayer()->getClass();
            QueryResult *result5 = sDatabase.PQuery("SELECT `map`,`zone`,`position_x`,`position_y`,`position_z` FROM `playercreateinfo` WHERE `race` = '%u' AND `class` = '%u'", plrace, plclass);
            assert(result5);
            fields = result5->Fetch();
            // store and send homebind for player
            sDatabase.PExecute("INSERT INTO `character_homebind` (`guid`,`map`,`zone`,`position_x`,`position_y`,`position_z`) VALUES ('%u', '%u', '%u', '%f', '%f', '%f')", GUID_LOPART(playerGuid), fields[0].GetUInt32(), fields[1].GetUInt32(), fields[2].GetFloat(), fields[3].GetFloat(), fields[4].GetFloat());
            data.Initialize (SMSG_BINDPOINTUPDATE, 5*4);
            data << fields[2].GetFloat() << fields[3].GetFloat() << fields[4].GetFloat();
            data << fields[0].GetUInt32();
            data << fields[1].GetUInt32();
            SendPacket (&data);
            DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f\n",fields[0].GetUInt32(),fields[1].GetUInt32(),fields[2].GetFloat(), fields[3].GetFloat(), fields[4].GetFloat());
            delete result5;
        }
        delete result7;
    }

    data.Initialize( SMSG_TUTORIAL_FLAGS, 8*32 );

    for (int i = 0; i < 8; i++)
        data << uint32( GetPlayer()->GetTutorialInt(i) );

    SendPacket(&data);
    //sLog.outDebug( "WORLD: Sent tutorial flags." );

    GetPlayer()->SendInitialSpells();
    GetPlayer()->SendInitialActionButtons();

    /*if(GetPlayer()->getClass() == CLASS_HUNTER || GetPlayer()->getClass() == CLASS_ROGUE)
    {
        uint32 shiftdata=0x01;
        for(uint8 i=0;i<32;i++)
        {
            if ( 522753 & shiftdata )
            {
                data.Initialize(SMSG_SET_FLAT_SPELL_MODIFIER);
                data << uint8(i);
                data << uint8(5);
                data << uint16(1);
                data << uint16(0);
                SendPacket(&data);
            }
            shiftdata=shiftdata<<1;
        }
    }*/

    data.Initialize(SMSG_INITIALIZE_FACTIONS, (4+64*5));
    data << uint32 (0x00000040);
    for(uint32 a=0; a<64; a++)
    {
        if(GetPlayer()->FactionIsInTheList(a))
        {
            std::list<struct Factions>::iterator itr;
            for(itr = GetPlayer()->factions.begin(); itr != GetPlayer()->factions.end(); ++itr)
            {
                if(itr->ReputationListID == a)
                {
                    data << uint8  (itr->Flags);
                    data << uint32 (itr->Standing);
                    break;
                }
            }
        }
        else
        {
            data << uint8  (0x00);
            data << uint32 (0x00000000);
        }
    }
    SendPacket(&data);

    GetPlayer()->UpdateHonor();

    data.Initialize(SMSG_LOGIN_SETTIMESPEED, 8);
    time_t gameTime = sWorld.GetGameTime();
    struct tm *lt = localtime(&gameTime);
    uint32 xmitTime = (lt->tm_year - 100) << 24 | lt->tm_mon  << 20 |
        (lt->tm_mday - 1) << 14 | lt->tm_wday << 11 |
        lt->tm_hour << 6 | lt->tm_min;
    data << xmitTime;
    data << (uint32)0x3C888889;                             //(float)0.017f;
    SendPacket( &data );

    //Show cinematic at the first time that player login
    if( !GetPlayer()->getCinematic() )
    {
        GetPlayer()->setCinematic(1);

        ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(GetPlayer()->getRace());
        if(rEntry)
        {
            data.Initialize( SMSG_TRIGGER_CINEMATIC,4 );
            data << uint32(rEntry->startmovie);
            SendPacket( &data );
        }
    }

    QueryResult *result = sDatabase.PQuery("SELECT `guildid`,`rank` FROM `guild_member` WHERE `guid` = '%u'",pCurrChar->GetGUIDLow());

    if(result)
    {
        Field *fields = result->Fetch();
        pCurrChar->SetInGuild(fields[0].GetUInt32());
        pCurrChar->SetRank(fields[1].GetUInt32());
        delete result;
    }

    MapManager::Instance().GetMap(pCurrChar->GetMapId())->Add(pCurrChar);
    ObjectAccessor::Instance().InsertPlayer(pCurrChar);
    //sLog.outDebug("Player %s added to Map.",pCurrChar->GetName());

    if (pCurrChar->m_transport)
    {
        Transport* curTrans = pCurrChar->m_transport;
        pCurrChar->TeleportTo(curTrans->GetMapId(), curTrans->GetPositionX(), curTrans->GetPositionY(), curTrans->GetPositionZ(), curTrans->GetOrientation(), true, false);
    }

    sDatabase.PExecute("UPDATE `character` SET `online` = 1 WHERE `guid` = '%u'", pCurrChar->GetGUIDLow());
    loginDatabase.PExecute("UPDATE `account` SET `online` = 1 WHERE `id` = '%u'", GetAccountId());
    plr->SetInGameTime( getMSTime() );

    data.Initialize(SMSG_FRIEND_STATUS, 19);
    data<<uint8(FRIEND_ONLINE);
    data<<pCurrChar->GetGUID();
    data<<uint8(1);
    data<<pCurrChar->GetAreaId();
    data<<pCurrChar->getLevel();
    data<<pCurrChar->getClass();
    pCurrChar->BroadcastPacketToFriendListers(&data);

    // setting new speed if dead
    if ( pCurrChar->m_deathState == DEAD )
    {
        pCurrChar->SetMovement(MOVE_WATER_WALK);

        if (pCurrChar->getRace() == RACE_NIGHTELF)
        {
            pCurrChar->SetSpeed(MOVE_RUN,  1.5f*1.2f, true);
            pCurrChar->SetSpeed(MOVE_SWIM, 1.5f*1.2f, true);
        }
        else
        {
            pCurrChar->SetSpeed(MOVE_RUN,  1.5f, true);
            pCurrChar->SetSpeed(MOVE_SWIM, 1.5f, true);
        }
    }

    pCurrChar->LoadEnchant();
    pCurrChar->_LoadSpellCooldowns();

    // Place charcter in world (and load zone) before some object loading
    pCurrChar->LoadCorpse();
    pCurrChar->LoadPet();
    // show time before shutdown if shudown planned.
    if(sWorld.IsShutdowning())
        sWorld.ShutdownMsg(true,pCurrChar);

    result = sDatabase.PQuery("SELECT `leaderGuid` FROM `raidgroup_member` WHERE `memberGuid`='%u'", GUID_LOPART(pCurrChar->GetGUID()));
    if(result)
    {
        uint64 leaderGuid = MAKE_GUID((*result)[0].GetUInt32(),HIGHGUID_PLAYER);
        delete result;

        pCurrChar->groupInfo.group = objmgr.GetGroupByLeader(leaderGuid);
        if(pCurrChar->groupInfo.group)
        {
            pCurrChar->groupInfo.group->SendInit(this);
            pCurrChar->groupInfo.group->SendUpdate();
        }
    }

    if(pCurrChar->isGameMaster())
        SendNotification("GM mode is ON");
    m_playerLoading = false;
}
void WorldSession::HandleCharCreateOpcode( WorldPacket & recv_data )
{
    CHECK_PACKET_SIZE(recv_data, 10);
    std::string name;
    uint8 race, class_;

    recv_data >> name >> race >> class_;
    recv_data.rpos(0);

    WorldPacket data(SMSG_CHAR_CREATE, 1);
    if(!sWorld.VerifyName(name.c_str(), name.length()))
    {
        data << uint8(CHAR_CREATE_NAME_IN_USE);
        SendPacket(&data);
        return;
    }

    if(g_characterNameFilter->Parse(name, false))
    {
        data << uint8(CHAR_CREATE_NAME_IN_USE);
        SendPacket(&data);
        return;
    }

    //reserved for console whisper
    if(name == "Console" ||  name == "console")
    {
        data << uint8(CHAR_CREATE_NAME_IN_USE);
        SendPacket(&data);
        return;
    }

    if(objmgr.GetPlayerInfoByName(name.c_str()) != 0)
    {
        data << uint8(CHAR_CREATE_NAME_IN_USE);
        SendPacket(&data);
        return;
    }

    if(!sHookInterface.OnNewCharacter(race, class_, this, name.c_str()))
    {
        data << uint8(CHAR_CREATE_NAME_IN_USE);
        SendPacket(&data);
        return;
    }

    if( class_ == DEATHKNIGHT )
    {
        if(!HasFlag(ACCOUNT_FLAG_XPACK_02))
        {
            data << uint8(CHAR_CREATE_EXPANSION);
            SendPacket(&data);
            return;
        }
        else if(!CanCreateDeathKnight() && !HasGMPermissions())
        {
            if(sWorld.m_deathKnightReqLevel > m_highestLevel)
                data << uint8(CHAR_CREATE_LEVEL_REQUIREMENT);
            else
                data << uint8(CHAR_CREATE_UNIQUE_CLASS_LIMIT);
            SendPacket(&data);
            return;
        }
    }

    QueryResult * result = CharacterDatabase.Query("SELECT COUNT(*) FROM banned_names WHERE name = '%s'", CharacterDatabase.EscapeString(name).c_str());
    if(result)
    {
        if(result->Fetch()[0].GetUInt32() > 0)
        {
            // That name is banned!
            data << uint8(CHAR_NAME_PROFANE);
            SendPacket(&data);
            delete result;
            return;
        }
        delete result;
    }
    // loading characters

    //checking number of chars is useless since client will not allow to create more than 10 chars
    //as the 'create' button will not appear (unless we want to decrease maximum number of characters)
    Player* pNewChar = objmgr.CreatePlayer();
    pNewChar->SetSession(this);
    if(!pNewChar->Create( recv_data ))
    {
        // failed.
        pNewChar->ok_to_remove = true;
        pNewChar->Destruct();
        pNewChar = NULLPLR;
        return;
    }

    pNewChar->UnSetBanned();
    pNewChar->addSpell(22027);    // Remove Insignia

    if(pNewChar->getClass() == WARLOCK)
    {
        pNewChar->AddSummonSpell(416, 3110);        // imp fireball
        pNewChar->AddSummonSpell(417, 19505);
        pNewChar->AddSummonSpell(1860, 3716);
        pNewChar->AddSummonSpell(1863, 7814);
    }

    pNewChar->SaveToDB(true);

    PlayerInfo *pn = new PlayerInfo;
    memset(pn, 0, sizeof(PlayerInfo));
    pn->guid = pNewChar->GetLowGUID();
    pn->name = strdup(pNewChar->GetName());
    pn->_class = pNewChar->getClass();
    pn->race = pNewChar->getRace();
    pn->gender = pNewChar->getGender();
    pn->lastLevel = pNewChar->getLevel();
    pn->lastZone = pNewChar->GetZoneId();
    pn->lastOnline = UNIXTIME;
    pn->team = pNewChar->GetTeam();
    pn->acct = GetAccountId();
    objmgr.AddPlayerInfo(pn);

    pNewChar->ok_to_remove = true;
    pNewChar->Destruct();
    pNewChar = NULLPLR;

    // CHAR_CREATE_SUCCESS
    data << uint8(CHAR_CREATE_SUCCESS);
    SendPacket(&data);

    sLogonCommHandler.UpdateAccountCount(GetAccountId(), 1);
}
Example #19
0
void WorldSession::SendLfgSearchResults(LfgType type, uint32 entry)
{
    WorldPacket data(SMSG_LFG_SEARCH_RESULTS);
    data << uint32(type);                                   // type
    data << uint32(entry);                                  // entry from LFGDungeons.dbc

    uint8 isGuidsPresent = 0;
    data << uint8(isGuidsPresent);
    if (isGuidsPresent)
    {
        uint32 guids_count = 0;
        data << uint32(guids_count);
        for (uint32 i = 0; i < guids_count; ++i)
        {
            data << uint64(0);                              // player/group guid
        }
    }

    uint32 groups_count = 1;
    data << uint32(groups_count);                           // groups count
    data << uint32(groups_count);                           // groups count (total?)

    for (uint32 i = 0; i < groups_count; ++i)
    {
        data << uint64(1);                                  // group guid

        uint32 flags = 0x92;
        data << uint32(flags);                              // flags

        if (flags & 0x2)
        {
            data << uint8(0);                               // comment string, max len 256
        }

        if (flags & 0x10)
        {
            for (uint32 j = 0; j < 3; ++j)
                data << uint8(0);                           // roles
        }

        if (flags & 0x80)
        {
            data << uint64(0);                              // instance guid
            data << uint32(0);                              // completed encounters
        }
    }

    // TODO: Guard Player map
    HashMapHolder<Player>::MapType const& players = sObjectAccessor.GetPlayers();
    uint32 playersSize = players.size();
    data << uint32(playersSize);                            // players count
    data << uint32(playersSize);                            // players count (total?)

    for (HashMapHolder<Player>::MapType::const_iterator iter = players.begin(); iter != players.end(); ++iter)
    {
        Player* plr = iter->second;

        if (!plr || plr->GetTeam() != _player->GetTeam())
            continue;

        if (!plr->IsInWorld())
            continue;

        data << plr->GetObjectGuid();                       // guid

        uint32 flags = 0xFF;
        data << uint32(flags);                              // flags

        if (flags & 0x1)
        {
            data << uint8(plr->getLevel());
            data << uint8(plr->getClass());
            data << uint8(plr->getRace());

            for (uint32 i = 0; i < 3; ++i)
                data << uint8(0);                           // talent spec x/x/x

            data << uint32(0);                              // armor
            data << uint32(0);                              // spd/heal
            data << uint32(0);                              // spd/heal
            data << uint32(0);                              // HasteMelee
            data << uint32(0);                              // HasteRanged
            data << uint32(0);                              // HasteSpell
            data << float(0);                               // MP5
            data << float(0);                               // MP5 Combat
            data << uint32(0);                              // AttackPower
            data << uint32(0);                              // Agility
            data << uint32(0);                              // Health
            data << uint32(0);                              // Mana
            data << uint32(0);                              // Unk1
            data << float(0);                               // Unk2
            data << uint32(0);                              // Defence
            data << uint32(0);                              // Dodge
            data << uint32(0);                              // Block
            data << uint32(0);                              // Parry
            data << uint32(0);                              // Crit
            data << uint32(0);                              // Expertise
        }

        if (flags & 0x2)
            data << "";                                     // comment

        if (flags & 0x4)
            data << uint8(0);                               // group leader

        if (flags & 0x8)
            data << uint64(1);                              // group guid

        if (flags & 0x10)
            data << uint8(0);                               // roles

        if (flags & 0x20)
            data << uint32(plr->GetZoneId());               // areaid

        if (flags & 0x40)
            data << uint8(0);                               // status

        if (flags & 0x80)
        {
            data << uint64(0);                              // instance guid
            data << uint32(0);                              // completed encounters
        }
    }

    SendPacket(&data);
}
Example #20
0
        void UpdateAI(const uint32 diff)
        {
            if (PlayerGUID && !me->getVictim() && me->isAlive())
            {
                if (ExecuteSpeech_Timer <= diff)
                {
                    Player* player = Unit::GetPlayer(*me, PlayerGUID);

                    if (!player)
                    {
                        Reset();
                        return;
                    }

                    //TODO: simplify text's selection

                    switch (player->getRace())
                    {
                        case RACE_HUMAN:
                            switch (ExecuteSpeech_Counter)
                            {
                                case 0: DoScriptText(SAY_EXEC_START_1, me, player); break;
                                case 1: me->SetStandState(UNIT_STAND_STATE_STAND); break;
                                case 2: DoScriptText(SAY_EXEC_PROG_5, me, player); break;
                                case 3: DoScriptText(SAY_EXEC_NAME_1, me, player); break;
                                case 4: DoScriptText(SAY_EXEC_RECOG_1, me, player); break;
                                case 5: DoScriptText(SAY_EXEC_NOREM_5, me, player); break;
                                case 6: DoScriptText(SAY_EXEC_THINK_7, me, player); break;
                                case 7: DoScriptText(SAY_EXEC_LISTEN_1, me, player); break;
                                case 8:
                                    if (Creature* Plaguefist = GetClosestCreatureWithEntry(me, NPC_PLAGUEFIST, 85.0f))
                                        DoScriptText(SAY_PLAGUEFIST, Plaguefist, player);
                                    break;
                                case 9:
                                    DoScriptText(SAY_EXEC_TIME_6, me, player);
                                    me->SetStandState(UNIT_STAND_STATE_KNEEL);
                                    me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE);
                                    break;
                                case 10: DoScriptText(SAY_EXEC_WAITING, me, player); break;
                                case 11:
                                    DoScriptText(EMOTE_DIES, me);
                                    me->setDeathState(JUST_DIED);
                                    me->SetHealth(0);
                                    return;
                            }
                            break;
                        case RACE_ORC:
                            switch (ExecuteSpeech_Counter)
                            {
                                case 0: DoScriptText(SAY_EXEC_START_1, me, player); break;
                                case 1: me->SetStandState(UNIT_STAND_STATE_STAND); break;
                                case 2: DoScriptText(SAY_EXEC_PROG_6, me, player); break;
                                case 3: DoScriptText(SAY_EXEC_NAME_1, me, player); break;
                                case 4: DoScriptText(SAY_EXEC_RECOG_1, me, player); break;
                                case 5: DoScriptText(SAY_EXEC_NOREM_7, me, player); break;
                                case 6: DoScriptText(SAY_EXEC_THINK_8, me, player); break;
                                case 7: DoScriptText(SAY_EXEC_LISTEN_1, me, player); break;
                                case 8:
                                    if (Creature* Plaguefist = GetClosestCreatureWithEntry(me, NPC_PLAGUEFIST, 85.0f))
                                        DoScriptText(SAY_PLAGUEFIST, Plaguefist, player);
                                    break;
                                case 9:
                                    DoScriptText(SAY_EXEC_TIME_8, me, player);
                                    me->SetStandState(UNIT_STAND_STATE_KNEEL);
                                    me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE);
                                    break;
                                case 10: DoScriptText(SAY_EXEC_WAITING, me, player); break;
                                case 11:
                                    DoScriptText(EMOTE_DIES, me);
                                    me->setDeathState(JUST_DIED);
                                    me->SetHealth(0);
                                    return;
                            }
                            break;
                        case RACE_DWARF:
                            switch (ExecuteSpeech_Counter)
                            {
                                case 0: DoScriptText(SAY_EXEC_START_2, me, player); break;
                                case 1: me->SetStandState(UNIT_STAND_STATE_STAND); break;
                                case 2: DoScriptText(SAY_EXEC_PROG_2, me, player); break;
                                case 3: DoScriptText(SAY_EXEC_NAME_1, me, player); break;
                                case 4: DoScriptText(SAY_EXEC_RECOG_3, me, player); break;
                                case 5: DoScriptText(SAY_EXEC_NOREM_2, me, player); break;
                                case 6: DoScriptText(SAY_EXEC_THINK_5, me, player); break;
                                case 7: DoScriptText(SAY_EXEC_LISTEN_2, me, player); break;
                                case 8:
                                    if (Creature* Plaguefist = GetClosestCreatureWithEntry(me, NPC_PLAGUEFIST, 85.0f))
                                        DoScriptText(SAY_PLAGUEFIST, Plaguefist, player);
                                    break;
                                case 9:
                                    DoScriptText(SAY_EXEC_TIME_3, me, player);
                                    me->SetStandState(UNIT_STAND_STATE_KNEEL);
                                    me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE);
                                    break;
                                case 10: DoScriptText(SAY_EXEC_WAITING, me, player); break;
                                case 11:
                                    DoScriptText(EMOTE_DIES, me);
                                    me->setDeathState(JUST_DIED);
                                    me->SetHealth(0);
                                    return;
                            }
                            break;
                        case RACE_NIGHTELF:
                            switch (ExecuteSpeech_Counter)
                            {
                                case 0: DoScriptText(SAY_EXEC_START_1, me, player); break;
                                case 1: me->SetStandState(UNIT_STAND_STATE_STAND); break;
                                case 2: DoScriptText(SAY_EXEC_PROG_5, me, player); break;
                                case 3: DoScriptText(SAY_EXEC_NAME_1, me, player); break;
                                case 4: DoScriptText(SAY_EXEC_RECOG_1, me, player); break;
                                case 5: DoScriptText(SAY_EXEC_NOREM_6, me, player); break;
                                case 6: DoScriptText(SAY_EXEC_THINK_2, me, player); break;
                                case 7: DoScriptText(SAY_EXEC_LISTEN_1, me, player); break;
                                case 8:
                                    if (Creature* Plaguefist = GetClosestCreatureWithEntry(me, NPC_PLAGUEFIST, 85.0f))
                                        DoScriptText(SAY_PLAGUEFIST, Plaguefist, player);
                                    break;
                                case 9:
                                    DoScriptText(SAY_EXEC_TIME_7, me, player);
                                    me->SetStandState(UNIT_STAND_STATE_KNEEL);
                                    me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE);
                                    break;
                                case 10: DoScriptText(SAY_EXEC_WAITING, me, player); break;
                                case 11:
                                    DoScriptText(EMOTE_DIES, me);
                                    me->setDeathState(JUST_DIED);
                                    me->SetHealth(0);
                                    return;
                            }
                            break;
                        case RACE_UNDEAD_PLAYER:
                            switch (ExecuteSpeech_Counter)
                            {
                                case 0: DoScriptText(SAY_EXEC_START_1, me, player); break;
                                case 1: me->SetStandState(UNIT_STAND_STATE_STAND); break;
                                case 2: DoScriptText(SAY_EXEC_PROG_3, me, player); break;
                                case 3: DoScriptText(SAY_EXEC_NAME_1, me, player); break;
                                case 4: DoScriptText(SAY_EXEC_RECOG_4, me, player); break;
                                case 5: DoScriptText(SAY_EXEC_NOREM_3, me, player); break;
                                case 6: DoScriptText(SAY_EXEC_THINK_1, me, player); break;
                                case 7: DoScriptText(SAY_EXEC_LISTEN_3, me, player); break;
                                case 8:
                                    if (Creature* Plaguefist = GetClosestCreatureWithEntry(me, NPC_PLAGUEFIST, 85.0f))
                                        DoScriptText(SAY_PLAGUEFIST, Plaguefist, player);
                                    break;
                                case 9:
                                    DoScriptText(SAY_EXEC_TIME_4, me, player);
                                    me->SetStandState(UNIT_STAND_STATE_KNEEL);
                                    me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE);
                                    break;
                                case 10: DoScriptText(SAY_EXEC_WAITING, me, player); break;
                                case 11:
                                    DoScriptText(EMOTE_DIES, me);
                                    me->setDeathState(JUST_DIED);
                                    me->SetHealth(0);
                                    return;
                            }
                            break;
                        case RACE_TAUREN:
                            switch (ExecuteSpeech_Counter)
                            {
                                case 0: DoScriptText(SAY_EXEC_START_1, me, player); break;
                                case 1: me->SetStandState(UNIT_STAND_STATE_STAND); break;
                                case 2: DoScriptText(SAY_EXEC_PROG_1, me, player); break;
                                case 3: DoScriptText(SAY_EXEC_NAME_1, me, player); break;
                                case 4: DoScriptText(SAY_EXEC_RECOG_5, me, player); break;
                                case 5: DoScriptText(SAY_EXEC_NOREM_8, me, player); break;
                                case 6: DoScriptText(SAY_EXEC_THINK_9, me, player); break;
                                case 7: DoScriptText(SAY_EXEC_LISTEN_1, me, player); break;
                                case 8:
                                    if (Creature* Plaguefist = GetClosestCreatureWithEntry(me, NPC_PLAGUEFIST, 85.0f))
                                        DoScriptText(SAY_PLAGUEFIST, Plaguefist, player);
                                    break;
                                case 9:
                                    DoScriptText(SAY_EXEC_TIME_9, me, player);
                                    me->SetStandState(UNIT_STAND_STATE_KNEEL);
                                    me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE);
                                    break;
                                case 10: DoScriptText(SAY_EXEC_WAITING, me, player); break;
                                case 11:
                                    DoScriptText(EMOTE_DIES, me);
                                    me->setDeathState(JUST_DIED);
                                    me->SetHealth(0);
                                    return;
                            }
                            break;
                        case RACE_GNOME:
                            switch (ExecuteSpeech_Counter)
                            {
                                case 0: DoScriptText(SAY_EXEC_START_1, me, player); break;
                                case 1: me->SetStandState(UNIT_STAND_STATE_STAND); break;
                                case 2: DoScriptText(SAY_EXEC_PROG_4, me, player); break;
                                case 3: DoScriptText(SAY_EXEC_NAME_1, me, player); break;
                                case 4: DoScriptText(SAY_EXEC_RECOG_1, me, player); break;
                                case 5: DoScriptText(SAY_EXEC_NOREM_4, me, player); break;
                                case 6: DoScriptText(SAY_EXEC_THINK_6, me, player); break;
                                case 7: DoScriptText(SAY_EXEC_LISTEN_1, me, player); break;
                                case 8:
                                    if (Creature* Plaguefist = GetClosestCreatureWithEntry(me, NPC_PLAGUEFIST, 85.0f))
                                        DoScriptText(SAY_PLAGUEFIST, Plaguefist, player);
                                    break;
                                case 9:
                                    DoScriptText(SAY_EXEC_TIME_5, me, player);
                                    me->SetStandState(UNIT_STAND_STATE_KNEEL);
                                    me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE);
                                    break;
                                case 10: DoScriptText(SAY_EXEC_WAITING, me, player); break;
                                case 11:
                                    DoScriptText(EMOTE_DIES, me);
                                    me->setDeathState(JUST_DIED);
                                    me->SetHealth(0);
                                    return;
                            }
                            break;
                        case RACE_TROLL:
                            switch (ExecuteSpeech_Counter)
                            {
                                case 0: DoScriptText(SAY_EXEC_START_3, me, player); break;
                                case 1: me->SetStandState(UNIT_STAND_STATE_STAND); break;
                                case 2: DoScriptText(SAY_EXEC_PROG_7, me, player); break;
                                case 3: DoScriptText(SAY_EXEC_NAME_2, me, player); break;
                                case 4: DoScriptText(SAY_EXEC_RECOG_6, me, player); break;
                                case 5: DoScriptText(SAY_EXEC_NOREM_9, me, player); break;
                                case 6: DoScriptText(SAY_EXEC_THINK_10, me, player); break;
                                case 7: DoScriptText(SAY_EXEC_LISTEN_4, me, player); break;
                                case 8:
                                    if (Creature* Plaguefist = GetClosestCreatureWithEntry(me, NPC_PLAGUEFIST, 85.0f))
                                        DoScriptText(SAY_PLAGUEFIST, Plaguefist, player);
                                    break;
                                case 9:
                                    DoScriptText(SAY_EXEC_TIME_10, me, player);
                                    me->SetStandState(UNIT_STAND_STATE_KNEEL);
                                    me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE);
                                    break;
                                case 10: DoScriptText(SAY_EXEC_WAITING, me, player); break;
                                case 11:
                                    DoScriptText(EMOTE_DIES, me);
                                    me->setDeathState(JUST_DIED);
                                    me->SetHealth(0);
                                    return;
                            }
                            break;
                        case RACE_BLOODELF:
                            switch (ExecuteSpeech_Counter)
                            {
                                case 0: DoScriptText(SAY_EXEC_START_1, me, player); break;
                                case 1: me->SetStandState(UNIT_STAND_STATE_STAND); break;
                                case 2: DoScriptText(SAY_EXEC_PROG_1, me, player); break;
                                case 3: DoScriptText(SAY_EXEC_NAME_1, me, player); break;
                                case 4: DoScriptText(SAY_EXEC_RECOG_1, me, player); break;
                                //case 5: //unknown
                                case 6: DoScriptText(SAY_EXEC_THINK_3, me, player); break;
                                case 7: DoScriptText(SAY_EXEC_LISTEN_1, me, player); break;
                                case 8:
                                    if (Creature* Plaguefist = GetClosestCreatureWithEntry(me, NPC_PLAGUEFIST, 85.0f))
                                        DoScriptText(SAY_PLAGUEFIST, Plaguefist, player);
                                    break;
                                case 9:
                                    DoScriptText(SAY_EXEC_TIME_1, me, player);
                                    me->SetStandState(UNIT_STAND_STATE_KNEEL);
                                    me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE);
                                    break;
                                case 10: DoScriptText(SAY_EXEC_WAITING, me, player); break;
                                case 11:
                                    DoScriptText(EMOTE_DIES, me);
                                    me->setDeathState(JUST_DIED);
                                    me->SetHealth(0);
                                    return;
                            }
                            break;
                        case RACE_DRAENEI:
                            switch (ExecuteSpeech_Counter)
                            {
                                case 0: DoScriptText(SAY_EXEC_START_1, me, player); break;
                                case 1: me->SetStandState(UNIT_STAND_STATE_STAND); break;
                                case 2: DoScriptText(SAY_EXEC_PROG_1, me, player); break;
                                case 3: DoScriptText(SAY_EXEC_NAME_1, me, player); break;
                                case 4: DoScriptText(SAY_EXEC_RECOG_2, me, player); break;
                                case 5: DoScriptText(SAY_EXEC_NOREM_1, me, player); break;
                                case 6: DoScriptText(SAY_EXEC_THINK_4, me, player); break;
                                case 7: DoScriptText(SAY_EXEC_LISTEN_1, me, player); break;
                                case 8:
                                    if (Creature* Plaguefist = GetClosestCreatureWithEntry(me, NPC_PLAGUEFIST, 85.0f))
                                        DoScriptText(SAY_PLAGUEFIST, Plaguefist, player);
                                    break;
                                case 9:
                                    DoScriptText(SAY_EXEC_TIME_2, me, player);
                                    me->SetStandState(UNIT_STAND_STATE_KNEEL);
                                    me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE);
                                    break;
                                case 10: DoScriptText(SAY_EXEC_WAITING, me, player); break;
                                case 11:
                                    DoScriptText(EMOTE_DIES, me);
                                    me->setDeathState(JUST_DIED);
                                    me->SetHealth(0);
                                    return;
                            }
                            break;
                    }

                    if (ExecuteSpeech_Counter >= 9)
                        ExecuteSpeech_Timer = 15000;
                    else
                        ExecuteSpeech_Timer = 7000;

                    ++ExecuteSpeech_Counter;
                }
                else
                    ExecuteSpeech_Timer -= diff;
            }
        }
Example #21
0
void WorldSession::HandlePlayerLogin(LoginQueryHolder * holder)
{
    uint64 playerGuid = holder->GetGuid();

    Player* pCurrChar = new Player(this);
    pCurrChar->GetMotionMaster()->Initialize();

    // "GetAccountId()==db stored account id" checked in LoadFromDB (prevent login not own character using cheating tools)
    if(!pCurrChar->LoadFromDB(GUID_LOPART(playerGuid), holder))
    {
        KickPlayer();                                       // disconnect client, player no set to session and it will not deleted or saved at kick
        delete pCurrChar;                                   // delete it manually
        delete holder;                                      // delete all unprocessed queries
        m_playerLoading = false;
        return;
    }

    SetPlayer(pCurrChar);

    pCurrChar->SendDungeonDifficulty(false);

    WorldPacket data( SMSG_LOGIN_VERIFY_WORLD, 20 );
    data << pCurrChar->GetMapId();
    data << pCurrChar->GetPositionX();
    data << pCurrChar->GetPositionY();
    data << pCurrChar->GetPositionZ();
    data << pCurrChar->GetOrientation();
    SendPacket(&data);

    data.Initialize( SMSG_ACCOUNT_DATA_TIMES, 4+1+8*4 );    // changed in WotLK
    data << uint32(time(NULL));                             // unix time of something
    data << uint8(1);
    for(int i = 0; i < NUM_ACCOUNT_DATA_TYPES; i++)
        data << uint32(GetAccountData(i)->Time);            // also unix time
    SendPacket(&data);

    data.Initialize(SMSG_FEATURE_SYSTEM_STATUS, 2);         // added in 2.2.0
    data << uint8(2);                                       // unknown value
    data << uint8(0);                                       // enable(1)/disable(0) voice chat interface in client
    SendPacket(&data);

    // Send MOTD
    {
        data.Initialize(SMSG_MOTD, 50);                     // new in 2.0.1
        data << (uint32)0;

        uint32 linecount=0;
        std::string str_motd = sWorld.GetMotd();
        std::string::size_type pos, nextpos;

        pos = 0;
        while ( (nextpos= str_motd.find('@',pos)) != std::string::npos )
        {
            if (nextpos != pos)
            {
                data << str_motd.substr(pos,nextpos-pos);
                ++linecount;
            }
            pos = nextpos+1;
        }

        if (pos<str_motd.length())
        {
            data << str_motd.substr(pos);
            ++linecount;
        }

        data.put(0, linecount);

        SendPacket( &data );
        DEBUG_LOG( "WORLD: Sent motd (SMSG_MOTD)" );
    }

    //QueryResult *result = CharacterDatabase.PQuery("SELECT guildid,rank FROM guild_member WHERE guid = '%u'",pCurrChar->GetGUIDLow());
    QueryResult *resultGuild = holder->GetResult(PLAYER_LOGIN_QUERY_LOADGUILD);

    if(resultGuild)
    {
        Field *fields = resultGuild->Fetch();
        pCurrChar->SetInGuild(fields[0].GetUInt32());
        pCurrChar->SetRank(fields[1].GetUInt32());
        delete resultGuild;
    }
    else if(pCurrChar->GetGuildId())                        // clear guild related fields in case wrong data about non existed membership
    {
        pCurrChar->SetInGuild(0);
        pCurrChar->SetRank(0);
    }

    if(pCurrChar->GetGuildId() != 0)
    {
        Guild* guild = objmgr.GetGuildById(pCurrChar->GetGuildId());
        if(guild)
        {
            data.Initialize(SMSG_GUILD_EVENT, (2+guild->GetMOTD().size()+1));
            data << (uint8)GE_MOTD;
            data << (uint8)1;
            data << guild->GetMOTD();
            SendPacket(&data);
            DEBUG_LOG( "WORLD: Sent guild-motd (SMSG_GUILD_EVENT)" );

            data.Initialize(SMSG_GUILD_EVENT, (5+10));      // we guess size
            data<<(uint8)GE_SIGNED_ON;
            data<<(uint8)1;
            data<<pCurrChar->GetName();
            data<<pCurrChar->GetGUID();
            guild->BroadcastPacket(&data);
            DEBUG_LOG( "WORLD: Sent guild-signed-on (SMSG_GUILD_EVENT)" );

            // Increment online members of the guild
            guild->IncOnlineMemberCount();
        }
        else
        {
            // remove wrong guild data
            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());
            pCurrChar->SetInGuild(0);
        }
    }

    if(!pCurrChar->isAlive())
        pCurrChar->SendCorpseReclaimDelay(true);

    pCurrChar->SendInitialPacketsBeforeAddToMap();

    //Show cinematic at the first time that player login
    if( !pCurrChar->getCinematic() )
    {
        pCurrChar->setCinematic(1);

        if(ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(pCurrChar->getClass()))
        {
            if(cEntry->CinematicSequence)
            {
                data.Initialize(SMSG_TRIGGER_CINEMATIC, 4);
                data << uint32(cEntry->CinematicSequence);
                SendPacket( &data );
            }
            else if(ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(pCurrChar->getRace()))
            {
                data.Initialize(SMSG_TRIGGER_CINEMATIC, 4);
                data << uint32(rEntry->CinematicSequence);
                SendPacket( &data );
            }
        }
    }

    if (!pCurrChar->GetMap()->Add(pCurrChar))
    {
        AreaTrigger const* at = objmgr.GetGoBackTrigger(pCurrChar->GetMapId());
        if(at)
            pCurrChar->TeleportTo(at->target_mapId, at->target_X, at->target_Y, at->target_Z, pCurrChar->GetOrientation());
        else
            pCurrChar->TeleportTo(pCurrChar->m_homebindMapId, pCurrChar->m_homebindX, pCurrChar->m_homebindY, pCurrChar->m_homebindZ, pCurrChar->GetOrientation());
    }

    ObjectAccessor::Instance().AddObject(pCurrChar);
    //sLog.outDebug("Player %s added to Map.",pCurrChar->GetName());
    pCurrChar->GetSocial()->SendSocialList();

    pCurrChar->SendInitialPacketsAfterAddToMap();

    CharacterDatabase.PExecute("UPDATE characters SET online = 1 WHERE guid = '%u'", pCurrChar->GetGUIDLow());
    loginDatabase.PExecute("UPDATE account SET online = 1 WHERE id = '%u'", GetAccountId());
    pCurrChar->SetInGameTime( getMSTime() );

    // announce group about member online (must be after add to player list to receive announce to self)
    if(Group *group = pCurrChar->GetGroup())
    {
        //pCurrChar->groupInfo.group->SendInit(this); // useless
        group->SendUpdate();
    }

    // friend status
    sSocialMgr.SendFriendStatus(pCurrChar, FRIEND_ONLINE, pCurrChar->GetGUIDLow(), true);

    // Place character in world (and load zone) before some object loading
    pCurrChar->LoadCorpse();

    // setting Ghost+speed if dead
    if (pCurrChar->m_deathState != ALIVE)
    {
        // not blizz like, we must correctly save and load player instead...
        if(pCurrChar->getRace() == RACE_NIGHTELF)
            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)
        pCurrChar->CastSpell(pCurrChar, 8326, true, 0);     // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)

        pCurrChar->SetMovement(MOVE_WATER_WALK);
    }

    if(uint32 sourceNode = pCurrChar->m_taxi.GetTaxiSource())
    {

        sLog.outDebug( "WORLD: Restart character %u taxi flight", pCurrChar->GetGUIDLow() );

        uint32 MountId = objmgr.GetTaxiMount(sourceNode, pCurrChar->GetTeam());
        uint32 path = pCurrChar->m_taxi.GetCurrentTaxiPath();

        // search appropriate start path node
        uint32 startNode = 0;

        TaxiPathNodeList const& nodeList = sTaxiPathNodesByPath[path];

        float distPrev = MAP_SIZE*MAP_SIZE;
        float distNext =
            (nodeList[0].x-pCurrChar->GetPositionX())*(nodeList[0].x-pCurrChar->GetPositionX())+
            (nodeList[0].y-pCurrChar->GetPositionY())*(nodeList[0].y-pCurrChar->GetPositionY())+
            (nodeList[0].z-pCurrChar->GetPositionZ())*(nodeList[0].z-pCurrChar->GetPositionZ());

        for(uint32 i = 1; i < nodeList.size(); ++i)
        {
            TaxiPathNode const& node = nodeList[i];
            TaxiPathNode const& prevNode = nodeList[i-1];

            // skip nodes at another map
            if(node.mapid != pCurrChar->GetMapId())
                continue;

            distPrev = distNext;

            distNext =
                (node.x-pCurrChar->GetPositionX())*(node.x-pCurrChar->GetPositionX())+
                (node.y-pCurrChar->GetPositionY())*(node.y-pCurrChar->GetPositionY())+
                (node.z-pCurrChar->GetPositionZ())*(node.z-pCurrChar->GetPositionZ());

            float distNodes =
                (node.x-prevNode.x)*(node.x-prevNode.x)+
                (node.y-prevNode.y)*(node.y-prevNode.y)+
                (node.z-prevNode.z)*(node.z-prevNode.z);

            if(distNext + distPrev < distNodes)
            {
                startNode = i;
                break;
            }
        }

        SendDoFlight( MountId, path, startNode );
    }

    // Load pet if any and player is alive and not in taxi flight
    if(pCurrChar->isAlive() && pCurrChar->m_taxi.GetTaxiSource()==0)
        pCurrChar->LoadPet();

    // Set FFA PvP for non GM in non-rest mode
    if(sWorld.IsFFAPvPRealm() && !pCurrChar->isGameMaster() && !pCurrChar->HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_RESTING) )
        pCurrChar->SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);

    if(pCurrChar->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP))
        pCurrChar->SetContestedPvP();

    // Apply at_login requests
    if(pCurrChar->HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
    {
        pCurrChar->resetSpells();
        SendNotification(LANG_RESET_SPELLS);
    }

    if(pCurrChar->HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
    {
        pCurrChar->resetTalents(true);
        SendNotification(LANG_RESET_TALENTS);
    }

    // show time before shutdown if shutdown planned.
    if(sWorld.IsShutdowning())
        sWorld.ShutdownMsg(true,pCurrChar);

    if(sWorld.getConfig(CONFIG_ALL_TAXI_PATHS))
        pCurrChar->SetTaxiCheater(true);

    if(pCurrChar->isGameMaster())
        SendNotification(LANG_GM_ON);

    std::string IP_str = GetRemoteAddress();
    sLog.outChar("Account: %d (IP: %s) Login Character:[%s] (guid:%u)",
        GetAccountId(),IP_str.c_str(),pCurrChar->GetName() ,pCurrChar->GetGUIDLow());

    m_playerLoading = false;
    delete holder;
}
Example #22
0
//show info of player
bool ChatHandler::HandlePInfoCommand(const char* args)
{
    Player* target;
    uint64 target_guid;
    std::string target_name;
    if (!extractPlayerTarget((char*)args,&target,&target_guid,&target_name))
        return false;

    uint32 accId = 0;
    uint32 money = 0;
    uint32 total_player_time = 0;
    uint8 level = 0;
    uint32 latency = 0;
    uint8 race;
    uint8 Class;

    // get additional information from Player object
    if (target)
    {
        // check online security
        if (HasLowerSecurity(target, 0))
            return false;

        accId = target->GetSession()->GetAccountId();
        money = target->GetMoney();
        total_player_time = target->GetTotalPlayedTime();
        level = target->getLevel();
        latency = target->GetSession()->GetLatency();
        race = target->getRace();
        Class = target->getClass();
    }
    // get additional information from DB
    else
    {
        // check offline security
        if (HasLowerSecurity(NULL, target_guid))
            return false;

        //                                                     0          1      2      3        4     5
        QueryResult result = CharacterDatabase.PQuery("SELECT totaltime, level, money, account, race, class FROM characters WHERE guid = '%u'", GUID_LOPART(target_guid));
        if (!result)
            return false;

        Field *fields = result->Fetch();
        total_player_time = fields[0].GetUInt32();
        level = fields[1].GetUInt32();
        money = fields[2].GetUInt32();
        accId = fields[3].GetUInt32();
        race = fields[4].GetUInt8();
        Class = fields[5].GetUInt8();
    }

    std::string username = GetTrinityString(LANG_ERROR);
    std::string email = GetTrinityString(LANG_ERROR);
    std::string last_ip = GetTrinityString(LANG_ERROR);
    uint32 security = 0;
    std::string last_login = GetTrinityString(LANG_ERROR);

    QueryResult result = LoginDatabase.PQuery("SELECT a.username,aa.gmlevel,a.email,a.last_ip,a.last_login "
                         "FROM account a "
                         "LEFT JOIN account_access aa "
                         "ON (a.id = aa.id) "
                         "WHERE a.id = '%u'",accId);
    if (result)
    {
        Field* fields = result->Fetch();
        username = fields[0].GetString();
        security = fields[1].GetUInt32();
        email = fields[2].GetString();

        if (email.empty())
            email = "-";

        if (!m_session || m_session->GetSecurity() >= AccountTypes(security))
        {
            last_ip = fields[3].GetString();
            last_login = fields[4].GetString();
        }
        else
        {
            last_ip = "-";
            last_login = "******";
        }
    }

    std::string nameLink = playerLink(target_name);

    PSendSysMessage(LANG_PINFO_ACCOUNT, (target?"":GetTrinityString(LANG_OFFLINE)), nameLink.c_str(), GUID_LOPART(target_guid), username.c_str(), accId, email.c_str(), security, last_ip.c_str(), last_login.c_str(), latency);

    std::string race_s, Class_s;
    switch(race)
    {
    case RACE_HUMAN:
        race_s = "Human";
        break;
    case RACE_ORC:
        race_s = "Orc";
        break;
    case RACE_DWARF:
        race_s = "Dwarf";
        break;
    case RACE_NIGHTELF:
        race_s = "Night Elf";
        break;
    case RACE_UNDEAD_PLAYER:
        race_s = "Undead";
        break;
    case RACE_TAUREN:
        race_s = "Tauren";
        break;
    case RACE_GNOME:
        race_s = "Gnome";
        break;
    case RACE_TROLL:
        race_s = "Troll";
        break;
    case RACE_BLOODELF:
        race_s = "Blood Elf";
        break;
    case RACE_DRAENEI:
        race_s = "Draenei";
        break;
    }
    switch(Class)
    {
    case CLASS_WARRIOR:
        Class_s = "Warrior";
        break;
    case CLASS_PALADIN:
        Class_s = "Paladin";
        break;
    case CLASS_HUNTER:
        Class_s = "Hunter";
        break;
    case CLASS_ROGUE:
        Class_s = "Rogue";
        break;
    case CLASS_PRIEST:
        Class_s = "Priest";
        break;
    case CLASS_DEATH_KNIGHT:
        Class_s = "Death Knight";
        break;
    case CLASS_SHAMAN:
        Class_s = "Shaman";
        break;
    case CLASS_MAGE:
        Class_s = "Mage";
        break;
    case CLASS_WARLOCK:
        Class_s = "Warlock";
        break;
    case CLASS_DRUID:
        Class_s = "Druid";
        break;
    }

    std::string timeStr = secsToTimeString(total_player_time,true,true);
    uint32 gold = money /GOLD;
    uint32 silv = (money % GOLD) / SILVER;
    uint32 copp = (money % GOLD) % SILVER;
    PSendSysMessage(LANG_PINFO_LEVEL, race_s.c_str(), Class_s.c_str(), timeStr.c_str(), level, gold, silv, copp);

    return true;
}
void WorldSession::HandlePlayerLogin(LoginQueryHolder * holder)
{
    uint64 playerGuid = holder->GetGuid();

    Player* pCurrChar = new Player(this);
     // for send server info and strings (config)
    ChatHandler chH = ChatHandler(pCurrChar);

    // "GetAccountId() == db stored account id" checked in LoadFromDB (prevent login not own character using cheating tools)
    if (!pCurrChar->LoadFromDB(GUID_LOPART(playerGuid), holder))
    {
        KickPlayer();                                       // disconnect client, player no set to session and it will not deleted or saved at kick
        delete pCurrChar;                                   // delete it manually
        delete holder;                                      // delete all unprocessed queries
        m_playerLoading = false;
        return;
    }

    pCurrChar->GetMotionMaster()->Initialize();

    SetPlayer(pCurrChar);

    pCurrChar->SendDungeonDifficulty(false);

    WorldPacket data(SMSG_LOGIN_VERIFY_WORLD, 20);
    data << pCurrChar->GetMapId();
    data << pCurrChar->GetPositionX();
    data << pCurrChar->GetPositionY();
    data << pCurrChar->GetPositionZ();
    data << pCurrChar->GetOrientation();
    SendPacket(&data);

    data.Initialize(SMSG_ACCOUNT_DATA_TIMES, 128);
    for (int i = 0; i < 32; i++)
        data << uint32(0);
    SendPacket(&data);

    data.Initialize(SMSG_FEATURE_SYSTEM_STATUS, 2);         // added in 2.2.0
    data << uint8(2);                                       // unknown value
    data << uint8(0);                                       // enable(1)/disable(0) voice chat interface in client
    SendPacket(&data);

    // Send MOTD
    {
        data.Initialize(SMSG_MOTD, 50);                     // new in 2.0.1
        data << (uint32)0;

        uint32 linecount=0;
        std::string str_motd = sWorld.GetMotd();
        std::string::size_type pos, nextpos;

        pos = 0;
        while ((nextpos= str_motd.find('@',pos)) != std::string::npos)
        {
            if (nextpos != pos)
            {
                data << str_motd.substr(pos,nextpos-pos);
                ++linecount;
            }
            pos = nextpos+1;
        }

        if (pos<str_motd.length())
        {
            data << str_motd.substr(pos);
            ++linecount;
        }

        data.put(0, linecount);

        SendPacket(&data);
        DEBUG_LOG("WORLD: Sent motd (SMSG_MOTD)");

        // send server info
        if (sWorld.getConfig(CONFIG_ENABLE_SINFO_LOGIN) == 1)
            chH.PSendSysMessage(_FULLVERSION);

        DEBUG_LOG("WORLD: Sent server info");
    }

    QueryResult_AutoPtr resultGuild = holder->GetResult(PLAYER_LOGIN_QUERY_LOADGUILD);

    if (resultGuild)
    {
        Field *fields = resultGuild->Fetch();
        pCurrChar->SetInGuild(fields[0].GetUInt32());
        pCurrChar->SetRank(fields[1].GetUInt32());
    }
    else if (pCurrChar->GetGuildId())                        // clear guild related fields in case wrong data about non existed membership
    {
        pCurrChar->SetInGuild(0);
        pCurrChar->SetRank(0);
    }

    if (pCurrChar->GetGuildId() != 0)
    {
        Guild* guild = objmgr.GetGuildById(pCurrChar->GetGuildId());
        if (guild)
        {
            data.Initialize(SMSG_GUILD_EVENT, (1+1+guild->GetMOTD().size()+1));
            data << uint8(GE_MOTD);
            data << uint8(1);
            data << guild->GetMOTD();
            SendPacket(&data);
            DEBUG_LOG("WORLD: Sent guild-motd (SMSG_GUILD_EVENT)");

            data.Initialize(SMSG_GUILD_EVENT, (5+10));      // we guess size
            data<<(uint8)GE_SIGNED_ON;
            data<<(uint8)1;
            data<<pCurrChar->GetName();
            data<<pCurrChar->GetGUID();
            guild->BroadcastPacket(&data);
            DEBUG_LOG("WORLD: Sent guild-signed-on (SMSG_GUILD_EVENT)");

            // Increment online members of the guild
            guild->IncOnlineMemberCount();
        }
        else
        {
            // remove wrong guild data
            sLog.outError("Player %s (GUID: %u) marked as member of invalid guild (id: %u), removing guild membership for player.",pCurrChar->GetName(),pCurrChar->GetGUIDLow(),pCurrChar->GetGuildId());
            pCurrChar->SetInGuild(0);
        }
    }

    if (!pCurrChar->isAlive())
        pCurrChar->SendCorpseReclaimDelay(true);

    pCurrChar->SendInitialPacketsBeforeAddToMap();

    //Show cinematic at the first time that player login
    if (!pCurrChar->getCinematic())
    {
        pCurrChar->setCinematic(1);

        if (ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(pCurrChar->getRace()))
        {
            pCurrChar->SendCinematicStart(rEntry->CinematicSequence);

            // send new char string if not empty
            if (!sWorld.GetNewCharString().empty())
                chH.PSendSysMessage("%s", sWorld.GetNewCharString().c_str());
        }
    }

    if (!pCurrChar->GetMap()->Add(pCurrChar))
    {
        // normal delayed teleport protection not applied (and this correct) for this case (Player object just created)
        AreaTrigger const* at = objmgr.GetGoBackTrigger(pCurrChar->GetMapId());
        if (at)
            pCurrChar->TeleportTo(at->target_mapId, at->target_X, at->target_Y, at->target_Z, pCurrChar->GetOrientation());
        else
            pCurrChar->TeleportToHomebind();
    }

    ObjectAccessor::Instance().AddObject(pCurrChar);
    //sLog.outDebug("Player %s added to Map.",pCurrChar->GetName());
    pCurrChar->GetSocial()->SendSocialList();

    pCurrChar->SendInitialPacketsAfterAddToMap();

    CharacterDatabase.PExecute("UPDATE characters SET online = 1 WHERE guid = '%u'", pCurrChar->GetGUIDLow());
    //LoginDatabase.PExecute("UPDATE account SET active_realm_id = %d WHERE id = '%u'", realmID, GetAccountId());
    pCurrChar->SetInGameTime(getMSTime());

    // announce group about member online (must be after add to player list to receive announce to self)
    if (Group *group = pCurrChar->GetGroup())
        group->SendUpdate();

    // friend status
    sSocialMgr.SendFriendStatus(pCurrChar, FRIEND_ONLINE, pCurrChar->GetGUIDLow(), true);

    // Place character in world (and load zone) before some object loading
    pCurrChar->LoadCorpse();

    // setting Ghost+speed if dead
    if (pCurrChar->m_deathState != ALIVE)
    {
        // not blizz like, we must correctly save and load player instead...
        if (pCurrChar->getRace() == RACE_NIGHTELF)
        {
            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)
        }
        
            pCurrChar->CastSpell(pCurrChar, 8326, true, 0);     // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
            pCurrChar->SetMovement(MOVE_WATER_WALK);
    }

    pCurrChar->ContinueTaxiFlight();

    // Load pet if any and player is alive and not in taxi flight
    if (pCurrChar->isAlive() && pCurrChar->m_taxi.GetTaxiSource() == 0)
        pCurrChar->LoadPet();

    // Set FFA PvP for non GM in non-rest mode
    if (sWorld.IsFFAPvPRealm() && !pCurrChar->isGameMaster() && !pCurrChar->HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_RESTING))
        pCurrChar->SetFFAPvP(true);

    if (pCurrChar->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP))
        pCurrChar->SetContestedPvP();

    // Apply at_login requests
    if (pCurrChar->HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
    {
        pCurrChar->resetSpells();
        SendNotification(LANG_RESET_SPELLS);
    }

    if (pCurrChar->HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
    {
        pCurrChar->resetTalents(true);
        SendNotification(LANG_RESET_TALENTS);
    }

    // show time before shutdown if shutdown planned.
    if (sWorld.IsShutdowning())
        sWorld.ShutdownMsg(true,pCurrChar);

    // ImpConfig - Max weapon skill when logging in
    if (sWorld.getConfig(CONFIG_ALWAYS_MAXSKILL))
        pCurrChar->UpdateSkillsToMaxSkillsForLevel();

    if (sWorld.getConfig(CONFIG_ALL_TAXI_PATHS))
        pCurrChar->SetTaxiCheater(true);

    //Reputations if "StartAllReputation" is enabled
    if (sWorld.getConfig(CONFIG_START_ALL_REP))
    {
        pCurrChar->SetFactionReputation(sFactionStore.LookupEntry(942),42999);
        pCurrChar->SetFactionReputation(sFactionStore.LookupEntry(935),42999);
        pCurrChar->SetFactionReputation(sFactionStore.LookupEntry(936),42999);
        pCurrChar->SetFactionReputation(sFactionStore.LookupEntry(1011),42999);
        pCurrChar->SetFactionReputation(sFactionStore.LookupEntry(970),42999);
        pCurrChar->SetFactionReputation(sFactionStore.LookupEntry(967),42999);
        pCurrChar->SetFactionReputation(sFactionStore.LookupEntry(989),42999);
        pCurrChar->SetFactionReputation(sFactionStore.LookupEntry(932),42999);
        pCurrChar->SetFactionReputation(sFactionStore.LookupEntry(934),42999);
        pCurrChar->SetFactionReputation(sFactionStore.LookupEntry(1038),42999);
        pCurrChar->SetFactionReputation(sFactionStore.LookupEntry(1077),42999);
        pCurrChar->SetFactionReputation(sFactionStore.LookupEntry(990),42999);

        // Factions depending on team, like cities and some more stuff
        switch(pCurrChar->GetTeam())
        {
        case ALLIANCE:
            pCurrChar->SetFactionReputation(sFactionStore.LookupEntry(72),42999);
            pCurrChar->SetFactionReputation(sFactionStore.LookupEntry(47),42999);
            pCurrChar->SetFactionReputation(sFactionStore.LookupEntry(69),42999);
            pCurrChar->SetFactionReputation(sFactionStore.LookupEntry(930),42999);
            pCurrChar->SetFactionReputation(sFactionStore.LookupEntry(730),42999);
            pCurrChar->SetFactionReputation(sFactionStore.LookupEntry(978),42999);
            pCurrChar->SetFactionReputation(sFactionStore.LookupEntry(54),42999);
            pCurrChar->SetFactionReputation(sFactionStore.LookupEntry(946),42999);
            break;
        case HORDE:
            pCurrChar->SetFactionReputation(sFactionStore.LookupEntry(76),42999);
            pCurrChar->SetFactionReputation(sFactionStore.LookupEntry(68),42999);
            pCurrChar->SetFactionReputation(sFactionStore.LookupEntry(81),42999);
            pCurrChar->SetFactionReputation(sFactionStore.LookupEntry(911),42999);
            pCurrChar->SetFactionReputation(sFactionStore.LookupEntry(729),42999);
            pCurrChar->SetFactionReputation(sFactionStore.LookupEntry(941),42999);
            pCurrChar->SetFactionReputation(sFactionStore.LookupEntry(530),42999);
            pCurrChar->SetFactionReputation(sFactionStore.LookupEntry(947),42999);
            break;
        default:
                break;
        }
    }

    if (pCurrChar->isGameMaster())
        SendNotification(LANG_GM_ON);

    std::string IP_str = GetRemoteAddress();
    sLog.outChar("Account: %d (IP: %s) Login Character:[%s] (guid: %u)",
        GetAccountId(), IP_str.c_str(), pCurrChar->GetName(), pCurrChar->GetGUIDLow());

    m_playerLoading = false;

    //Hook for OnLogin Event
    sScriptMgr.OnLogin(pCurrChar);

    delete holder;
}
Example #24
0
//show info of player
bool ChatHandler::HandlePInfoCommand(const char* args)
{
    Player* target;
    uint64 target_guid;
    std::string target_name;

    uint32 parseGUID = MAKE_NEW_GUID(atol((char*)args), 0, HIGHGUID_PLAYER);

    if (sObjectMgr->GetPlayerNameByGUID(parseGUID, target_name))
    {
        target = sObjectMgr->GetPlayerByLowGUID(parseGUID);
        target_guid = parseGUID;
    }
    else if (!extractPlayerTarget((char*)args, &target, &target_guid, &target_name))
        return false;

    uint32 accId = 0;
    uint32 money = 0;
    uint32 total_player_time = 0;
    uint8 level = 0;
    uint32 latency = 0;
    uint8 race;
    uint8 Class;
    int64 muteTime = 0;
    int64 banTime = -1;
    uint32 mapId;
    uint32 areaId;
    uint32 phase = 0;


    // get additional information from Player object
    if (target)
    {
        // check online security
        if (HasLowerSecurity(target, 0))
            return false;

        accId = target->GetSession()->GetAccountId();
        money = target->GetMoney();
        total_player_time = target->GetTotalPlayedTime();
        level = target->getLevel();
        latency = target->GetSession()->GetLatency();
        race = target->getRace();
        Class = target->getClass();
        muteTime = target->GetSession()->m_muteTime;
        mapId = target->GetMapId();
        areaId = target->GetAreaId();
        phase = target->GetPhaseMask();
    }
    // get additional information from DB
    else
    {
        // check offline security
        if (HasLowerSecurity(NULL, target_guid))
            return false;

        //                                                     0          1      2      3        4     5      6    7
        QueryResult result = CharacterDatabase.PQuery("SELECT totaltime, level, money, account, race, class, map, zone FROM characters "
                                                      "WHERE guid = '%u'", GUID_LOPART(target_guid));
        if (!result)
            return false;

        Field *fields = result->Fetch();
        total_player_time = fields[0].GetUInt32();
        level = fields[1].GetUInt32();
        money = fields[2].GetUInt32();
        accId = fields[3].GetUInt32();
        race = fields[4].GetUInt8();
        Class = fields[5].GetUInt8();
        mapId = fields[6].GetUInt16();
        areaId = fields[7].GetUInt16();
    }

    std::string username = GetTrilliumString(LANG_ERROR);
    std::string email = GetTrilliumString(LANG_ERROR);
    std::string last_ip = GetTrilliumString(LANG_ERROR);
    uint32 security = 0;
    std::string last_login = GetTrilliumString(LANG_ERROR);

    QueryResult result = LoginDatabase.PQuery("SELECT a.username, aa.gmlevel, a.email, a.last_ip, a.last_login, a.mutetime "
                                                "FROM account a "
                                                "LEFT JOIN account_access aa "
                                                "ON (a.id = aa.id) "
                                                "WHERE a.id = '%u'", accId);
    if (result)
    {
        Field* fields = result->Fetch();
        username = fields[0].GetString();
        security = fields[1].GetUInt32();
        email = fields[2].GetString();
        muteTime = fields[5].GetUInt64();

        if (email.empty())
            email = "-";

        if (!m_session || m_session->GetSecurity() >= AccountTypes(security))
        {
            last_ip = fields[3].GetString();
            last_login = fields[4].GetString();
        }
        else
        {
            last_ip = "-";
            last_login = "******";
        }
    }

    std::string nameLink = playerLink(target_name);

    PSendSysMessage(LANG_PINFO_ACCOUNT, (target?"":GetTrilliumString(LANG_OFFLINE)), nameLink.c_str(), GUID_LOPART(target_guid), username.c_str(), accId, email.c_str(), security, last_ip.c_str(), last_login.c_str(), latency);

    std::string bannedby = "unknown";
    std::string banreason = "";
    if (QueryResult result = LoginDatabase.PQuery("SELECT unbandate, bandate = unbandate, bannedby, banreason FROM account_banned "
                                                  "WHERE id = '%u' AND active ORDER BY bandate ASC LIMIT 1", accId))
    {
        Field * fields = result->Fetch();
        banTime = fields[1].GetBool() ? 0 : fields[0].GetUInt64();
        bannedby = fields[2].GetString();
        banreason = fields[3].GetString();
    }
    else if (QueryResult result = CharacterDatabase.PQuery("SELECT unbandate, bandate = unbandate, bannedby, banreason FROM character_banned "
                                                           "WHERE guid = '%u' AND active ORDER BY bandate ASC LIMIT 1", GUID_LOPART(target_guid)))
    {
        Field * fields = result->Fetch();
        banTime = fields[1].GetBool() ? 0 : fields[0].GetUInt64();
        bannedby = fields[2].GetString();
        banreason = fields[3].GetString();
    }

    if (muteTime > 0)
        PSendSysMessage(LANG_PINFO_MUTE, secsToTimeString(muteTime - time(NULL), true).c_str());

    if (banTime >= 0)
        PSendSysMessage(LANG_PINFO_BAN, banTime > 0 ? secsToTimeString(banTime - time(NULL), true).c_str() : "permanently", bannedby.c_str(), banreason.c_str());

    std::string race_s, Class_s;
    switch(race)
    {
        case RACE_HUMAN:            race_s = "Human";       break;
        case RACE_ORC:              race_s = "Orc";         break;
        case RACE_DWARF:            race_s = "Dwarf";       break;
        case RACE_NIGHTELF:         race_s = "Night Elf";   break;
        case RACE_UNDEAD_PLAYER:    race_s = "Undead";      break;
        case RACE_TAUREN:           race_s = "Tauren";      break;
        case RACE_GNOME:            race_s = "Gnome";       break;
        case RACE_TROLL:            race_s = "Troll";       break;
        case RACE_BLOODELF:         race_s = "Blood Elf";   break;
        case RACE_DRAENEI:          race_s = "Draenei";     break;
    }
    switch(Class)
    {
        case CLASS_WARRIOR:         Class_s = "Warrior";        break;
        case CLASS_PALADIN:         Class_s = "Paladin";        break;
        case CLASS_HUNTER:          Class_s = "Hunter";         break;
        case CLASS_ROGUE:           Class_s = "Rogue";          break;
        case CLASS_PRIEST:          Class_s = "Priest";         break;
        case CLASS_DEATH_KNIGHT:    Class_s = "Death Knight";   break;
        case CLASS_SHAMAN:          Class_s = "Shaman";         break;
        case CLASS_MAGE:            Class_s = "Mage";           break;
        case CLASS_WARLOCK:         Class_s = "Warlock";        break;
        case CLASS_DRUID:           Class_s = "Druid";          break;
    }

    std::string timeStr = secsToTimeString(total_player_time, true, true);
    uint32 gold = money /GOLD;
    uint32 silv = (money % GOLD) / SILVER;
    uint32 copp = (money % GOLD) % SILVER;
    PSendSysMessage(LANG_PINFO_LEVEL, race_s.c_str(), Class_s.c_str(), timeStr.c_str(), level, gold, silv, copp);

    // Add map, zone, subzone and phase to output
    int locale = GetSessionDbcLocale();
    std::string areaName = "<unknown>";
    std::string zoneName = "";

    MapEntry const* map = sMapStore.LookupEntry(mapId);

    AreaTableEntry const* area = GetAreaEntryByAreaID(areaId);
    if (area)
    {
        areaName = area->area_name[locale];

        AreaTableEntry const* zone = GetAreaEntryByAreaID(area->zone);

        if (zone)
            zoneName = zone->area_name[locale];
    }

    if (target)
    {
        if (!zoneName.empty())
            PSendSysMessage(LANG_PINFO_MAP_ONLINE, map->name[locale], zoneName.c_str(), areaName.c_str(), phase);
        else
            PSendSysMessage(LANG_PINFO_MAP_ONLINE, map->name[locale], areaName.c_str(), "<unknown>", phase);
    }
    else
        PSendSysMessage(LANG_PINFO_MAP_OFFLINE, map->name[locale], areaName.c_str());

    return true;
}
Example #25
0
void WorldSession::HandleCharCreateOpcode( WorldPacket & recv_data )
{
	CHECK_PACKET_SIZE(recv_data, 10);
	std::string name;
	uint8 race, class_;

	recv_data >> name >> race >> class_;
	recv_data.rpos(0);

	if(!sWorld.VerifyName(name.c_str(), name.length()))
	{
		OutPacket(SMSG_CHAR_CREATE, 1, "\x32");
		return;
	}

	if(g_characterNameFilter->Parse(name, false))
	{
		OutPacket(SMSG_CHAR_CREATE, 1, "\x32");
		return;
	}

	//reserved for console whisper
	if(name == "Console" ||  name == "console")
	{
		OutPacket(SMSG_CHAR_CREATE, 1, "\x32");
		return;
	}

	if(objmgr.GetPlayerInfoByName(name.c_str()) != 0)
	{
		OutPacket(SMSG_CHAR_CREATE, 1, "\x32");
		return;
	}

	if(!sHookInterface.OnNewCharacter(race, class_, this, name.c_str()))
	{
		OutPacket(SMSG_CHAR_CREATE, 1, "\x32");
		return;
	}

	if( class_ == DEATHKNIGHT && (!HasFlag(ACCOUNT_FLAG_XPACK_02) || !CanCreateDeathKnight() ) )
	{
		OutPacket(SMSG_CHAR_CREATE, 1, "\x3B");
		return;
	}

	QueryResult * result = CharacterDatabase.Query("SELECT COUNT(*) FROM banned_names WHERE name = '%s'", CharacterDatabase.EscapeString(name).c_str());
	if(result)
	{
		if(result->Fetch()[0].GetUInt32() > 0)
		{
			// That name is banned!
			OutPacket(SMSG_CHAR_CREATE, 1, "\x51"); // You cannot use that name
			delete result;
			return;
		}
		delete result;
	}
	// loading characters

	//checking number of chars is useless since client will not allow to create more than 10 chars
	//as the 'create' button will not appear (unless we want to decrease maximum number of characters)

	Player* pNewChar = objmgr.CreatePlayer();
	pNewChar->SetSession(this);
	if(!pNewChar->Create( recv_data ))
	{
		// failed.
		pNewChar->ok_to_remove = true;
		pNewChar->Destructor();
		return;
	}

	//Same Faction limitation only applies to PVP and RPPVP realms, after 3.1.0 the Blizzard is disable this function, so actually we are disable this.
	/*uint32 realmType = sLogonCommHandler.GetRealmType();
	if(!HasGMPermissions() && (realmType == REALMTYPE_PVP || realmType == REALMTYPE_RPPVP) && _side >= 0)
	{
		if( ((pNewChar->GetTeam() == 0) && (_side == 1)) || ((pNewChar->GetTeam() == 1) && (_side == 0)) )
		{
			pNewChar->ok_to_remove = true;
			pNewChar->Destructor();
			WorldPacket data(1);
			data.SetOpcode(SMSG_CHAR_CREATE);
			data << (uint8)ALL_CHARS_ON_PVP_REALM_MUST_AT_SAME_SIDE+1;
			SendPacket( &data );
			return;
		}
	}*/
	pNewChar->UnSetBanned();
	pNewChar->addSpell(22027);	  // Remove Insignia

	if(pNewChar->getClass() == WARLOCK)
	{
		pNewChar->AddSummonSpell(416, 3110);		// imp fireball
		pNewChar->AddSummonSpell(417, 19505);
		pNewChar->AddSummonSpell(1860, 3716);
		pNewChar->AddSummonSpell(1863, 7814);
	}

	pNewChar->SaveToDB(true);

	PlayerInfo *pn=new PlayerInfo;
	memset(pn, 0, sizeof(PlayerInfo));
	pn->guid = pNewChar->GetLowGUID();
	pn->name = strdup(pNewChar->GetName());
	pn->cl = pNewChar->getClass();
	pn->race = pNewChar->getRace();
	pn->gender = pNewChar->getGender();
	pn->lastLevel = pNewChar->getLevel();
	pn->lastZone = pNewChar->GetZoneId();
	pn->lastOnline = UNIXTIME;
	pn->team = pNewChar->GetTeam();
	pn->acct = GetAccountId();
#ifdef VOICE_CHAT
	pn->groupVoiceId = -1;
#endif
	objmgr.AddPlayerInfo(pn);

	pNewChar->ok_to_remove = true;
	pNewChar->Destructor();

	// CHAR_CREATE_SUCCESS
	OutPacket(SMSG_CHAR_CREATE, 1, "\x2F");

	sLogonCommHandler.UpdateAccountCount(GetAccountId(), 1);
	m_lastEnumTime = 0;
}
Example #26
0
void WorldSession::HandlePlayerLogin(LoginQueryHolder* holder)
{
    ObjectGuid playerGuid = holder->GetGuid();

    Player* pCurrChar = new Player(this);
    pCurrChar->GetMotionMaster()->Initialize();

    // "GetAccountId()==db stored account id" checked in LoadFromDB (prevent login not own character using cheating tools)
    if (!pCurrChar->LoadFromDB(playerGuid, holder))
    {
        KickPlayer();                                       // disconnect client, player no set to session and it will not deleted or saved at kick
        delete pCurrChar;                                   // delete it manually
        delete holder;                                      // delete all unprocessed queries
        m_playerLoading = false;
        return;
    }

    SetPlayer(pCurrChar);

    pCurrChar->SendDungeonDifficulty(false);

    WorldPacket data(SMSG_LOGIN_VERIFY_WORLD, 20);
    data << pCurrChar->GetMapId();
    data << pCurrChar->GetPositionX();
    data << pCurrChar->GetPositionY();
    data << pCurrChar->GetPositionZ();
    data << pCurrChar->GetOrientation();
    SendPacket(&data);

    data.Initialize(SMSG_ACCOUNT_DATA_TIMES, 128);
    for (int i = 0; i < 32; ++i)
        data << uint32(0);
    SendPacket(&data);

    data.Initialize(SMSG_FEATURE_SYSTEM_STATUS, 2);         // added in 2.2.0
    data << uint8(2);                                       // unknown value
    data << uint8(0);                                       // enable(1)/disable(0) voice chat interface in client
    SendPacket(&data);

    // Send MOTD
    {
        data.Initialize(SMSG_MOTD, 50);                     // new in 2.0.1
        data << (uint32)0;

        uint32 linecount = 0;
        std::string str_motd = sWorld.GetMotd();
        std::string::size_type pos, nextpos;

        pos = 0;
        while ((nextpos = str_motd.find('@', pos)) != std::string::npos)
        {
            if (nextpos != pos)
            {
                data << str_motd.substr(pos, nextpos - pos);
                ++linecount;
            }
            pos = nextpos + 1;
        }

        if (pos < str_motd.length())
        {
            data << str_motd.substr(pos);
            ++linecount;
        }

        data.put(0, linecount);

        SendPacket(&data);
        DEBUG_LOG("WORLD: Sent motd (SMSG_MOTD)");
    }

    // QueryResult *result = CharacterDatabase.PQuery("SELECT guildid,rank FROM guild_member WHERE guid = '%u'",pCurrChar->GetGUIDLow());
    QueryResult* resultGuild = holder->GetResult(PLAYER_LOGIN_QUERY_LOADGUILD);

    if (resultGuild)
    {
        Field* fields = resultGuild->Fetch();
        pCurrChar->SetInGuild(fields[0].GetUInt32());
        pCurrChar->SetRank(fields[1].GetUInt32());
        delete resultGuild;
    }
    else if (pCurrChar->GetGuildId())                       // clear guild related fields in case wrong data about nonexistent membership
    {
        pCurrChar->SetInGuild(0);
        pCurrChar->SetRank(0);
    }

    if (pCurrChar->GetGuildId() != 0)
    {
        Guild* guild = sGuildMgr.GetGuildById(pCurrChar->GetGuildId());
        if (guild)
        {
            data.Initialize(SMSG_GUILD_EVENT, (1 + 1 + guild->GetMOTD().size() + 1));
            data << uint8(GE_MOTD);
            data << uint8(1);
            data << guild->GetMOTD();
            SendPacket(&data);
            DEBUG_LOG("WORLD: Sent guild-motd (SMSG_GUILD_EVENT)");

            guild->DisplayGuildBankTabsInfo(this);

            guild->BroadcastEvent(GE_SIGNED_ON, pCurrChar->GetObjectGuid(), pCurrChar->GetName());
        }
        else
        {
            // remove wrong guild data
            sLog.outError("Player %s (GUID: %u) marked as member of nonexistent guild (id: %u), removing guild membership for player.", pCurrChar->GetName(), pCurrChar->GetGUIDLow(), pCurrChar->GetGuildId());
            pCurrChar->SetInGuild(0);
        }
    }

    if (!pCurrChar->isAlive())
        pCurrChar->SendCorpseReclaimDelay(true);

    pCurrChar->SendInitialPacketsBeforeAddToMap();

    // Show cinematic at the first time that player login
    /*if (!pCurrChar->getCinematic())
    {
        pCurrChar->setCinematic(1);

        if (ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(pCurrChar->getRace()))
            pCurrChar->SendCinematicStart(rEntry->CinematicSequence);
    }*/

    uint32 miscRequirement = 0;
    AreaLockStatus lockStatus = AREA_LOCKSTATUS_OK;
    if (AreaTrigger const* at = sObjectMgr.GetMapEntranceTrigger(pCurrChar->GetMapId()))
        lockStatus = pCurrChar->GetAreaTriggerLockStatus(at, miscRequirement);
    else
    {
        // Some basic checks in case of a map without areatrigger
        MapEntry const* mapEntry = sMapStore.LookupEntry(pCurrChar->GetMapId());
        if (!mapEntry)
            lockStatus = AREA_LOCKSTATUS_UNKNOWN_ERROR;
        else if (pCurrChar->GetSession()->Expansion() < mapEntry->Expansion())
            lockStatus = AREA_LOCKSTATUS_INSUFFICIENT_EXPANSION;
    }
    if (lockStatus != AREA_LOCKSTATUS_OK || !pCurrChar->GetMap()->Add(pCurrChar))
    {
        // normal delayed teleport protection not applied (and this correct) for this case (Player object just created)
        AreaTrigger const* at = sObjectMgr.GetGoBackTrigger(pCurrChar->GetMapId());
        if (at)
            lockStatus = pCurrChar->GetAreaTriggerLockStatus(at, miscRequirement);
        if (!at || lockStatus != AREA_LOCKSTATUS_OK || !pCurrChar->TeleportTo(at->target_mapId, at->target_X, at->target_Y, at->target_Z, pCurrChar->GetOrientation()))
            pCurrChar->TeleportToHomebind();
    }

    sObjectAccessor.AddObject(pCurrChar);
    // DEBUG_LOG("Player %s added to Map.",pCurrChar->GetName());
    pCurrChar->GetSocial()->SendSocialList();

    pCurrChar->SendInitialPacketsAfterAddToMap();

    static SqlStatementID updChars;
    static SqlStatementID updAccount;

    SqlStatement stmt = CharacterDatabase.CreateStatement(updChars, "UPDATE characters SET online = 1 WHERE guid = ?");
    stmt.PExecute(pCurrChar->GetGUIDLow());

    stmt = LoginDatabase.CreateStatement(updAccount, "UPDATE account SET active_realm_id = ? WHERE id = ?");
    stmt.PExecute(realmID, GetAccountId());

    pCurrChar->SetInGameTime(WorldTimer::getMSTime());

    // announce group about member online (must be after add to player list to receive announce to self)
    if (Group* group = pCurrChar->GetGroup())
        group->SendUpdate();

    // friend status
    sSocialMgr.SendFriendStatus(pCurrChar, FRIEND_ONLINE, pCurrChar->GetObjectGuid(), true);

    // Place character in world (and load zone) before some object loading
    pCurrChar->LoadCorpse();

    // setting Ghost+speed if dead
    if (pCurrChar->m_deathState != ALIVE)
    {
        // not blizz like, we must correctly save and load player instead...
        if (pCurrChar->getRace() == RACE_NIGHTELF)
            pCurrChar->CastSpell(pCurrChar, 20584, true);   // 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)
        pCurrChar->CastSpell(pCurrChar, 8326, true);        // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)

        pCurrChar->SetWaterWalk(true);
    }

    pCurrChar->ContinueTaxiFlight();

    // Load pet if any (if player not alive and in taxi flight or another then pet will remember as temporary unsummoned)
    pCurrChar->LoadPet();

    // Set FFA PvP for non GM in non-rest mode
    if (sWorld.IsFFAPvPRealm() && !pCurrChar->isGameMaster() && !pCurrChar->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
        pCurrChar->SetFFAPvP(true);

    if (pCurrChar->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP))
        pCurrChar->SetContestedPvP();

    // Apply at_login requests
    if (pCurrChar->HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
    {
        pCurrChar->resetSpells();
        SendNotification(LANG_RESET_SPELLS);
    }

    if (pCurrChar->HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
    {
        pCurrChar->resetTalents(true);
        SendNotification(LANG_RESET_TALENTS);               // we can use SMSG_TALENTS_INVOLUNTARILY_RESET here
    }

    if (pCurrChar->HasAtLoginFlag(AT_LOGIN_FIRST))
        pCurrChar->RemoveAtLoginFlag(AT_LOGIN_FIRST);

    // show time before shutdown if shutdown planned.
    if (sWorld.IsShutdowning())
        sWorld.ShutdownMsg(true, pCurrChar);

    if (sWorld.getConfig(CONFIG_BOOL_ALL_TAXI_PATHS))
        pCurrChar->SetTaxiCheater(true);

    if (pCurrChar->isGameMaster())
        SendNotification(LANG_GM_ON);

    if (!pCurrChar->isGMVisible())
    {
        SendNotification(LANG_INVISIBLE_INVISIBLE);
        SpellEntry const* invisibleAuraInfo = sSpellStore.LookupEntry(sWorld.getConfig(CONFIG_UINT32_GM_INVISIBLE_AURA));
        if (invisibleAuraInfo && IsSpellAppliesAura(invisibleAuraInfo))
            pCurrChar->CastSpell(pCurrChar, invisibleAuraInfo, true);
    }

    std::string IP_str = GetRemoteAddress();
    sLog.outChar("Account: %d (IP: %s) Login Character:[%s] (guid: %u)",
                 GetAccountId(), IP_str.c_str(), pCurrChar->GetName(), pCurrChar->GetGUIDLow());

    if (!pCurrChar->IsStandState() && !pCurrChar->hasUnitState(UNIT_STAT_STUNNED))
        pCurrChar->SetStandState(UNIT_STAND_STATE_STAND);

    pCurrChar->OnLogin();

    m_playerLoading = false;
    delete holder;
}
Example #27
0
int Player::displayCreature(Creature* target)  {
    int     percent=0, align=0, rank=0, chance=0, flags = displayFlags();
    Player  *pTarget = target->getAsPlayer();
    Monster *mTarget = target->getAsMonster();
    std::ostringstream oStr;
    bstring str = "";
    bool space=false;

    if(mTarget) {
        oStr << "You see " << mTarget->getCrtStr(this, flags, 1) << ".\n";
        if(mTarget->getDescription() != "")
            oStr << mTarget->getDescription() << "\n";
        else
            oStr << "There is nothing special about " << mTarget->getCrtStr(this, flags, 0) << ".\n";

        if(mTarget->getMobTrade()) {
            rank = mTarget->getSkillLevel()/10;
            oStr << "^y" << mTarget->getCrtStr(this, flags | CAP, 0) << " is a " << get_trade_string(mTarget->getMobTrade())
                 << ". " << mTarget->upHisHer() << " skill level: " << get_skill_string(rank) << ".^x\n";
        }
    } else if(pTarget) {

        oStr << "You see " << pTarget->fullName() << " the "
             << gConfig->getRace(pTarget->getDisplayRace())->getAdjective();
        // will they see through the illusion?
        if(willIgnoreIllusion() && pTarget->getDisplayRace() != pTarget->getRace())
            oStr << " (" << gConfig->getRace(pTarget->getRace())->getAdjective() << ")";
        oStr << " "
             << pTarget->getTitle() << ".\n";

        if(gConfig->getCalendar()->isBirthday(pTarget)) {
            oStr << "^yToday is " << pTarget->getCName() << "'s birthday! " << pTarget->upHeShe()
                 << " is " << pTarget->getAge() << " years old.^x\n";
        }

        if(pTarget->description != "")
            oStr << pTarget->description << "\n";
    }

    if(target->isEffected("vampirism")) {
        chance = intelligence.getCur()/10 + piety.getCur()/10;
        // vampires and werewolves can sense each other
        if(isEffected("vampirism") || isEffected("lycanthropy"))
            chance = 101;
        if(chance > mrand(0,100)) {
            switch(mrand(1,4)) {
            case 1:
                oStr << target->upHeShe() << " looks awfully pale.\n";
                break;
            case 2:
                oStr << target->upHeShe() << " has an unearthly presence.\n";
                break;
            case 3:
                oStr << target->upHeShe() << " has hypnotic eyes.\n";
                break;
            default:
                oStr << target->upHeShe() << " looks rather pale.\n";
            }
        }
    }

    if(target->isEffected("lycanthropy")) {
        chance = intelligence.getCur()/10 + piety.getCur()/10;
        // vampires and werewolves can sense each other
        if(isEffected("vampirism") || isEffected("lycanthropy"))
            chance = 101;
        if(chance > mrand(0,100)) {
            switch(mrand(1,3)) {
            case 1:
                oStr << target->upHeShe() << " looks awfully shaggy.\n";
                break;
            case 2:
                oStr << target->upHeShe() << " has a feral presence.\n";
                break;
            default:
                oStr << target->upHeShe() << " looks rather shaggy.\n";
            }
        }
    }

    if(target->isEffected("slow"))
        oStr << target->upHeShe() << " is moving very slowly.\n";
    else if(target->isEffected("haste"))
        oStr << target->upHeShe() << " is moving unnaturally quick.\n";


    if((cClass == CreatureClass::CLERIC && deity == JAKAR && level >=7) || isCt())
        oStr << "^y" << target->getCrtStr(this, flags | CAP, 0 ) << " is carrying "
             << target->coins[GOLD] << " gold coin"
             << (target->coins[GOLD] != 1 ? "s" : "") << ".^x\n";

    if(isEffected("know-aura") || cClass==CreatureClass::PALADIN) {
        space = true;
        oStr << target->getCrtStr(this, flags | CAP, 0) << " ";

        align = target->getAdjustedAlignment();

        switch(align) {
        case BLOODRED:
            oStr << "has a blood red aura.";
            break;
        case REDDISH:
            oStr << "has a reddish aura.";
            break;
        case PINKISH:
            oStr << "has a pinkish aura.";
            break;
        case NEUTRAL:
            oStr << "has a grey aura.";
            break;
        case LIGHTBLUE:
            oStr << "has a light blue aura.";
            break;
        case BLUISH:
            oStr << "has a bluish aura.";
            break;
        case ROYALBLUE:
            oStr << "has a royal blue aura.";
            break;
        default:
            oStr << "has a grey aura.";
            break;
        }
    }

    if(mTarget && mTarget->getRace()) {
        if(space)
            oStr << " ";
        space = true;
        oStr << mTarget->upHeShe() << " is ^W"
             << gConfig->getRace(mTarget->getRace())->getAdjective().toLower() << "^x.";
    }
    if(target->getSize() != NO_SIZE) {
        if(space)
            oStr << " ";
        space = true;
        oStr << target->upHeShe() << " is ^W" << getSizeName(target->getSize()) << "^x.";
    }

    if(space)
        oStr << "\n";

    if(target->hp.getCur() > 0 && target->hp.getMax())
        percent = (100 * (target->hp.getCur())) / (target->hp.getMax());
    else
        percent = -1;

    if(!(mTarget && mTarget->flagIsSet(M_UNKILLABLE))) {
        oStr << target->upHeShe();
        if(percent >= 100 || !target->hp.getMax())
            oStr << " is in excellent condition.\n";
        else if(percent >= 90)
            oStr << " has a few scratches.\n";
        else if(percent >= 75)
            oStr << " has some small wounds and bruises.\n";
        else if(percent >= 60)
            oStr << " is wincing in pain.\n";
        else if(percent >= 35)
            oStr << " has quite a few wounds.\n";
        else if(percent >= 20)
            oStr << " has some big nasty wounds and scratches.\n";
        else if(percent >= 10)
            oStr << " is bleeding awfully from big wounds.\n";
        else if(percent >= 5)
            oStr << " is barely clinging to life.\n";
        else if(percent >= 0)
            oStr << " is nearly dead.\n";
    }

    if(pTarget) {
        if(pTarget->isEffected("mist")) {
            oStr << pTarget->upHeShe() << "%s is currently in mist form.\n";
            printColor("%s", oStr.str().c_str());
            return(0);
        }

        if(pTarget->flagIsSet(P_UNCONSCIOUS))
            oStr << pTarget->getName() << " is "
                 << (pTarget->flagIsSet(P_SLEEPING) ? "sleeping" : "unconscious") << ".\n";

        if(pTarget->isEffected("petrification"))
            oStr << pTarget->getName() << " is petrified.\n";

        if(pTarget->isBraindead())
            oStr << pTarget->getName() << "%M is currently brain dead.\n";
    } else {
        if(mTarget->isEnemy(this))
            oStr << mTarget->upHeShe() << " looks very angry at you.\n";
        else if(mTarget->getPrimeFaction() != "")
            oStr << mTarget->upHeShe() << " " << getFactionMessage(mTarget->getPrimeFaction()) << ".\n";

        Creature* firstEnm = nullptr;
        if((firstEnm = mTarget->getTarget(false)) != nullptr) {
            if(firstEnm == this) {
                if(  !mTarget->flagIsSet(M_HIDDEN) &&
                    !(mTarget->isInvisible() && isEffected("detect-invisible")))
                    oStr << mTarget->upHeShe() << " is attacking you.\n";
            } else
                oStr << mTarget->upHeShe() << " is attacking " << firstEnm->getName() << ".\n";

            /// print all the enemies if a CT or DM is looking
            if(isCt())
                oStr << mTarget->threatTable;
        }
        oStr << consider(mTarget);

        // pet code
        if(mTarget->isPet() && mTarget->getMaster() == this) {
            str = mTarget->listObjects(this, true);
            oStr << mTarget->upHeShe() << " ";
            if(str == "")
                oStr << "isn't holding anything.\n";
            else
                oStr << "is carrying: " << str << ".\n";
        }
    }
    printColor("%s", oStr.str().c_str());
    target->printEquipList(this);
    return(0);
}