示例#1
0
bool ChatHandler::HandlePlayerbotCommand(const char* args)
{
    if(!(m_session->GetSecurity() > SEC_PLAYER))
        if(sConfig.GetBoolDefault("PlayerbotAI.DisableBots", false))
        {
            PSendSysMessage("|cffff0000Playerbot system is currently disabled!");
            SetSentErrorMessage(true);
            return false;
        }

    if (! m_session)
    {
        PSendSysMessage("|cffff0000You may only add bots from an active session");
        SetSentErrorMessage(true);
        return false;
    }

    if (!*args)
    {
        PSendSysMessage("|cffff0000usage: add PLAYERNAME  or  remove PLAYERNAME");
        SetSentErrorMessage(true);
        return false;
    }

    char *cmd = strtok ((char*)args, " ");
    char *charname = strtok (NULL, " ");
    if (!cmd || !charname)
    {
        PSendSysMessage("|cffff0000usage: add PLAYERNAME  or  remove PLAYERNAME");
        SetSentErrorMessage(true);
        return false;
    }

    std::string cmdStr = cmd;
    std::string charnameStr = charname;

    if(!normalizePlayerName(charnameStr))
        return false;

    uint64 guid = sObjectMgr.GetPlayerGUIDByName(charnameStr.c_str());
    if (guid == 0 || (guid == m_session->GetPlayer()->GetGUID()))
    {
        SendSysMessage(LANG_PLAYER_NOT_FOUND);
        SetSentErrorMessage(true);
        return false;
    }

    uint32 accountId = sObjectMgr.GetPlayerAccountIdByGUID(guid);
    if (accountId != m_session->GetAccountId())
    {
        PSendSysMessage("|cffff0000You may only add bots from the same account.");
        SetSentErrorMessage(true);
        return false;
    }

    // create the playerbot manager if it doesn't already exist
    PlayerbotMgr* mgr = m_session->GetPlayer()->GetPlayerbotMgr();
    if (!mgr)
    {
        mgr = new PlayerbotMgr(m_session->GetPlayer());
        m_session->GetPlayer()->SetPlayerbotMgr(mgr);
    }

    QueryResult *resultchar = CharacterDatabase.PQuery("SELECT Count(*) FROM characters WHERE online = 1 AND account = '%u'", m_session->GetAccountId());
    if(resultchar)
    {
        Field *fields=resultchar->Fetch();
        int acctcharcount = fields[0].GetUInt32();
        if(!(m_session->GetSecurity() > SEC_PLAYER))
            if((acctcharcount > sConfig.GetIntDefault("PlayerbotAI.MaxNumBots", 9)) && (cmdStr == "add" || cmdStr == "login"))
            {
                PSendSysMessage("|cffff0000You cannot summon anymore bots, for this account.");
                SetSentErrorMessage(true);
                delete resultchar;
                return false;
            }
    }
    delete resultchar;

    QueryResult *resultlvl = CharacterDatabase.PQuery("SELECT level,name FROM characters WHERE guid = '%u'", guid);
    if(resultlvl)
    {
        Field *fields=resultlvl->Fetch();
        int charlvl = fields[0].GetUInt32();
        if(!(m_session->GetSecurity() > SEC_PLAYER))
            if(charlvl > sConfig.GetIntDefault("PlayerbotAI.RestrictBotLevel", 80))
            {
                PSendSysMessage("|cffff0000You cannot summon |cffffffff[%s]|cffff0000, it's level is too high.",fields[1].GetString());
                SetSentErrorMessage(true);
                delete resultlvl;
                return false;
            }
    }
    delete resultlvl;
    // end of gmconfig patch
    if (cmdStr == "add" || cmdStr == "login")
    {
        if (mgr->GetPlayerBot(guid))
        {
            PSendSysMessage("Bot already exists in world.");
            SetSentErrorMessage(true);
            return false;
        }
        CharacterDatabase.DirectPExecute("UPDATE characters SET online = 1 WHERE guid = '%u'", guid);
        mgr->AddPlayerBot(guid);
        PSendSysMessage("Bot added successfully.");
    }
    else if (cmdStr == "remove" || cmdStr == "logout")
    {
        if (! mgr->GetPlayerBot(guid))
        {
            PSendSysMessage("|cffff0000Bot can not be removed because bot does not exist in world.");
            SetSentErrorMessage(true);
            return false;
        }
        CharacterDatabase.DirectPExecute("UPDATE characters SET online = 0 WHERE guid = '%u'", guid);
        mgr->LogoutPlayerBot(guid);
        PSendSysMessage("Bot removed successfully.");
    }
    else if (cmdStr == "co" || cmdStr == "combatorder")
    {
        Unit *target = 0;
        char *orderChar = strtok( NULL, " " );
        if(!orderChar)
        {
            PSendSysMessage("|cffff0000Syntax error:|cffffffff .bot co <botName> <order=reset|tank|assist|heal|protect> [targetPlayer]");
            SetSentErrorMessage(true);
            return false;
        }
        std::string orderStr = orderChar;
        if(orderStr == "protect" || orderStr == "assist")
        {
            char *targetChar = strtok( NULL, " " );
            uint64 targetGUID = m_session->GetPlayer()->GetSelection();
            if(!targetChar && !targetGUID)
            {
                PSendSysMessage("|cffff0000Combat orders protect and assist expect a target either by selection or by giving target player in command string!");
                SetSentErrorMessage(true);
                return false;
            }
            std::string targetStr = targetChar;
            if(targetChar)
            {
                targetGUID = sObjectMgr.GetPlayerGUIDByName( targetStr.c_str() );
            }
            target = ObjectAccessor::GetUnit( *m_session->GetPlayer(), targetGUID );
            if(!target)
            {
                PSendSysMessage("|cffff0000Invalid target for combat order protect or assist!");
                SetSentErrorMessage(true);
                return false;
            }
        }
        if (mgr->GetPlayerBot(guid) == NULL)
        {
            PSendSysMessage("|cffff0000Bot can not receive combat order because bot does not exist in world.");
            SetSentErrorMessage(true);
            return false;
        }
        mgr->GetPlayerBot( guid )->GetPlayerbotAI()->SetCombatOrderByStr( orderStr, target );
    }
    return true;
}
示例#2
0
void LoadDisables()
{
    uint32 oldMSTime = getMSTime();

    // reload case
    for (std::size_t i = 0; i < m_DisableMap.size(); ++i)
        m_DisableMap[i].clear();

    QueryResult result = WorldDatabase.Query("SELECT sourceType, entry, flags, params_0, params_1 FROM disables");

    uint32 total_count = 0;

    if (!result)
    {
        TC_LOG_INFO("server.loading", ">> Loaded 0 disables. DB table `disables` is empty!");
        return;
    }

    Field* fields;
    do
    {
        fields = result->Fetch();
        uint32 type = fields[0].GetUInt32();
        if (type >= MAX_DISABLE_TYPES)
        {
            TC_LOG_ERROR("sql.sql", "Invalid type %u specified in `disables` table, skipped.", type);
            continue;
        }

        uint32 entry = fields[1].GetUInt32();
        uint8 flags = fields[2].GetUInt8();
        std::string params_0 = fields[3].GetString();
        std::string params_1 = fields[4].GetString();

        DisableData data;
        data.flags = flags;

        switch (type)
        {
            case DISABLE_TYPE_SPELL:
                if (!(sSpellMgr->GetSpellInfo(entry) || flags & SPELL_DISABLE_DEPRECATED_SPELL))
                {
                    TC_LOG_ERROR("sql.sql", "Spell entry %u from `disables` doesn't exist in dbc, skipped.", entry);
                    continue;
                }

                if (!flags || flags > MAX_SPELL_DISABLE_TYPE)
                {
                    TC_LOG_ERROR("sql.sql", "Disable flags for spell %u are invalid, skipped.", entry);
                    continue;
                }

                if (flags & SPELL_DISABLE_MAP)
                {
                    Tokenizer tokens(params_0, ',');
                    for (uint8 i = 0; i < tokens.size(); )
                        data.params[0].insert(atoi(tokens[i++]));
                }

                if (flags & SPELL_DISABLE_AREA)
                {
                    Tokenizer tokens(params_1, ',');
                    for (uint8 i = 0; i < tokens.size(); )
                        data.params[1].insert(atoi(tokens[i++]));
                }

                break;
            // checked later
            case DISABLE_TYPE_QUEST:
                break;
            case DISABLE_TYPE_MAP:
            {
                MapEntry const* mapEntry = sMapStore.LookupEntry(entry);
                if (!mapEntry)
                {
                    TC_LOG_ERROR("sql.sql", "Map entry %u from `disables` doesn't exist in dbc, skipped.", entry);
                    continue;
                }
                bool isFlagInvalid = false;
                switch (mapEntry->InstanceType)
                {
                    case MAP_COMMON:
                        if (flags)
                            isFlagInvalid = true;
                        break;
                    case MAP_INSTANCE:
                    case MAP_RAID:
                        if (flags & DUNGEON_STATUSFLAG_HEROIC && !sDB2Manager.GetMapDifficultyData(entry, DIFFICULTY_HEROIC))
                            flags -= DUNGEON_STATUSFLAG_HEROIC;
                        if (flags & RAID_STATUSFLAG_10MAN_HEROIC && !sDB2Manager.GetMapDifficultyData(entry, DIFFICULTY_10_HC))
                            flags -= RAID_STATUSFLAG_10MAN_HEROIC;
                        if (flags & RAID_STATUSFLAG_25MAN_HEROIC && !sDB2Manager.GetMapDifficultyData(entry, DIFFICULTY_25_HC))
                            flags -= RAID_STATUSFLAG_25MAN_HEROIC;
                        if (!flags)
                            isFlagInvalid = true;
                        break;
                    case MAP_BATTLEGROUND:
                    case MAP_ARENA:
                        TC_LOG_ERROR("sql.sql", "Battleground map %u specified to be disabled in map case, skipped.", entry);
                        continue;
                }
                if (isFlagInvalid)
                {
                    TC_LOG_ERROR("sql.sql", "Disable flags for map %u are invalid, skipped.", entry);
                    continue;
                }
                break;
            }
            case DISABLE_TYPE_BATTLEGROUND:
                if (!sBattlemasterListStore.LookupEntry(entry))
                {
                    TC_LOG_ERROR("sql.sql", "Battleground entry %u from `disables` doesn't exist in dbc, skipped.", entry);
                    continue;
                }
                if (flags)
                    TC_LOG_ERROR("sql.sql", "Disable flags specified for battleground %u, useless data.", entry);
                break;
            case DISABLE_TYPE_OUTDOORPVP:
                if (entry > MAX_OUTDOORPVP_TYPES)
                {
                    TC_LOG_ERROR("sql.sql", "OutdoorPvPTypes value %u from `disables` is invalid, skipped.", entry);
                    continue;
                }
                if (flags)
                    TC_LOG_ERROR("sql.sql", "Disable flags specified for outdoor PvP %u, useless data.", entry);
                break;
            case DISABLE_TYPE_CRITERIA:
                if (!sCriteriaStore.LookupEntry(entry))
                {
                    TC_LOG_ERROR("sql.sql", "Criteria entry %u from `disables` doesn't exist in dbc, skipped.", entry);
                    continue;
                }
                if (flags)
                    TC_LOG_ERROR("sql.sql", "Disable flags specified for Criteria %u, useless data.", entry);
                break;
            case DISABLE_TYPE_VMAP:
            {
                MapEntry const* mapEntry = sMapStore.LookupEntry(entry);
                if (!mapEntry)
                {
                    TC_LOG_ERROR("sql.sql", "Map entry %u from `disables` doesn't exist in dbc, skipped.", entry);
                    continue;
                }
                switch (mapEntry->InstanceType)
                {
                    case MAP_COMMON:
                        if (flags & VMAP::VMAP_DISABLE_AREAFLAG)
                            TC_LOG_INFO("misc", "Areaflag disabled for %s map %u.", MapTypeNames[mapEntry->InstanceType], entry);
                        if (flags & VMAP::VMAP_DISABLE_LIQUIDSTATUS)
                            TC_LOG_INFO("misc", "Liquid status disabled for %s map %u.", MapTypeNames[mapEntry->InstanceType], entry);
                        break;
                    case MAP_INSTANCE:
                    case MAP_RAID:
                    case MAP_BATTLEGROUND:
                    case MAP_ARENA:
                    case MAP_SCENARIO:
                        if (flags & VMAP::VMAP_DISABLE_HEIGHT)
                            TC_LOG_INFO("misc", "Height disabled for %s map %u.", MapTypeNames[mapEntry->InstanceType], entry);
                        if (flags & VMAP::VMAP_DISABLE_LOS)
                            TC_LOG_INFO("misc", "LoS disabled for %s map %u.", MapTypeNames[mapEntry->InstanceType], entry);
                        break;
                }
                break;
            }
            case DISABLE_TYPE_MMAP:
            {
                MapEntry const* mapEntry = sMapStore.LookupEntry(entry);
                if (!mapEntry)
                {
                    TC_LOG_ERROR("sql.sql", "Map entry %u from `disables` doesn't exist in dbc, skipped.", entry);
                    continue;
                }
                if (mapEntry->InstanceType <= MAP_SCENARIO)
                    TC_LOG_INFO("misc", "Pathfinding disabled for %s map %u.", MapTypeNames[mapEntry->InstanceType], entry);
                break;
            }
            default:
                break;
        }

        m_DisableMap[type][entry] = std::move(data);
        ++total_count;
    }
    while (result->NextRow());

    TC_LOG_INFO("server.loading", ">> Loaded %u disables in %u ms", total_count, GetMSTimeDiffToNow(oldMSTime));
}
示例#3
0
// Writing - High-level functions
bool PlayerDumpWriter::DumpTable(std::string& dump, uint32 guid, char const*tableFrom, char const*tableTo, DumpTableType type)
{
    GUIDs const* guids = NULL;
    char const* fieldname = NULL;

    switch (type)
    {
        case DTT_ITEM:      fieldname = "guid";      guids = &items; break;
        case DTT_ITEM_GIFT: fieldname = "item_guid"; guids = &items; break;
        case DTT_PET:       fieldname = "owner";                     break;
        case DTT_PET_TABLE: fieldname = "guid";      guids = &pets;  break;
        case DTT_MAIL:      fieldname = "receiver";                  break;
        case DTT_MAIL_ITEM: fieldname = "mail_id";   guids = &mails; break;
        default:            fieldname = "guid";                      break;
    }

    // for guid set stop if set is empty
    if (guids && guids->empty())
        return true;                                        // nothing to do

    // setup for guids case start position
    GUIDs::const_iterator guids_itr;
    if (guids)
        guids_itr = guids->begin();

    do
    {
        std::string wherestr;

        if (guids)                                           // set case, get next guids string
            wherestr = GenerateWhereStr(fieldname, *guids, guids_itr);
        else                                                // not set case, get single guid string
            wherestr = GenerateWhereStr(fieldname, guid);

        QueryResult result = CharacterDatabase.PQuery("SELECT * FROM %s WHERE %s", tableFrom, wherestr.c_str());
        if (!result)
            return true;

        do
        {
            // collect guids
            switch (type)
            {
                case DTT_INVENTORY:
                    StoreGUID(result, 3, items);                // item guid collection (character_inventory.item)
                    break;
                case DTT_PET:
                    StoreGUID(result, 0, pets);                 // pet petnumber collection (character_pet.id)
                    break;
                case DTT_MAIL:
                    StoreGUID(result, 0, mails);                // mail id collection (mail.id)
                    break;
                case DTT_MAIL_ITEM:
                    StoreGUID(result, 1, items);                // item guid collection (mail_items.item_guid)
                    break;
                case DTT_CHARACTER:
                {
                    if (result->GetFieldCount() <= 64)          // avoid crashes on next check
                    {
                        TC_LOG_FATAL("misc", "PlayerDumpWriter::DumpTable - Trying to access non-existing or wrong positioned field (`deleteInfos_Account`) in `characters` table.");
                        return false;
                    }

                    if (result->Fetch()[64].GetUInt32())        // characters.deleteInfos_Account - if filled error
                        return false;
                    break;
                }
                default:
                    break;
            }

            dump += CreateDumpString(tableTo, result);
            dump += "\n";
        }
        while (result->NextRow());
    }
    while (guids && guids_itr != guids->end());              // not set case iterate single time, set case iterate for all guids
    return true;
}
示例#4
0
void WorldSession::HandlePetitionBuyOpcode(WorldPacket & recv_data)
{
    sLog->outDebug(LOG_FILTER_NETWORKIO, "Received opcode CMSG_PETITION_BUY");

    uint64 guidNPC;
    uint32 clientIndex;                                     // 1 for guild and arenaslot+1 for arenas in client
    std::string name;

    recv_data >> guidNPC;                                   // NPC GUID
    recv_data.read_skip<uint32>();                          // 0
    recv_data.read_skip<uint64>();                          // 0
    recv_data >> name;                                      // name
    recv_data.read_skip<std::string>();                     // some string
    recv_data.read_skip<uint32>();                          // 0
    recv_data.read_skip<uint32>();                          // 0
    recv_data.read_skip<uint32>();                          // 0
    recv_data.read_skip<uint32>();                          // 0
    recv_data.read_skip<uint32>();                          // 0
    recv_data.read_skip<uint32>();                          // 0
    recv_data.read_skip<uint32>();                          // 0
    recv_data.read_skip<uint16>();                          // 0
    recv_data.read_skip<uint32>();                          // 0
    recv_data.read_skip<uint32>();                          // 0
    recv_data.read_skip<uint32>();                          // 0

    for (int i = 0; i < 10; ++i)
        recv_data.read_skip<std::string>();

    recv_data >> clientIndex;                               // index
    recv_data.read_skip<uint32>();                          // 0

    sLog->outDebug(LOG_FILTER_NETWORKIO, "Petitioner with GUID %u tried sell petition: name %s", GUID_LOPART(guidNPC), name.c_str());

    // prevent cheating
    Creature *pCreature = GetPlayer()->GetNPCIfCanInteractWith(guidNPC, UNIT_NPC_FLAG_PETITIONER);
    if (!pCreature)
    {
        sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: HandlePetitionBuyOpcode - Unit (GUID: %u) not found or you can't interact with him.", GUID_LOPART(guidNPC));
        return;
    }

    // remove fake death
    if (GetPlayer()->HasUnitState(UNIT_STAT_DIED))
        GetPlayer()->RemoveAurasByType(SPELL_AURA_FEIGN_DEATH);

    uint32 charterid = 0;
    uint64 cost = 0;
    uint32 type = 0;
    if (pCreature->isTabardDesigner())
    {
        // if tabard designer, then trying to buy a guild charter.
        // do not let if already in guild.
        if (_player->GetGuildId())
            return;

        charterid = GUILD_CHARTER;
        cost = GUILD_CHARTER_COST;
        type = GUILD_CHARTER_TYPE;
    }
    else
    {
        // TODO: find correct opcode
        if (_player->getLevel() < sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL))
        {
            SendNotification(LANG_ARENA_ONE_TOOLOW, sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL));
            return;
        }

        switch(clientIndex)                                 // arenaSlot+1 as received from client (1 from 3 case)
        {
            case 1:
                charterid = ARENA_TEAM_CHARTER_2v2;
                cost = ARENA_TEAM_CHARTER_2v2_COST;
                type = ARENA_TEAM_CHARTER_2v2_TYPE;
                break;
            case 2:
                charterid = ARENA_TEAM_CHARTER_3v3;
                cost = ARENA_TEAM_CHARTER_3v3_COST;
                type = ARENA_TEAM_CHARTER_3v3_TYPE;
                break;
            case 3:
                charterid = ARENA_TEAM_CHARTER_5v5;
                cost = ARENA_TEAM_CHARTER_5v5_COST;
                type = ARENA_TEAM_CHARTER_5v5_TYPE;
                break;
            default:
                sLog->outDebug(LOG_FILTER_NETWORKIO, "unknown selection at buy arena petition: %u", clientIndex);
                return;
        }

        if (_player->GetArenaTeamId(clientIndex - 1))        // arenaSlot+1 as received from client
        {
            SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, name, "", ERR_ALREADY_IN_ARENA_TEAM);
            return;
        }
    }

    if (type == GUILD_CHARTER_TYPE)
    {
        if (sGuildMgr->GetGuildByName(name))
        {
            Guild::SendCommandResult(this, GUILD_CREATE_S, ERR_GUILD_NAME_EXISTS_S, name);
            return;
        }
        if (sObjectMgr->IsReservedName(name) || !ObjectMgr::IsValidCharterName(name))
        {
            Guild::SendCommandResult(this, GUILD_CREATE_S, ERR_GUILD_NAME_INVALID, name);
            return;
        }
    }
    else
    {
        if (sArenaTeamMgr->GetArenaTeamByName(name))
        {
            SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, name, "", ERR_ARENA_TEAM_NAME_EXISTS_S);
            return;
        }
        if (sObjectMgr->IsReservedName(name) || !ObjectMgr::IsValidCharterName(name))
        {
            SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, name, "", ERR_ARENA_TEAM_NAME_INVALID);
            return;
        }
    }

    ItemTemplate const *pProto = sObjectMgr->GetItemTemplate(charterid);
    if (!pProto)
    {
        _player->SendBuyError(BUY_ERR_ITEM_NOT_FOUND, NULL, charterid, 0);
        return;
    }

    if (!_player->HasEnoughMoney(cost))
    {                                                       //player hasn't got enough money
        _player->SendBuyError(BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, charterid, 0);
        return;
    }

    ItemPosCountVec dest;
    InventoryResult msg = _player->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, charterid, pProto->BuyCount);
    if (msg != EQUIP_ERR_OK)
    {
        _player->SendEquipError(msg, NULL, NULL, charterid);
        return;
    }

    _player->ModifyMoney(-(int32)cost);
    Item *charter = _player->StoreNewItem(dest, charterid, true);
    if (!charter)
        return;

    charter->SetUInt32Value(ITEM_FIELD_ENCHANTMENT_1_1, charter->GetGUIDLow());
    // ITEM_FIELD_ENCHANTMENT_1_1 is guild/arenateam id
    // ITEM_FIELD_ENCHANTMENT_1_1+1 is current signatures count (showed on item)
    charter->SetState(ITEM_CHANGED, _player);
    _player->SendNewItem(charter, 1, true, false);

    // a petition is invalid, if both the owner and the type matches
    // we checked above, if this player is in an arenateam, so this must be
    // datacorruption
    QueryResult result = CharacterDatabase.PQuery("SELECT petitionguid FROM petition WHERE ownerguid = '%u'  AND type = '%u'", _player->GetGUIDLow(), type);

    std::ostringstream ssInvalidPetitionGUIDs;

    if (result)
    {
        do
        {
            Field *fields = result->Fetch();
            ssInvalidPetitionGUIDs << '\'' << fields[0].GetUInt32() << "' , ";
        } while (result->NextRow());
    }

    // delete petitions with the same guid as this one
    ssInvalidPetitionGUIDs << '\'' << charter->GetGUIDLow() << '\'';

    sLog->outDebug(LOG_FILTER_NETWORKIO, "Invalid petition GUIDs: %s", ssInvalidPetitionGUIDs.str().c_str());
    CharacterDatabase.EscapeString(name);
    SQLTransaction trans = CharacterDatabase.BeginTransaction();
    trans->PAppend("DELETE FROM petition WHERE petitionguid IN (%s)",  ssInvalidPetitionGUIDs.str().c_str());
    trans->PAppend("DELETE FROM petition_sign WHERE petitionguid IN (%s)", ssInvalidPetitionGUIDs.str().c_str());
    trans->PAppend("INSERT INTO petition (ownerguid, petitionguid, name, type) VALUES ('%u', '%u', '%s', '%u')",
        _player->GetGUIDLow(), charter->GetGUIDLow(), name.c_str(), type);
    CharacterDatabase.CommitTransaction(trans);
}
示例#5
0
    bool OnGossipSelectCode(Player* pPlayer, Creature* pCreature, uint32 uiSender, uint32 uiAction, const char* code)
    {
        pPlayer->PlayerTalkClass->ClearMenus();
        if (uiSender == GOSSIP_SENDER_MAIN)
        {
            switch (uiAction)
            {
                case GOSSIP_ACTION_INFO_DEF:
                {
                    char * charCode = (char*)code;
                    std::string strCode = (char*)code;
                    char * tmp;
                    int32 number[5];
                    std::string error = ("Вы ввели неверное число. Ваша ставка должна находится в пределах от 1 до " + std::string(sConfig->GetStringDefault("Lottery.MaxNumber", "30")));
                    std::string errordub = ("Вы уже делали ставку. Ожидайте розыграша и да благословит вас Элуна");
                    std::string numbers = ("Вы сделали ставку на номера:" + std::string(strCode));

                    tmp = strtok (charCode," ");
                    for (int8 n = 0; n < 5; ++n)
                    {
                        if (tmp != NULL)
                        {
                            number[n] = atoi(tmp);
                            if (number[n] < 0 || number[n] > sConfig->GetIntDefault("Lottery.MaxNumber", 30))
                            {
                                pCreature->MonsterWhisper(error.c_str(), pPlayer->GetGUID());
                                pPlayer->CLOSE_GOSSIP_MENU();
                                return false;
                            }
                            tmp = strtok (NULL, " ");
                        }
                        else
                        {
                            pCreature->MonsterWhisper(error.c_str(), pPlayer->GetGUID());
                            pPlayer->CLOSE_GOSSIP_MENU();
                            return false;
                        }
                    }

                    uint32 betMaxID;
                    QueryResult qbetMaxID = WorldDatabase.Query("SELECT MAX(id) FROM lottery_bets");

                    if (qbetMaxID)
                        betMaxID = qbetMaxID->Fetch()->GetUInt32();
                    else
                        betMaxID = 0;
                        
                    uint32 rBetGuid;
                    QueryResult pBetGuid = WorldDatabase.Query("SELECT guid FROM lottery_bets");
                    
                    if (pBetGuid)
                        rBetGuid = pBetGuid->Fetch()->GetUInt32();
                    else
                        rBetGuid = 0;
                    
                    if (rBetGuid == pPlayer->GetGUID())
                    {
                        pCreature->MonsterWhisper(errordub.c_str(), pPlayer->GetGUID());
                        pPlayer->CLOSE_GOSSIP_MENU();
                        return false;
                    }

                    WorldDatabase.PExecute("INSERT INTO lottery_bets (id, name, guid, bet) VALUES ('%u', '%s', '%u', '%s')", betMaxID+1, pPlayer->GetName(), pPlayer->GetGUIDLow(), strCode.c_str());
                    pCreature->MonsterWhisper(numbers.c_str(), pPlayer->GetGUID());
                    pPlayer->ModifyMoney(-sConfig->GetIntDefault("Lottery.BetCost", 500000));

                    pPlayer->CLOSE_GOSSIP_MENU();

                    return true;
                }
            }
        }

        return false;
        }
示例#6
0
void WorldSession::SendPetitionQueryOpcode(uint64 petitionguid)
{
    uint64 ownerguid = 0;
    uint32 type;
    std::string name = "NO_NAME_FOR_GUID";
    uint8 signs = 0;

    QueryResult result = CharacterDatabase.PQuery(
        "SELECT ownerguid, name, "
        "  (SELECT COUNT(playerguid) FROM petition_sign WHERE petition_sign.petitionguid = '%u') AS signs, "
        "  type "
        "FROM petition WHERE petitionguid = '%u'", GUID_LOPART(petitionguid), GUID_LOPART(petitionguid));

    if (result)
    {
        Field* fields = result->Fetch();
        ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
        name      = fields[1].GetString();
        signs     = fields[2].GetUInt8();
        type      = fields[3].GetUInt32();
    }
    else
    {
        sLog->outDebug(LOG_FILTER_NETWORKIO, "CMSG_PETITION_QUERY failed for petition (GUID: %u)", GUID_LOPART(petitionguid));
        return;
    }

    WorldPacket data(SMSG_PETITION_QUERY_RESPONSE, (4+8+name.size()+1+1+4*12+2+10));
    data << uint32(GUID_LOPART(petitionguid));              // guild/team guid (in Trillium always same as GUID_LOPART(petition guid)
    data << uint64(ownerguid);                              // charter owner guid
    data << name;                                           // name (guild/arena team)
    data << uint8(0);                                       // some string
    if (type == GUILD_CHARTER_TYPE)
    {
        data << uint32(9);
        data << uint32(9);
        data << uint32(0);                                  // bypass client - side limitation, a different value is needed here for each petition
    }
    else
    {
        data << uint32(type-1);
        data << uint32(type-1);
        data << uint32(type);                               // bypass client - side limitation, a different value is needed here for each petition
    }
    data << uint32(0);                                      // 5
    data << uint32(0);                                      // 6
    data << uint32(0);                                      // 7
    data << uint32(0);                                      // 8
    data << uint16(0);                                      // 9 2 bytes field
    data << uint32(0);                                      // 10
    data << uint32(0);                                      // 11
    data << uint32(0);                                      // 13 count of next strings?

    for (int i = 0; i < 10; ++i)
        data << uint8(0);                                   // some string

    data << uint32(0);                                      // 14

    if (type == GUILD_CHARTER_TYPE)
        data << uint32(0);                                  // 15 0 - guild, 1 - arena team
    else
        data << uint32(1);

    SendPacket(&data);
}
示例#7
0
void WorldSession::HandlePetitionSignOpcode(WorldPacket & recv_data)
{
    sLog->outDebug(LOG_FILTER_NETWORKIO, "Received opcode CMSG_PETITION_SIGN");    // ok

    Field *fields;
    uint64 petitionguid;
    uint8 unk;
    recv_data >> petitionguid;                              // petition guid
    recv_data >> unk;

    QueryResult result = CharacterDatabase.PQuery(
        "SELECT ownerguid, "
        "  (SELECT COUNT(playerguid) FROM petition_sign WHERE petition_sign.petitionguid = '%u') AS signs, "
        "  type "
        "FROM petition WHERE petitionguid = '%u'", GUID_LOPART(petitionguid), GUID_LOPART(petitionguid));

    if (!result)
    {
        sLog->outError("Petition %u is not found for player %u %s", GUID_LOPART(petitionguid), GetPlayer()->GetGUIDLow(), GetPlayer()->GetName());
        return;
    }

    fields = result->Fetch();
    uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
    uint8 signs = fields[1].GetUInt8();
    uint32 type = fields[2].GetUInt32();

    uint32 plguidlo = _player->GetGUIDLow();
    if (GUID_LOPART(ownerguid) == plguidlo)
        return;

    // not let enemies sign guild charter
    if (!sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_GUILD) && GetPlayer()->GetTeam() != sObjectMgr->GetPlayerTeamByGUID(ownerguid))
    {
        if (type != GUILD_CHARTER_TYPE)
            SendArenaTeamCommandResult(ERR_ARENA_TEAM_INVITE_SS, "", "", ERR_ARENA_TEAM_NOT_ALLIED);
        else
            Guild::SendCommandResult(this, GUILD_CREATE_S, ERR_GUILD_NOT_ALLIED);
        return;
    }

    if (type != GUILD_CHARTER_TYPE)
    {
        if (_player->getLevel() < sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL))
        {
            SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, "", _player->GetName(), ERR_ARENA_TEAM_TARGET_TOO_LOW_S);
            return;
        }

        uint8 slot = ArenaTeam::GetSlotByType(type);
        if (slot >= MAX_ARENA_SLOT)
            return;

        if (_player->GetArenaTeamId(slot))
        {
            SendArenaTeamCommandResult(ERR_ARENA_TEAM_INVITE_SS, "", _player->GetName(), ERR_ALREADY_IN_ARENA_TEAM_S);
            return;
        }

        if (_player->GetArenaTeamIdInvited())
        {
            SendArenaTeamCommandResult(ERR_ARENA_TEAM_INVITE_SS, "", _player->GetName(), ERR_ALREADY_INVITED_TO_ARENA_TEAM_S);
            return;
        }
    }
    else
    {
        if (_player->GetGuildId())
        {
            Guild::SendCommandResult(this, GUILD_INVITE_S, ERR_ALREADY_IN_GUILD_S, _player->GetName());
            return;
        }
        if (_player->GetGuildIdInvited())
        {
            Guild::SendCommandResult(this, GUILD_INVITE_S, ERR_ALREADY_INVITED_TO_GUILD_S, _player->GetName());
            return;
        }
    }

    if (++signs > type)                                        // client signs maximum
        return;

    //client doesn't allow to sign petition two times by one character, but not check sign by another character from same account
    //not allow sign another player from already sign player account
    result = CharacterDatabase.PQuery("SELECT playerguid FROM petition_sign WHERE player_account = '%u' AND petitionguid = '%u'", GetAccountId(), GUID_LOPART(petitionguid));

    if (result)
    {
        WorldPacket data(SMSG_PETITION_SIGN_RESULTS, (8+8+4));
        data << uint64(petitionguid);
        data << uint64(_player->GetGUID());
        data << (uint32)PETITION_SIGN_ALREADY_SIGNED;

        // close at signer side
        SendPacket(&data);

        // update for owner if online
        if (Player *owner = ObjectAccessor::FindPlayer(ownerguid))
            owner->GetSession()->SendPacket(&data);
        return;
    }

    CharacterDatabase.PExecute("INSERT INTO petition_sign (ownerguid, petitionguid, playerguid, player_account) VALUES ('%u', '%u', '%u', '%u')", GUID_LOPART(ownerguid), GUID_LOPART(petitionguid), plguidlo, GetAccountId());

    sLog->outDebug(LOG_FILTER_NETWORKIO, "PETITION SIGN: GUID %u by player: %s (GUID: %u Account: %u)", GUID_LOPART(petitionguid), _player->GetName(), plguidlo, GetAccountId());

    WorldPacket data(SMSG_PETITION_SIGN_RESULTS, (8+8+4));
    data << uint64(petitionguid);
    data << uint64(_player->GetGUID());
    data << uint32(PETITION_SIGN_OK);

    // close at signer side
    SendPacket(&data);

    // update signs count on charter, required testing...
    //Item *item = _player->GetItemByGuid(petitionguid));
    //if (item)
    //    item->SetUInt32Value(ITEM_FIELD_ENCHANTMENT_1_1+1, signs);

    // update for owner if online
    if (Player *owner = ObjectAccessor::FindPlayer(ownerguid))
        owner->GetSession()->SendPacket(&data);
}
示例#8
0
	static bool HandleWpModifyCommand(ChatHandler* handler, const char* args) {
		if (!*args)
			return false;

		// first arg: add del text emote spell waittime move
		char* show_str = strtok((char*) args, " ");
		if (!show_str) {
			return false;
		}

		std::string show = show_str;
		// Check
		// Remember: "show" must also be the name of a column!
		if ((show != "delay") && (show != "action") && (show != "action_chance")
				&& (show != "move_flag") && (show != "del") && (show != "move")
				&& (show != "wpadd")) {
			return false;
		}

		// Next arg is: <PATHID> <WPNUM> <ARGUMENT>
		char* arg_str = NULL;

		// Did user provide a GUID
		// or did the user select a creature?
		// -> variable lowguid is filled with the GUID of the NPC
		uint32 pathid = 0;
		uint32 point = 0;
		uint32 wpGuid = 0;
		Creature* target = handler->getSelectedCreature();

		if (!target || target->GetEntry() != VISUAL_WAYPOINT) {
			handler->SendSysMessage(
					"|cffff33ffERROR: You must select a waypoint.|r");
			return false;
		}

		// The visual waypoint
		Creature* wpCreature = NULL;
		wpGuid = target->GetGUIDLow();

		// Did the user select a visual spawnpoint?
		if (wpGuid)
			wpCreature =
					handler->GetSession()->GetPlayer()->GetMap()->GetCreature(
							MAKE_NEW_GUID(wpGuid, VISUAL_WAYPOINT, HIGHGUID_UNIT));
		// attempt check creature existence by DB data
		else {
			handler->PSendSysMessage(LANG_WAYPOINT_CREATNOTFOUND, wpGuid);
			return false;
		}
		// User did select a visual waypoint?
		// Check the creature
		if (wpCreature->GetEntry() == VISUAL_WAYPOINT) {
			QueryResult result = WorldDatabase.PQuery(
					"SELECT id, point FROM waypoint_data WHERE wpguid = %u",
					wpGuid);

			if (!result) {
				handler->PSendSysMessage(LANG_WAYPOINT_NOTFOUNDSEARCH,
						target->GetGUIDLow());
				// Select waypoint number from database
				// Since we compare float values, we have to deal with
				// some difficulties.
				// Here we search for all waypoints that only differ in one from 1 thousand
				// (0.001) - There is no other way to compare C++ floats with mySQL floats
				// See also: http://dev.mysql.com/doc/refman/5.0/en/problems-with-float.html
				const char* maxDIFF = "0.01";
				result =
						WorldDatabase.PQuery(
								"SELECT id, point FROM waypoint_data WHERE (abs(position_x - %f) <= %s) and (abs(position_y - %f) <= %s) and (abs(position_z - %f) <= %s)",
								wpCreature->GetPositionX(), maxDIFF,
								wpCreature->GetPositionY(), maxDIFF,
								wpCreature->GetPositionZ(), maxDIFF);
				if (!result) {
					handler->PSendSysMessage(LANG_WAYPOINT_NOTFOUNDDBPROBLEM,
							wpGuid);
					return true;
				}
			}

			do {
				Field *fields = result->Fetch();
				pathid = fields[0].GetUInt32();
				point = fields[1].GetUInt32();
			} while (result->NextRow());

			// We have the waypoint number and the GUID of the "master npc"
			// Text is enclosed in "<>", all other arguments not
			arg_str = strtok((char*) NULL, " ");
		}

		// Check for argument
		if (show != "del" && show != "move" && arg_str == NULL) {
			handler->PSendSysMessage(LANG_WAYPOINT_ARGUMENTREQ, show_str);
			return false;
		}

		if (show == "del" && target) {
			handler->PSendSysMessage(
					"|cff00ff00DEBUG: wp modify del, PathID: |r|cff00ffff%u|r",
					pathid);

			// wpCreature
			Creature* wpCreature = NULL;

			if (wpGuid != 0) {
				wpCreature =
						handler->GetSession()->GetPlayer()->GetMap()->GetCreature(
								MAKE_NEW_GUID(wpGuid, VISUAL_WAYPOINT, HIGHGUID_UNIT));
				wpCreature->CombatStop();
				wpCreature->DeleteFromDB();
				wpCreature->AddObjectToRemoveList();
			}

			WorldDatabase.PExecute(
					"DELETE FROM waypoint_data WHERE id='%u' AND point='%u'",
					pathid, point);
			WorldDatabase.PExecute(
					"UPDATE waypoint_data SET point=point-1 WHERE id='%u' AND point>'%u'",
					pathid, point);

			handler->PSendSysMessage(LANG_WAYPOINT_REMOVED);
			return true;
		} // del

		if (show == "move" && target) {
			handler->PSendSysMessage(
					"|cff00ff00DEBUG: wp move, PathID: |r|cff00ffff%u|r",
					pathid);

			Player *chr = handler->GetSession()->GetPlayer();
			Map *map = chr->GetMap();
			{
				// wpCreature
				Creature* wpCreature = NULL;
				// What to do:
				// Move the visual spawnpoint
				// Respawn the owner of the waypoints
				if (wpGuid != 0) {
					wpCreature =
							handler->GetSession()->GetPlayer()->GetMap()->GetCreature(
									MAKE_NEW_GUID(wpGuid, VISUAL_WAYPOINT, HIGHGUID_UNIT));
					wpCreature->CombatStop();
					wpCreature->DeleteFromDB();
					wpCreature->AddObjectToRemoveList();
					// re-create
					Creature* wpCreature2 = new Creature;
					if (!wpCreature2->Create(
							sObjectMgr->GenerateLowGuid(HIGHGUID_UNIT), map, chr->GetPhaseMaskForSpawn(), VISUAL_WAYPOINT, 0, 0, chr->GetPositionX(), chr->GetPositionY(), chr->GetPositionZ(), chr->GetOrientation()))
							{
								handler->PSendSysMessage(LANG_WAYPOINT_VP_NOTCREATED, VISUAL_WAYPOINT);
								delete wpCreature2;
								return false;
							}

					wpCreature2->SaveToDB(map->GetId(),
							(1 << map->GetSpawnMode()),
							chr->GetPhaseMaskForSpawn());
					// To call _LoadGoods(); _LoadQuests(); CreateTrainerSpells();
					wpCreature2->LoadFromDB(wpCreature2->GetDBTableGUIDLow(),
							map);
					map->Add(wpCreature2);
					//sMapMgr->GetMap(npcCreature->GetMapId())->Add(wpCreature2);
				}

				WorldDatabase.PExecute(
						"UPDATE waypoint_data SET position_x = '%f', position_y = '%f', position_z = '%f' where id = '%u' AND point='%u'",
						chr->GetPositionX(), chr->GetPositionY(),
						chr->GetPositionZ(), pathid, point);

				handler->PSendSysMessage(LANG_WAYPOINT_CHANGED);
			}
			return true;
		} // move

		const char *text = arg_str;

		if (text == 0) {
			// show_str check for present in list of correct values, no sql injection possible
			WorldDatabase.PExecute(
					"UPDATE waypoint_data SET %s=NULL WHERE id='%u' AND point='%u'",
					show_str, pathid, point);
		} else {
			// show_str check for present in list of correct values, no sql injection possible
			std::string text2 = text;
			WorldDatabase.EscapeString(text2);
			WorldDatabase.PExecute(
					"UPDATE waypoint_data SET %s='%s' WHERE id='%u' AND point='%u'",
					show_str, text2.c_str(), pathid, point);
		}

		handler->PSendSysMessage(LANG_WAYPOINT_CHANGED_NO, show_str);
		return true;
	}
示例#9
0
	static bool HandleWpShowCommand(ChatHandler* handler, const char* args) {
		if (!*args)
			return false;

		// first arg: on, off, first, last
		char* show_str = strtok((char*) args, " ");
		if (!show_str)
			return false;

		// second arg: GUID (optional, if a creature is selected)
		char* guid_str = strtok((char*) NULL, " ");

		uint32 pathid = 0;
		Creature* target = handler->getSelectedCreature();

		// Did player provide a PathID?

		if (!guid_str) {
			// No PathID provided
			// -> Player must have selected a creature

			if (!target) {
				handler->SendSysMessage(LANG_SELECT_CREATURE);
				handler->SetSentErrorMessage(true);
				return false;
			}

			pathid = target->GetWaypointPath();
		} else {
			// PathID provided
			// Warn if player also selected a creature
			// -> Creature selection is ignored <-
			if (target)
				handler->SendSysMessage(LANG_WAYPOINT_CREATSELECTED);

			pathid = atoi((char*) guid_str);
		}

		std::string show = show_str;
		uint32 Maxpoint;

		//handler->PSendSysMessage("wpshow - show: %s", show);

		// Show info for the selected waypoint
		if (show == "info") {
			// Check if the user did specify a visual waypoint
			if (target->GetEntry() != VISUAL_WAYPOINT) {
				handler->PSendSysMessage(LANG_WAYPOINT_VP_SELECT);
				handler->SetSentErrorMessage(true);
				return false;
			}

			QueryResult result =
					WorldDatabase.PQuery(
							"SELECT id, point, delay, move_flag, action, action_chance FROM waypoint_data WHERE wpguid = %u",
							target->GetGUIDLow());

			if (!result) {
				handler->SendSysMessage(LANG_WAYPOINT_NOTFOUNDDBPROBLEM);
				return true;
			}

			handler->SendSysMessage("|cff00ffffDEBUG: wp show info:|r");
			do {
				Field *fields = result->Fetch();
				pathid = fields[0].GetUInt32();
				uint32 point = fields[1].GetUInt32();
				uint32 delay = fields[2].GetUInt32();
				uint32 flag = fields[3].GetUInt32();
				uint32 ev_id = fields[4].GetUInt32();
				uint32 ev_chance = fields[5].GetUInt32();

				handler->PSendSysMessage(
						"|cff00ff00Show info: for current point: |r|cff00ffff%u|r|cff00ff00, Path ID: |r|cff00ffff%u|r",
						point, pathid);
				handler->PSendSysMessage(
						"|cff00ff00Show info: delay: |r|cff00ffff%u|r", delay);
				handler->PSendSysMessage(
						"|cff00ff00Show info: Move flag: |r|cff00ffff%u|r",
						flag);
				handler->PSendSysMessage(
						"|cff00ff00Show info: Waypoint event: |r|cff00ffff%u|r",
						ev_id);
				handler->PSendSysMessage(
						"|cff00ff00Show info: Event chance: |r|cff00ffff%u|r",
						ev_chance);
			} while (result->NextRow());

			return true;
		}

		if (show == "on") {
			QueryResult result =
					WorldDatabase.PQuery(
							"SELECT point, position_x, position_y, position_z FROM waypoint_data WHERE id = '%u'",
							pathid);

			if (!result) {
				handler->SendSysMessage("|cffff33ffPath no found.|r");
				handler->SetSentErrorMessage(true);
				return false;
			}

			handler->PSendSysMessage(
					"|cff00ff00DEBUG: wp on, PathID: |cff00ffff%u|r", pathid);

			// Delete all visuals for this NPC
			QueryResult result2 =
					WorldDatabase.PQuery(
							"SELECT wpguid FROM waypoint_data WHERE id = '%u' and wpguid <> 0",
							pathid);

			if (result2) {
				bool hasError = false;
				do {
					Field *fields = result2->Fetch();
					uint32 wpguid = fields[0].GetUInt32();
					Creature* pCreature =
							handler->GetSession()->GetPlayer()->GetMap()->GetCreature(
									MAKE_NEW_GUID(wpguid, VISUAL_WAYPOINT, HIGHGUID_UNIT));

					if (!pCreature) {
						handler->PSendSysMessage(LANG_WAYPOINT_NOTREMOVED,
								wpguid);
						hasError = true;
						WorldDatabase.PExecute(
								"DELETE FROM creature WHERE guid = '%u'",
								wpguid);
					} else {
						pCreature->CombatStop();
						pCreature->DeleteFromDB();
						pCreature->AddObjectToRemoveList();
					}
				} while (result2->NextRow());

				if (hasError) {
					handler->PSendSysMessage(LANG_WAYPOINT_TOOFAR1);
					handler->PSendSysMessage(LANG_WAYPOINT_TOOFAR2);
					handler->PSendSysMessage(LANG_WAYPOINT_TOOFAR3);
				}
			}

			do {
				Field *fields = result->Fetch();
				uint32 point = fields[0].GetUInt32();
				float x = fields[1].GetFloat();
				float y = fields[2].GetFloat();
				float z = fields[3].GetFloat();

				uint32 id = VISUAL_WAYPOINT;

				Player *chr = handler->GetSession()->GetPlayer();
				Map *map = chr->GetMap();
				float o = chr->GetOrientation();

				Creature* wpCreature = new Creature;
				if (!wpCreature->Create(
						sObjectMgr->GenerateLowGuid(HIGHGUID_UNIT), map, chr->GetPhaseMaskForSpawn(), id, 0, 0, x, y, z, o))
						{
							handler->PSendSysMessage(LANG_WAYPOINT_VP_NOTCREATED, id);
							delete wpCreature;
							return false;
						}

				// set "wpguid" column to the visual waypoint
				WorldDatabase.PExecute(
						"UPDATE waypoint_data SET wpguid = '%u' WHERE id = '%u' and point = '%u'",
						wpCreature->GetGUIDLow(), pathid, point);

				wpCreature->SaveToDB(map->GetId(), (1 << map->GetSpawnMode()),
						chr->GetPhaseMaskForSpawn());
				// To call _LoadGoods(); _LoadQuests(); CreateTrainerSpells();
				wpCreature->LoadFromDB(wpCreature->GetDBTableGUIDLow(), map);
				map->Add(wpCreature);

				if (target) {
					wpCreature->SetDisplayId(target->GetDisplayId());
					wpCreature->SetFloatValue(OBJECT_FIELD_SCALE_X, 0.5);
					wpCreature->SetLevel(
							point > STRONG_MAX_LEVEL ?
									STRONG_MAX_LEVEL : point);
				}
			} while (result->NextRow());

			handler->SendSysMessage(
					"|cff00ff00Showing the current creature's path.|r");
			return true;
		}

		if (show == "first") {
			handler->PSendSysMessage("|cff00ff00DEBUG: wp first, GUID: %u|r",
					pathid);

			QueryResult result =
					WorldDatabase.PQuery(
							"SELECT position_x, position_y, position_z FROM waypoint_data WHERE point='1' AND id = '%u'",
							pathid);
			if (!result) {
				handler->PSendSysMessage(LANG_WAYPOINT_NOTFOUND, pathid);
				handler->SetSentErrorMessage(true);
				return false;
			}

			Field *fields = result->Fetch();
			float x = fields[0].GetFloat();
			float y = fields[1].GetFloat();
			float z = fields[2].GetFloat();
			uint32 id = VISUAL_WAYPOINT;

			Player *chr = handler->GetSession()->GetPlayer();
			float o = chr->GetOrientation();
			Map *map = chr->GetMap();

			Creature* pCreature = new Creature;
			if (!pCreature->Create(sObjectMgr->GenerateLowGuid(HIGHGUID_UNIT), map,chr->GetPhaseMaskForSpawn(), id, 0, 0, x, y, z, o))
			{
				handler->PSendSysMessage(LANG_WAYPOINT_VP_NOTCREATED, id);
				delete pCreature;
				return false;
			}

			pCreature->SaveToDB(map->GetId(), (1 << map->GetSpawnMode()),
					chr->GetPhaseMaskForSpawn());
			pCreature->LoadFromDB(pCreature->GetDBTableGUIDLow(), map);
			map->Add(pCreature);

			if (target) {
				pCreature->SetDisplayId(target->GetDisplayId());
				pCreature->SetFloatValue(OBJECT_FIELD_SCALE_X, 0.5);
			}

			return true;
		}

		if (show == "last") {
			handler->PSendSysMessage(
					"|cff00ff00DEBUG: wp last, PathID: |r|cff00ffff%u|r",
					pathid);

			QueryResult result = WorldDatabase.PQuery(
					"SELECT MAX(point) FROM waypoint_data WHERE id = '%u'",
					pathid);
			if (result)
				Maxpoint = (*result)[0].GetUInt32();
			else
				Maxpoint = 0;

			result =
					WorldDatabase.PQuery(
							"SELECT position_x, position_y, position_z FROM waypoint_data WHERE point ='%u' AND id = '%u'",
							Maxpoint, pathid);
			if (!result) {
				handler->PSendSysMessage(LANG_WAYPOINT_NOTFOUNDLAST, pathid);
				handler->SetSentErrorMessage(true);
				return false;
			}
			Field *fields = result->Fetch();
			float x = fields[0].GetFloat();
			float y = fields[1].GetFloat();
			float z = fields[2].GetFloat();
			uint32 id = VISUAL_WAYPOINT;

			Player *chr = handler->GetSession()->GetPlayer();
			float o = chr->GetOrientation();
			Map *map = chr->GetMap();

			Creature* pCreature = new Creature;
			if (!pCreature->Create(sObjectMgr->GenerateLowGuid(HIGHGUID_UNIT), map,chr->GetPhaseMaskForSpawn(), id, 0, 0, x, y, z, o))
			{
				handler->PSendSysMessage(LANG_WAYPOINT_NOTCREATED, id);
				delete pCreature;
				return false;
			}

			pCreature->SaveToDB(map->GetId(), (1 << map->GetSpawnMode()),
					chr->GetPhaseMaskForSpawn());
			pCreature->LoadFromDB(pCreature->GetDBTableGUIDLow(), map);
			map->Add(pCreature);

			if (target) {
				pCreature->SetDisplayId(target->GetDisplayId());
				pCreature->SetFloatValue(OBJECT_FIELD_SCALE_X, 0.5);
			}

			return true;
		}

		if (show == "off") {
			QueryResult result = WorldDatabase.PQuery(
					"SELECT guid FROM creature WHERE id = '%u'", 1);
			if (!result) {
				handler->SendSysMessage(LANG_WAYPOINT_VP_NOTFOUND);
				handler->SetSentErrorMessage(true);
				return false;
			}
			bool hasError = false;
			do {
				Field *fields = result->Fetch();
				uint32 guid = fields[0].GetUInt32();
				Creature* pCreature =
						handler->GetSession()->GetPlayer()->GetMap()->GetCreature(
								MAKE_NEW_GUID(guid, VISUAL_WAYPOINT, HIGHGUID_UNIT));
				if (!pCreature) {
					handler->PSendSysMessage(LANG_WAYPOINT_NOTREMOVED, guid);
					hasError = true;
					WorldDatabase.PExecute(
							"DELETE FROM creature WHERE guid = '%u'", guid);
				} else {
					pCreature->CombatStop();
					pCreature->DeleteFromDB();
					pCreature->AddObjectToRemoveList();
				}
			} while (result->NextRow());
			// set "wpguid" column to "empty" - no visual waypoint spawned
			WorldDatabase.PExecute("UPDATE waypoint_data SET wpguid = '0'");
			//WorldDatabase.PExecute("UPDATE creature_movement SET wpguid = '0' WHERE wpguid <> '0'");

			if (hasError) {
				handler->PSendSysMessage(LANG_WAYPOINT_TOOFAR1);
				handler->PSendSysMessage(LANG_WAYPOINT_TOOFAR2);
				handler->PSendSysMessage(LANG_WAYPOINT_TOOFAR3);
			}

			handler->SendSysMessage(LANG_WAYPOINT_VP_ALLREMOVED);
			return true;
		}

		handler->PSendSysMessage(
				"|cffff33ffDEBUG: wpshow - no valid command found|r");
		return true;
	}
// loads the extra item creation info from DB
void LoadSkillExtraItemTable() {
	uint32 oldMSTime = getMSTime();

	SkillExtraItemStore.clear(); // need for reload

	//                                                 0        1                       2                       3
	QueryResult result =
			WorldDatabase.Query(
					"SELECT spellId, requiredSpecialization, additionalCreateChance, additionalMaxNum FROM skill_extra_item_template");

	if (!result) {
		sLog->outErrorDb(
				">> Loaded 0 spell specialization definitions. DB table `skill_extra_item_template` is empty.");
		sLog->outString();
		return;
	}

	uint32 count = 0;

	do {
		Field *fields = result->Fetch();

		uint32 spellId = fields[0].GetUInt32();

		if (!sSpellStore.LookupEntry(spellId)) {
			sLog->outError(
					"Skill specialization %u has non-existent spell id in `skill_extra_item_template`!",
					spellId);
			continue;
		}

		uint32 requiredSpecialization = fields[1].GetUInt32();
		if (!sSpellStore.LookupEntry(requiredSpecialization)) {
			sLog->outError(
					"Skill specialization %u have not existed required specialization spell id %u in `skill_extra_item_template`!",
					spellId, requiredSpecialization);
			continue;
		}

		float additionalCreateChance = fields[2].GetFloat();
		if (additionalCreateChance <= 0.0f) {
			sLog->outError(
					"Skill specialization %u has too low additional create chance in `skill_extra_item_template`!",
					spellId);
			continue;
		}

		uint8 additionalMaxNum = fields[3].GetUInt8();
		if (!additionalMaxNum) {
			sLog->outError(
					"Skill specialization %u has 0 max number of extra items in `skill_extra_item_template`!",
					spellId);
			continue;
		}

		SkillExtraItemEntry& skillExtraItemEntry = SkillExtraItemStore[spellId];

		skillExtraItemEntry.requiredSpecialization = requiredSpecialization;
		skillExtraItemEntry.additionalCreateChance = additionalCreateChance;
		skillExtraItemEntry.additionalMaxNum = additionalMaxNum;

		++count;
	} while (result->NextRow());

	sLog->outString(">> Loaded %u spell specialization definitions in %u ms",
			count, GetMSTimeDiffToNow(oldMSTime));
	sLog->outString();
}
示例#11
0
	static bool HandleWpEventCommand(ChatHandler* handler, const char* args) {
		if (!*args)
			return false;

		char* show_str = strtok((char*) args, " ");
		std::string show = show_str;

		// Check
		if ((show != "add") && (show != "mod") && (show != "del")
				&& (show != "listid"))
			return false;

		char* arg_id = strtok(NULL, " ");
		uint32 id = 0;

		if (show == "add") {
			if (arg_id)
				id = atoi(arg_id);

			if (id) {
				QueryResult result = WorldDatabase.PQuery(
						"SELECT id FROM waypoint_scripts WHERE guid = %u", id);

				if (!result) {
					WorldDatabase.PExecute(
							"INSERT INTO waypoint_scripts(guid)VALUES(%u)", id);
					handler->PSendSysMessage("%s%s%u|r", "|cff00ff00",
							"Wp Event: New waypoint event added: ", id);
				} else
					handler->PSendSysMessage(
							"|cff00ff00Wp Event: You have choosed an existing waypoint script guid: %u|r",
							id);
			} else {
				QueryResult result = WorldDatabase.Query(
						"SELECT MAX(guid) FROM waypoint_scripts");
				id = result->Fetch()->GetUInt32();
				WorldDatabase.PExecute(
						"INSERT INTO waypoint_scripts(guid)VALUES(%u)", id + 1);
				handler->PSendSysMessage("%s%s%u|r", "|cff00ff00",
						"Wp Event: New waypoint event added: |r|cff00ffff",
						id + 1);
			}

			return true;
		}

		if (show == "listid") {
			if (!arg_id) {
				handler->PSendSysMessage("%s%s|r", "|cff33ffff",
						"Wp Event: You must provide waypoint script id.");
				return true;
			}

			id = atoi(arg_id);

			uint32 a2, a3, a4, a5, a6;
			float a8, a9, a10, a11;
			char const* a7;

			QueryResult result =
					WorldDatabase.PQuery(
							"SELECT guid, delay, command, datalong, datalong2, dataint, x, y, z, o FROM waypoint_scripts WHERE id = %u",
							id);

			if (!result) {
				handler->PSendSysMessage("%s%s%u|r", "|cff33ffff",
						"Wp Event: No waypoint scripts found on id: ", id);
				return true;
			}

			Field *fields;

			do {
				fields = result->Fetch();
				a2 = fields[0].GetUInt32();
				a3 = fields[1].GetUInt32();
				a4 = fields[2].GetUInt32();
				a5 = fields[3].GetUInt32();
				a6 = fields[4].GetUInt32();
				a7 = fields[5].GetCString();
				a8 = fields[6].GetFloat();
				a9 = fields[7].GetFloat();
				a10 = fields[8].GetFloat();
				a11 = fields[9].GetFloat();

				handler->PSendSysMessage(
						"|cffff33ffid:|r|cff00ffff %u|r|cff00ff00, guid: |r|cff00ffff%u|r|cff00ff00, delay: |r|cff00ffff%u|r|cff00ff00, command: |r|cff00ffff%u|r|cff00ff00, datalong: |r|cff00ffff%u|r|cff00ff00, datalong2: |r|cff00ffff%u|r|cff00ff00, datatext: |r|cff00ffff%s|r|cff00ff00, posx: |r|cff00ffff%f|r|cff00ff00, posy: |r|cff00ffff%f|r|cff00ff00, posz: |r|cff00ffff%f|r|cff00ff00, orientation: |r|cff00ffff%f|r",
						id, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11);
			} while (result->NextRow());
		}

		if (show == "del") {
			id = atoi(arg_id);

			QueryResult result = WorldDatabase.PQuery(
					"SELECT guid FROM waypoint_scripts WHERE guid = %u", id);

			if (result) {
				WorldDatabase.PExecute(
						"DELETE FROM waypoint_scripts WHERE guid = %u", id);
				handler->PSendSysMessage("%s%s%u|r", "|cff00ff00",
						"Wp Event: Waypoint script removed: ", id);
			} else
				handler->PSendSysMessage(
						"|cffff33ffWp Event: ERROR: you have selected a non existing script: %u|r",
						id);

			return true;
		}

		if (show == "mod") {
			if (!arg_id) {
				handler->SendSysMessage(
						"|cffff33ffERROR: Waypoint script guid not present.|r");
				return true;
			}

			id = atoi(arg_id);

			if (!id) {
				handler->SendSysMessage(
						"|cffff33ffERROR: No vallid waypoint script id not present.|r");
				return true;
			}

			char* arg_2 = strtok(NULL, " ");

			if (!arg_2) {
				handler->SendSysMessage(
						"|cffff33ffERROR: No argument present.|r");
				return true;
			}

			std::string arg_string = arg_2;

			if ((arg_string != "setid") && (arg_string != "delay")
					&& (arg_string != "command") && (arg_string != "datalong")
					&& (arg_string != "datalong2") && (arg_string != "dataint")
					&& (arg_string != "posx") && (arg_string != "posy")
					&& (arg_string != "posz")
					&& (arg_string != "orientation")) {
				handler->SendSysMessage(
						"|cffff33ffERROR: No valid argument present.|r");
				return true;
			}

			char* arg_3;
			std::string arg_str_2 = arg_2;
			arg_3 = strtok(NULL, " ");

			if (!arg_3) {
				handler->SendSysMessage(
						"|cffff33ffERROR: No additional argument present.|r");
				return true;
			}

			float coord;

			if (arg_str_2 == "setid") {
				uint32 newid = atoi(arg_3);
				handler->PSendSysMessage(
						"%s%s|r|cff00ffff%u|r|cff00ff00%s|r|cff00ffff%u|r",
						"|cff00ff00", "Wp Event: Wypoint scipt guid: ", newid,
						" id changed: ", id);
				WorldDatabase.PExecute(
						"UPDATE waypoint_scripts SET id='%u' WHERE guid='%u'",
						newid, id);
				return true;
			} else {
				QueryResult result = WorldDatabase.PQuery(
						"SELECT id FROM waypoint_scripts WHERE guid='%u'", id);

				if (!result) {
					handler->SendSysMessage(
							"|cffff33ffERROR: You have selected an non existing waypoint script guid.|r");
					return true;
				}

				if (arg_str_2 == "posx") {
					coord = (float) (atof(arg_3));
					WorldDatabase.PExecute(
							"UPDATE waypoint_scripts SET x='%f' WHERE guid='%u'",
							coord, id);
					handler->PSendSysMessage(
							"|cff00ff00Waypoint script:|r|cff00ffff %u|r|cff00ff00 position_x updated.|r",
							id);
					return true;
				} else if (arg_str_2 == "posy") {
					coord = (float) (atof(arg_3));
					WorldDatabase.PExecute(
							"UPDATE waypoint_scripts SET y='%f' WHERE guid='%u'",
							coord, id);
					handler->PSendSysMessage(
							"|cff00ff00Waypoint script: %u position_y updated.|r",
							id);
					return true;
				} else if (arg_str_2 == "posz") {
					coord = (float) (atof(arg_3));
					WorldDatabase.PExecute(
							"UPDATE waypoint_scripts SET z='%f' WHERE guid='%u'",
							coord, id);
					handler->PSendSysMessage(
							"|cff00ff00Waypoint script: |r|cff00ffff%u|r|cff00ff00 position_z updated.|r",
							id);
					return true;
				} else if (arg_str_2 == "orientation") {
					coord = (float) (atof(arg_3));
					WorldDatabase.PExecute(
							"UPDATE waypoint_scripts SET o='%f' WHERE guid='%u'",
							coord, id);
					handler->PSendSysMessage(
							"|cff00ff00Waypoint script: |r|cff00ffff%u|r|cff00ff00 orientation updated.|r",
							id);
					return true;
				} else if (arg_str_2 == "dataint") {
					WorldDatabase.PExecute(
							"UPDATE waypoint_scripts SET %s='%u' WHERE guid='%u'",
							arg_2, atoi(arg_3), id);
					handler->PSendSysMessage(
							"|cff00ff00Waypoint script: |r|cff00ffff%u|r|cff00ff00 dataint updated.|r",
							id);
					return true;
				} else {
					std::string arg_str_3 = arg_3;
					WorldDatabase.EscapeString(arg_str_3);
					WorldDatabase.PExecute(
							"UPDATE waypoint_scripts SET %s='%s' WHERE guid='%u'",
							arg_2, arg_str_3.c_str(), id);
				}
			}
			handler->PSendSysMessage("%s%s|r|cff00ffff%u:|r|cff00ff00 %s %s|r",
					"|cff00ff00", "Waypoint script:", id, arg_2, "updated.");
		}
		return true;
	}
示例#12
0
void GuildMgr::LoadGuilds()
{
    // 1. Load all guilds
    sLog->outString("Loading guilds definitions...");
    {
        uint32 oldMSTime = getMSTime();

                                                     //          0          1       2             3              4              5              6
        QueryResult result = CharacterDatabase.Query("SELECT g.guildid, g.name, g.leaderguid, g.EmblemStyle, g.EmblemColor, g.BorderStyle, g.BorderColor, "
                                                     //   7                  8       9       10            11           12              13   14
                                                     "g.BackgroundColor, g.info, g.motd, g.createdate, g.BankMoney, COUNT(gbt.guildid), xp, level "
                                                     "FROM guild g LEFT JOIN guild_bank_tab gbt ON g.guildid = gbt.guildid GROUP BY g.guildid ORDER BY g.guildid ASC");

        if (!result)
        {
            sLog->outString(">> Loaded 0 guild definitions. DB table `guild` is empty.");
            sLog->outString();
            return;
        }
        else
        {
            uint32 count = 0;
            do
            {
                Field* fields = result->Fetch();
                Guild* guild = new Guild();

                if (!guild->LoadFromDB(fields))
                {
                    delete guild;
                    continue;
                }
                AddGuild(guild);

                ++count;
            }
            while (result->NextRow());

            sLog->outString(">> Loaded %u guild definitions in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
            sLog->outString();
        }
    }

    // 2. Load all guild ranks
    sLog->outString("Loading guild ranks...");
    {
        uint32 oldMSTime = getMSTime();

        // Delete orphaned guild rank entries before loading the valid ones
        CharacterDatabase.DirectExecute("DELETE gr FROM guild_rank gr LEFT JOIN guild g ON gr.guildId = g.guildId WHERE g.guildId IS NULL");

        //                                                         0    1      2       3                4
        QueryResult result = CharacterDatabase.Query("SELECT guildid, rid, rname, rights, BankMoneyPerDay FROM guild_rank ORDER BY guildid ASC, rid ASC");

        if (!result)
        {
            sLog->outString(">> Loaded 0 guild ranks. DB table `guild_rank` is empty.");
            sLog->outString();
        }
        else
        {
            uint32 count = 0;
            do
            {
                Field* fields = result->Fetch();
                uint32 guildId = fields[0].GetUInt32();

                if (Guild* guild = GetGuildById(guildId))
                    guild->LoadRankFromDB(fields);

                ++count;
            }
            while (result->NextRow());

            sLog->outString(">> Loaded %u guild ranks in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
            sLog->outString();
        }
    }

    // 3. Load all guild members
    sLog->outString("Loading guild members...");
    {
        uint32 oldMSTime = getMSTime();

        // Delete orphaned guild member entries before loading the valid ones
        CharacterDatabase.DirectExecute("DELETE gm FROM guild_member gm LEFT JOIN guild g ON gm.guildId = g.guildId WHERE g.guildId IS NULL");

                                                     //          0        1        2     3      4        5                   6
        QueryResult result = CharacterDatabase.Query("SELECT guildid, gm.guid, rank, pnote, offnote, BankResetTimeMoney, BankRemMoney, "
                                                     //   7                  8                 9                  10                11                 12
                                                     "BankResetTimeTab0, BankRemSlotsTab0, BankResetTimeTab1, BankRemSlotsTab1, BankResetTimeTab2, BankRemSlotsTab2, "
                                                     //   13                 14                15                 16                17                 18
                                                     "BankResetTimeTab3, BankRemSlotsTab3, BankResetTimeTab4, BankRemSlotsTab4, BankResetTimeTab5, BankRemSlotsTab5, "
                                                     //   19      20       21       22      23         24
                                                     "c.name, c.level, c.class, c.zone, c.account, c.logout_time "
                                                     "FROM guild_member gm LEFT JOIN characters c ON c.guid = gm.guid ORDER BY guildid ASC");

        if (!result)
        {
            sLog->outString(">> Loaded 0 guild members. DB table `guild_member` is empty.");
            sLog->outString();
        }
        else
        {
            uint32 count = 0;

            do
            {
                Field* fields = result->Fetch();
                uint32 guildId = fields[0].GetUInt32();

                if (Guild* guild = GetGuildById(guildId))
                    guild->LoadMemberFromDB(fields);

                ++count;
            }
            while (result->NextRow());

            sLog->outString(">> Loaded %u guild members int %u ms", count, GetMSTimeDiffToNow(oldMSTime));
            sLog->outString();
        }
    }

    // 4. Load all guild bank tab rights
    sLog->outString("Loading bank tab rights...");
    {
        uint32 oldMSTime = getMSTime();

        // Delete orphaned guild bank right entries before loading the valid ones
        CharacterDatabase.DirectExecute("DELETE gbr FROM guild_bank_right gbr LEFT JOIN guild g ON gbr.guildId = g.guildId WHERE g.guildId IS NULL");


                                                     //       0        1      2    3        4
        QueryResult result = CharacterDatabase.Query("SELECT guildid, TabId, rid, gbright, SlotPerDay FROM guild_bank_right ORDER BY guildid ASC, TabId ASC");

        if (!result)
        {
            sLog->outString(">> Loaded 0 guild bank tab rights. DB table `guild_bank_right` is empty.");
            sLog->outString();
        }
        else
        {
            uint32 count = 0;
            do
            {
                Field* fields = result->Fetch();
                uint32 guildId = fields[0].GetUInt32();

                if (Guild* guild = GetGuildById(guildId))
                    guild->LoadBankRightFromDB(fields);

                ++count;
            }
            while (result->NextRow());

            sLog->outString(">> Loaded %u bank tab rights in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
            sLog->outString();
        }
    }

    // 5. Load all event logs
    sLog->outString("Loading guild event logs...");
    {
        uint32 oldMSTime = getMSTime();

        CharacterDatabase.DirectPExecute("DELETE FROM guild_eventlog WHERE LogGuid > %u", sWorld->getIntConfig(CONFIG_GUILD_EVENT_LOG_COUNT));

                                                     //          0        1        2          3            4            5        6
        QueryResult result = CharacterDatabase.Query("SELECT guildid, LogGuid, EventType, PlayerGuid1, PlayerGuid2, NewRank, TimeStamp FROM guild_eventlog ORDER BY TimeStamp DESC, LogGuid DESC");

        if (!result)
        {
            sLog->outString(">> Loaded 0 guild event logs. DB table `guild_eventlog` is empty.");
            sLog->outString();
        }
        else
        {
            uint32 count = 0;
            do
            {
                Field* fields = result->Fetch();
                uint32 guildId = fields[0].GetUInt32();

                if (Guild* guild = GetGuildById(guildId))
                    guild->LoadEventLogFromDB(fields);

                ++count;
            }
            while (result->NextRow());

            sLog->outString(">> Loaded %u guild event logs in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
            sLog->outString();
        }
    }

    // 6. Load all bank event logs
    sLog->outString("Loading guild bank event logs...");
    {
        uint32 oldMSTime = getMSTime();

        // Remove log entries that exceed the number of allowed entries per guild
        CharacterDatabase.DirectPExecute("DELETE FROM guild_bank_eventlog WHERE LogGuid > %u", sWorld->getIntConfig(CONFIG_GUILD_BANK_EVENT_LOG_COUNT));

                                                     //          0        1      2        3          4           5            6               7          8
        QueryResult result = CharacterDatabase.Query("SELECT guildid, TabId, LogGuid, EventType, PlayerGuid, ItemOrMoney, ItemStackCount, DestTabId, TimeStamp FROM guild_bank_eventlog ORDER BY TimeStamp DESC, LogGuid DESC");

        if (!result)
        {
            sLog->outString(">> Loaded 0 guild bank event logs. DB table `guild_bank_eventlog` is empty.");
            sLog->outString();
        }
        else
        {
            uint32 count = 0;
            do
            {
                Field* fields = result->Fetch();
                uint32 guildId = fields[0].GetUInt32();

                if (Guild* guild = GetGuildById(guildId))
                    guild->LoadBankEventLogFromDB(fields);

                ++count;
            }
            while (result->NextRow());

            sLog->outString(">> Loaded %u guild bank event logs in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
            sLog->outString();
        }
    }

    // 7. Load all guild bank tabs
    sLog->outString("Loading guild bank tabs...");
    {
        uint32 oldMSTime = getMSTime();

        // Delete orphaned guild bank tab entries before loading the valid ones
        CharacterDatabase.DirectExecute("DELETE gbt FROM guild_bank_tab gbt LEFT JOIN guild g ON gbt.guildId = g.guildId WHERE g.guildId IS NULL");

                                                     //         0        1      2        3        4
        QueryResult result = CharacterDatabase.Query("SELECT guildid, TabId, TabName, TabIcon, TabText FROM guild_bank_tab ORDER BY guildid ASC, TabId ASC");

        if (!result)
        {
            sLog->outString(">> Loaded 0 guild bank tabs. DB table `guild_bank_tab` is empty.");
            sLog->outString();
        }
        else
        {
            uint32 count = 0;
            do
            {
                Field* fields = result->Fetch();
                uint32 guildId = fields[0].GetUInt32();

                if (Guild* guild = GetGuildById(guildId))
                    guild->LoadBankTabFromDB(fields);

                ++count;
            }
            while (result->NextRow());

            sLog->outString(">> Loaded %u guild bank tabs in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
            sLog->outString();
        }
    }

    // 8. Fill all guild bank tabs
    sLog->outString("Filling bank tabs with items...");
    {
        uint32 oldMSTime = getMSTime();

        // Delete orphan guild bank items
        CharacterDatabase.DirectExecute("DELETE gbi FROM guild_bank_item gbi LEFT JOIN guild g ON gbi.guildId = g.guildId WHERE g.guildId IS NULL");

                                                     //          0            1                2      3         4        5      6             7                 8           9           10
        QueryResult result = CharacterDatabase.Query("SELECT creatorGuid, giftCreatorGuid, count, duration, charges, flags, enchantments, randomPropertyId, durability, playedTime, text, "
                                                     //   11       12     13      14         15
                                                     "guildid, TabId, SlotId, item_guid, itemEntry FROM guild_bank_item gbi INNER JOIN item_instance ii ON gbi.item_guid = ii.guid");

        if (!result)
        {
            sLog->outString(">> Loaded 0 guild bank tab items. DB table `guild_bank_item` or `item_instance` is empty.");
            sLog->outString();
        }
        else
        {
            uint32 count = 0;
            do
            {
                Field* fields = result->Fetch();
                uint32 guildId = fields[11].GetUInt32();

                if (Guild* guild = GetGuildById(guildId))
                    guild->LoadBankItemFromDB(fields);

                ++count;
            }
            while (result->NextRow());

            sLog->outString(">> Loaded %u guild bank tab items in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
            sLog->outString();
        }
    }

    // 9. Validate loaded guild data
    sLog->outString("Validating data of loaded guilds...");
    {
        uint32 oldMSTime = getMSTime();

        for (GuildContainer::iterator itr = GuildStore.begin(); itr != GuildStore.end(); ++itr)
        {
            Guild* guild = itr->second;
            if (guild)
            {
                if (!guild->Validate())
                {
                    RemoveGuild(guild->GetId());
                    delete guild;
                }
            }
        }

        sLog->outString(">> Validated data of loaded guilds in %u ms", GetMSTimeDiffToNow(oldMSTime));
        sLog->outString();
    }
}
示例#13
0
void LoadDisables()
{
    uint32 oldMSTime = getMSTime();

    // reload case
    for (DisableMap::iterator itr = m_DisableMap.begin(); itr != m_DisableMap.end(); ++itr)
        itr->second.clear();

    m_DisableMap.clear();

    QueryResult result = WorldDatabase.Query("SELECT sourceType, entry, flags, params_0, params_1 FROM disables");

    uint32 total_count = 0;

    if (!result)
    {
        sLog->outString(">> Loaded 0 disables. DB table `disables` is empty!");
        sLog->outString();
        return;
    }

    Field* fields;
    do
    {
        fields = result->Fetch();
        DisableType type = DisableType(fields[0].GetUInt32());
        if (type >= MAX_DISABLE_TYPES)
        {
            sLog->outErrorDb("Invalid type %u specified in `disables` table, skipped.", type);
            continue;
        }

        uint32 entry = fields[1].GetUInt32();
        uint8 flags = fields[2].GetUInt8();
        std::string params_0 = fields[3].GetString();
        std::string params_1 = fields[4].GetString();

        DisableData data;
        data.flags = flags;

        switch (type)
        {
            case DISABLE_TYPE_GO_LOS:
                if (!sObjectMgr->GetGameObjectTemplate(entry))
                {
                    sLog->outErrorDb("Gameobject entry %u from `disables` doesn't exist in dbc, skipped.", entry);
                    continue;
                }
                if (flags)
                    sLog->outErrorDb("Disable flags specified for gameobject %u, useless data.", entry);
                break;
            case DISABLE_TYPE_SPELL:
                if (!(sSpellMgr->GetSpellInfo(entry) || flags & SPELL_DISABLE_DEPRECATED_SPELL))
                {
                    sLog->outErrorDb("Spell entry %u from `disables` doesn't exist in dbc, skipped.", entry);
                    continue;
                }

                if (!flags || flags > MAX_SPELL_DISABLE_TYPE)
                {
                    sLog->outErrorDb("Disable flags for spell %u are invalid, skipped.", entry);
                    continue;
                }

                if (flags & SPELL_DISABLE_MAP)
                {
                    Tokenizer tokens(params_0, ',');
                    for (uint8 i = 0; i < tokens.size(); )
                        data.params[0].insert(atoi(tokens[i++]));
                }

                if (flags & SPELL_DISABLE_AREA)
                {
                    Tokenizer tokens(params_1, ',');
                    for (uint8 i = 0; i < tokens.size(); )
                        data.params[1].insert(atoi(tokens[i++]));
                }

                // xinef: if spell has disabled los, add flag
                if (flags & SPELL_DISABLE_LOS)
                {
                    SpellInfo* spellInfo = const_cast<SpellInfo*>(sSpellMgr->GetSpellInfo(entry));
                    spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS;
                }

                break;
            // checked later
            case DISABLE_TYPE_QUEST:
                break;
            case DISABLE_TYPE_MAP:
            {
                MapEntry const* mapEntry = sMapStore.LookupEntry(entry);
                if (!mapEntry)
                {
                    sLog->outErrorDb("Map entry %u from `disables` doesn't exist in dbc, skipped.", entry);
                    continue;
                }
                bool isFlagInvalid = false;
                switch (mapEntry->map_type)
                {
                    case MAP_COMMON:
                        if (flags)
                            isFlagInvalid = true;
                        break;
                    case MAP_INSTANCE:
                    case MAP_RAID:
                        if (flags & DUNGEON_STATUSFLAG_HEROIC && !GetMapDifficultyData(entry, DUNGEON_DIFFICULTY_HEROIC))
                            isFlagInvalid = true;
                        else if (flags & RAID_STATUSFLAG_10MAN_HEROIC && !GetMapDifficultyData(entry, RAID_DIFFICULTY_10MAN_HEROIC))
                            isFlagInvalid = true;
                        else if (flags & RAID_STATUSFLAG_25MAN_HEROIC && !GetMapDifficultyData(entry, RAID_DIFFICULTY_25MAN_HEROIC))
                            isFlagInvalid = true;
                        break;
                    case MAP_BATTLEGROUND:
                    case MAP_ARENA:
                        sLog->outErrorDb("Battleground map %u specified to be disabled in map case, skipped.", entry);
                        continue;
                }
                if (isFlagInvalid)
                {
                    sLog->outErrorDb("Disable flags for map %u are invalid, skipped.", entry);
                    continue;
                }
                break;
            }
            case DISABLE_TYPE_BATTLEGROUND:
                if (!sBattlemasterListStore.LookupEntry(entry))
                {
                    sLog->outErrorDb("Battleground entry %u from `disables` doesn't exist in dbc, skipped.", entry);
                    continue;
                }
                if (flags)
                    sLog->outErrorDb("Disable flags specified for battleground %u, useless data.", entry);
                break;
            case DISABLE_TYPE_OUTDOORPVP:
                if (entry > MAX_OUTDOORPVP_TYPES)
                {
                    sLog->outErrorDb("OutdoorPvPTypes value %u from `disables` is invalid, skipped.", entry);
                    continue;
                }
                if (flags)
                    sLog->outErrorDb("Disable flags specified for outdoor PvP %u, useless data.", entry);
                break;
            case DISABLE_TYPE_ACHIEVEMENT_CRITERIA:
                if (!sAchievementCriteriaStore.LookupEntry(entry))
                {
                    sLog->outErrorDb("Achievement Criteria entry %u from `disables` doesn't exist in dbc, skipped.", entry);
                    continue;
                }
                if (flags)
                    sLog->outErrorDb("Disable flags specified for Achievement Criteria %u, useless data.", entry);
                break;
            case DISABLE_TYPE_VMAP:
            {
                MapEntry const* mapEntry = sMapStore.LookupEntry(entry);
                if (!mapEntry)
                {
                    sLog->outErrorDb("Map entry %u from `disables` doesn't exist in dbc, skipped.", entry);
                    continue;
                }
                switch (mapEntry->map_type)
                {
                    case MAP_COMMON:
                        if (flags & VMAP_DISABLE_AREAFLAG)
                            sLog->outString("Areaflag disabled for world map %u.", entry);
                        if (flags & VMAP_DISABLE_LIQUIDSTATUS)
                            sLog->outString("Liquid status disabled for world map %u.", entry);
                        break;
                    case MAP_INSTANCE:
                    case MAP_RAID:
                        if (flags & VMAP_DISABLE_HEIGHT)
                            sLog->outString("Height disabled for instance map %u.", entry);
                        if (flags & VMAP_DISABLE_LOS)
                            sLog->outString("LoS disabled for instance map %u.", entry);
                        break;
                    case MAP_BATTLEGROUND:
                        if (flags & VMAP_DISABLE_HEIGHT)
                            sLog->outString("Height disabled for battleground map %u.", entry);
                        if (flags & VMAP_DISABLE_LOS)
                            sLog->outString("LoS disabled for battleground map %u.", entry);
                        break;
                    case MAP_ARENA:
                        if (flags & VMAP_DISABLE_HEIGHT)
                            sLog->outString("Height disabled for arena map %u.", entry);
                        if (flags & VMAP_DISABLE_LOS)
                            sLog->outString("LoS disabled for arena map %u.", entry);
                        break;
                    default:
                        break;
                }
                break;
            }
            default:
                break;
        }

        m_DisableMap[type].insert(DisableTypeMap::value_type(entry, data));
        ++total_count;
    }
    while (result->NextRow());

    sLog->outString(">> Loaded %u disables in %u ms", total_count, GetMSTimeDiffToNow(oldMSTime));
    sLog->outString();
}
示例#14
0
void WorldSession::SendAuthResponse(uint8 code, bool queued, uint32 queuePos)
{   
    QueryResult classResult = LoginDatabase.PQuery("SELECT class, expansion FROM realm_classes WHERE realmId = %u", realmID);
    QueryResult raceResult = LoginDatabase.PQuery("SELECT race, expansion FROM realm_races WHERE realmId = %u", realmID);

    if (!classResult || !raceResult)
    {
        TC_LOG_ERROR("network", "Unable to retrieve class or race data.");
        return;
    }

    TC_LOG_ERROR("network", "SMSG_AUTH_RESPONSE");
    WorldPacket packet(SMSG_AUTH_RESPONSE, 80);
    
    packet.WriteBit(code == AUTH_OK);

    if (code == AUTH_OK)
    {
        packet.WriteBits(0, 21);
        packet.WriteBit(0);
        packet.WriteBits(raceResult->GetRowCount(), 23);
        packet.WriteBits(0, 21);
        packet.WriteBit(0);
        packet.WriteBits(classResult->GetRowCount(), 23);
        packet.WriteBit(0);
        packet.WriteBit(0);
        packet.WriteBit(0);
    }

    packet.WriteBit(queued);

    if (queued)
        packet.WriteBit(1);                             // Unknown

    packet.FlushBits();

    if (queued)
        packet << uint32(0);                            // Unknown

    if (code == AUTH_OK)
    {
        do
        {
            Field* fields = classResult->Fetch();
            
            packet << fields[1].GetUInt8();
            packet << fields[0].GetUInt8();
        } 
        while (classResult->NextRow());

        packet << uint8(Expansion());
        
        do
        {
            Field* fields = raceResult->Fetch();
            
            packet << fields[1].GetUInt8();
            packet << fields[0].GetUInt8();
        } 
        while (raceResult->NextRow());

        packet << uint32(Expansion());

        packet << uint32(0);
        packet << uint32(0);
        packet << uint32(0);
        packet << uint32(0);

        packet << uint8(Expansion());
        packet << uint32(0);
    }
    packet << uint8(code);                             // Auth response ?

    SendPacket(&packet);
}
示例#15
0
void WorldSession::HandleTurnInPetitionOpcode(WorldPacket & recv_data)
{
    sLog.outDebug("Received opcode CMSG_TURN_IN_PETITION"); // ok
    //recv_data.hexlike();

    WorldPacket data;
    uint64 petitionguid;

    uint32 ownerguidlo;
    uint32 type;
    std::string name;

    recv_data >> petitionguid;

    sLog.outDebug("Petition %u turned in by %u", GUID_LOPART(petitionguid), _player->GetGUIDLow());

    // data
    QueryResult *result = CharacterDatabase.PQuery("SELECT ownerguid, name, type FROM petition WHERE petitionguid = '%u'", GUID_LOPART(petitionguid));
    if(result)
    {
        Field *fields = result->Fetch();
        ownerguidlo = fields[0].GetUInt32();
        name = fields[1].GetCppString();
        type = fields[2].GetUInt32();
        delete result;
    }
    else
    {
        sLog.outError("petition table has broken data!");
        return;
    }

    if(type == 9)
    {
        if(_player->GetGuildId())
        {
            data.Initialize(SMSG_TURN_IN_PETITION_RESULTS, 4);
            data << (uint32)PETITION_TURN_ALREADY_IN_GUILD; // already in guild
            _player->GetSession()->SendPacket(&data);
            return;
        }
    }
    else
    {
        uint8 slot = ArenaTeam::GetSlotByType(type);
        if(slot >= MAX_ARENA_SLOT)
            return;

        if(_player->GetArenaTeamId(slot))
        {
            //data.Initialize(SMSG_TURN_IN_PETITION_RESULTS, 4);
            //data << (uint32)PETITION_TURN_ALREADY_IN_GUILD;                          // already in guild
            //_player->GetSession()->SendPacket(&data);
            SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, name, "", ERR_ALREADY_IN_ARENA_TEAM);
            return;
        }
    }

    if(_player->GetGUIDLow() != ownerguidlo)
        return;

    // signs
    uint8 signs;
    result = CharacterDatabase.PQuery("SELECT playerguid FROM petition_sign WHERE petitionguid = '%u'", GUID_LOPART(petitionguid));
    if(result)
        signs = result->GetRowCount();
    else
        signs = 0;

    uint32 count;
    //if(signs < sWorld.getConfig(CONFIG_MIN_PETITION_SIGNS))
    if(type == 9)
        count = sWorld.getConfig(CONFIG_MIN_PETITION_SIGNS);
    else
        count = type-1;
    if(signs < count)
    {
        data.Initialize(SMSG_TURN_IN_PETITION_RESULTS, 4);
        data << (uint32)PETITION_TURN_NEED_MORE_SIGNATURES; // need more signatures...
        SendPacket(&data);
        delete result;
        return;
    }

    if(type == 9)
    {
        if(objmgr.GetGuildByName(name))
        {
            SendGuildCommandResult(GUILD_CREATE_S, name, GUILD_NAME_EXISTS);
            delete result;
            return;
        }
    }
    else
    {
        if(objmgr.GetArenaTeamByName(name))
        {
            SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, name, "", ERR_ARENA_TEAM_NAME_EXISTS_S);
            delete result;
            return;
        }
    }

    // and at last charter item check
    Item *item = _player->GetItemByGuid(petitionguid);
    if(!item)
    {
        delete result;
        return;
    }

    // OK!

    // delete charter item
    _player->DestroyItem(item->GetBagSlot(),item->GetSlot(), true);

    if(type == 9)                                           // create guild
    {
        Guild* guild = new Guild;
        if(!guild->Create(_player, name))
        {
            delete guild;
            delete result;
            return;
        }

        // register guild and add guildmaster
        objmgr.AddGuild(guild);

        // add members
        for(uint8 i = 0; i < signs; ++i)
        {
            Field* fields = result->Fetch();
            guild->AddMember(fields[0].GetUInt64(), guild->GetLowestRank());
            result->NextRow();
        }
    }
    else                                                    // or arena team
    {
        ArenaTeam* at = new ArenaTeam;
        if(!at->Create(_player->GetGUID(), type, name))
        {
            sLog.outError("PetitionsHandler: arena team create failed.");
            delete at;
            delete result;
            return;
        }

        uint32 icon, iconcolor, border, bordercolor, backgroud;
        recv_data >> backgroud >> icon >> iconcolor >> border >> bordercolor;

        at->SetEmblem(backgroud, icon, iconcolor, border, bordercolor);

        // register team and add captain
        objmgr.AddArenaTeam(at);
        sLog.outDebug("PetitonsHandler: arena team added to objmrg");

        // add members
        for(uint8 i = 0; i < signs; ++i)
        {
            Field* fields = result->Fetch();
            uint64 memberGUID = fields[0].GetUInt64();
            sLog.outDebug("PetitionsHandler: adding arena member %u", GUID_LOPART(memberGUID));
            at->AddMember(memberGUID);
            result->NextRow();
        }
    }

    delete result;

    CharacterDatabase.BeginTransaction();
    CharacterDatabase.PExecute("DELETE FROM petition WHERE petitionguid = '%u'", GUID_LOPART(petitionguid));
    CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE petitionguid = '%u'", GUID_LOPART(petitionguid));
    CharacterDatabase.CommitTransaction();

    // created
    sLog.outDebug("TURN IN PETITION GUID %u", GUID_LOPART(petitionguid));

    data.Initialize(SMSG_TURN_IN_PETITION_RESULTS, 4);
    data << (uint32)PETITION_TURN_OK;
    SendPacket(&data);
}
示例#16
0
文件: system.cpp 项目: Bootz/TC-One
void SystemMgr::LoadScriptWaypoints()
{
    // Drop Existing Waypoint list
    m_mPointMoveMap.clear();

    uint64 uiCreatureCount = 0;

    // Load Waypoints
    QueryResult* pResult = TScriptDB.PQuery("SELECT COUNT(entry) FROM script_waypoint GROUP BY entry");
    if (pResult)
    {
        uiCreatureCount = pResult->GetRowCount();
        delete pResult;
    }

    outstring_log("TSCR: Loading Script Waypoints for %u creature(s)...", uiCreatureCount);

    pResult = TScriptDB.PQuery("SELECT entry, pointid, location_x, location_y, location_z, waittime FROM script_waypoint ORDER BY pointid");

    if (pResult)
    {
        barGoLink bar(pResult->GetRowCount());
        uint32 uiNodeCount = 0;

        do
        {
            bar.step();
            Field* pFields = pResult->Fetch();
            ScriptPointMove pTemp;

            pTemp.uiCreatureEntry   = pFields[0].GetUInt32();
            uint32 uiEntry          = pTemp.uiCreatureEntry;
            pTemp.uiPointId         = pFields[1].GetUInt32();
            pTemp.fX                = pFields[2].GetFloat();
            pTemp.fY                = pFields[3].GetFloat();
            pTemp.fZ                = pFields[4].GetFloat();
            pTemp.uiWaitTime        = pFields[5].GetUInt32();

            CreatureInfo const* pCInfo = GetCreatureTemplateStore(pTemp.uiCreatureEntry);

            if (!pCInfo)
            {
                error_db_log("TSCR: DB table script_waypoint has waypoint for non-existant creature entry %u", pTemp.uiCreatureEntry);
                continue;
            }

            if (!pCInfo->ScriptID)
                error_db_log("TSCR: DB table script_waypoint has waypoint for creature entry %u, but creature does not have ScriptName defined and then useless.", pTemp.uiCreatureEntry);

            m_mPointMoveMap[uiEntry].push_back(pTemp);
            ++uiNodeCount;
        } while (pResult->NextRow());

        delete pResult;

        outstring_log("");
        outstring_log(">> Loaded %u Script Waypoint nodes.", uiNodeCount);
    }
    else
    {
        barGoLink bar(1);
        bar.step();
        outstring_log("");
        outstring_log(">> Loaded 0 Script Waypoints. DB table `script_waypoint` is empty.");
    }
}
示例#17
0
void FormationMgr::LoadCreatureFormations()
{
    uint32 oldMSTime = getMSTime();

    for (CreatureGroupInfoType::iterator itr = CreatureGroupMap.begin(); itr != CreatureGroupMap.end(); ++itr) // for reload case
        delete itr->second;
    CreatureGroupMap.clear();

    //Get group data
    QueryResult result = WorldDatabase.Query("SELECT leaderGUID, memberGUID, dist, angle, groupAI FROM creature_formations ORDER BY leaderGUID");

    if (!result)
    {
        sLog->outErrorDb(">>  Loaded 0 creatures in formations. DB table `creature_formations` is empty!");
        sLog->outString();
        return;
    }

    uint32 count = 0;
    Field* fields;
    FormationInfo* group_member;

    do
    {
        fields = result->Fetch();

        //Load group member data
        group_member                        = new FormationInfo();
        group_member->leaderGUID            = fields[0].GetUInt32();
        uint32 memberGUID                   = fields[1].GetUInt32();
        group_member->groupAI               = fields[4].GetUInt32();
        //If creature is group leader we may skip loading of dist/angle
        if (group_member->leaderGUID != memberGUID)
        {
            group_member->follow_dist       = fields[2].GetFloat();
            group_member->follow_angle      = fields[3].GetFloat() * M_PI / 180;
        }
        else
        {
            group_member->follow_dist       = 0;
            group_member->follow_angle      = 0;
        }

        // check data correctness
        {
            if (!sObjectMgr->GetCreatureData(group_member->leaderGUID))
            {
                sLog->outErrorDb("creature_formations table leader guid %u incorrect (not exist)", group_member->leaderGUID);
                delete group_member;
                continue;
            }

            if (!sObjectMgr->GetCreatureData(memberGUID))
            {
                sLog->outErrorDb("creature_formations table member guid %u incorrect (not exist)", memberGUID);
                delete group_member;
                continue;
            }
        }

        CreatureGroupMap[memberGUID] = group_member;
        ++count;
    }
    while (result->NextRow());

    sLog->outString(">> Loaded %u creatures in formations in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
    sLog->outString();
}
示例#18
0
文件: system.cpp 项目: Bootz/TC-One
void SystemMgr::LoadScriptTexts()
{
    outstring_log("TSCR: Loading Script Texts...");
    LoadTrinityStrings(TScriptDB,"script_texts",TEXT_SOURCE_RANGE,1+(TEXT_SOURCE_RANGE*2));

    QueryResult* pResult = TScriptDB.PQuery("SELECT entry, sound, type, language, emote FROM script_texts");

    outstring_log("TSCR: Loading Script Texts additional data...");

    if (pResult)
    {
        barGoLink bar(pResult->GetRowCount());
        uint32 uiCount = 0;

        do
        {
            bar.step();
            Field* pFields = pResult->Fetch();
            StringTextData pTemp;

            int32 iId           = pFields[0].GetInt32();
            pTemp.uiSoundId     = pFields[1].GetUInt32();
            pTemp.uiType        = pFields[2].GetUInt32();
            pTemp.uiLanguage    = pFields[3].GetUInt32();
            pTemp.uiEmote       = pFields[4].GetUInt32();

            if (iId >= 0)
            {
                error_db_log("TSCR: Entry %i in table `script_texts` is not a negative value.", iId);
                continue;
            }

            if (iId > TEXT_SOURCE_RANGE || iId <= TEXT_SOURCE_RANGE*2)
            {
                error_db_log("TSCR: Entry %i in table `script_texts` is out of accepted entry range for table.", iId);
                continue;
            }

            if (pTemp.uiSoundId)
            {
                if (!GetSoundEntriesStore()->LookupEntry(pTemp.uiSoundId))
                    error_db_log("TSCR: Entry %i in table `script_texts` has soundId %u but sound does not exist.", iId, pTemp.uiSoundId);
            }

            if (!GetLanguageDescByID(pTemp.uiLanguage))
                error_db_log("TSCR: Entry %i in table `script_texts` using Language %u but Language does not exist.", iId, pTemp.uiLanguage);

            if (pTemp.uiType > CHAT_TYPE_ZONE_YELL)
                error_db_log("TSCR: Entry %i in table `script_texts` has Type %u but this Chat Type does not exist.", iId, pTemp.uiType);

            m_mTextDataMap[iId] = pTemp;
            ++uiCount;
        } while (pResult->NextRow());

        outstring_log("");
        outstring_log(">> Loaded %u additional Script Texts data.", uiCount);
    }
    else
    {
        barGoLink bar(1);
        bar.step();
        outstring_log("");
        outstring_log(">> Loaded 0 additional Script Texts data. DB table `script_texts` is empty.");
    }
}
示例#19
0
void WorldSession::HandlePetitionRenameOpcode(WorldPacket & recv_data)
{
    sLog->outDebug(LOG_FILTER_NETWORKIO, "Received opcode MSG_PETITION_RENAME");   // ok

    uint64 petitionguid;
    uint32 type;
    std::string newname;

    recv_data >> petitionguid;                              // guid
    recv_data >> newname;                                   // new name

    Item *item = _player->GetItemByGuid(petitionguid);
    if (!item)
        return;

    QueryResult result = CharacterDatabase.PQuery("SELECT type FROM petition WHERE petitionguid = '%u'", GUID_LOPART(petitionguid));

    if (result)
    {
        Field* fields = result->Fetch();
        type = fields[0].GetUInt8();
    }
    else
    {
        sLog->outDebug(LOG_FILTER_NETWORKIO, "CMSG_PETITION_QUERY failed for petition (GUID: %u)", GUID_LOPART(petitionguid));
        return;
    }

    if (type == GUILD_CHARTER_TYPE)
    {
        if (sGuildMgr->GetGuildByName(newname))
        {
            Guild::SendCommandResult(this, GUILD_CREATE_S, ERR_GUILD_NAME_EXISTS_S, newname);
            return;
        }
        if (sObjectMgr->IsReservedName(newname) || !ObjectMgr::IsValidCharterName(newname))
        {
            Guild::SendCommandResult(this, GUILD_CREATE_S, ERR_GUILD_NAME_INVALID, newname);
            return;
        }
    }
    else
    {
        if (sArenaTeamMgr->GetArenaTeamByName(newname))
        {
            SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, newname, "", ERR_ARENA_TEAM_NAME_EXISTS_S);
            return;
        }
        if (sObjectMgr->IsReservedName(newname) || !ObjectMgr::IsValidCharterName(newname))
        {
            SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, newname, "", ERR_ARENA_TEAM_NAME_INVALID);
            return;
        }
    }

    std::string db_newname = newname;
    CharacterDatabase.EscapeString(db_newname);
    CharacterDatabase.PExecute("UPDATE petition SET name = '%s' WHERE petitionguid = '%u'",
        db_newname.c_str(), GUID_LOPART(petitionguid));

    sLog->outDebug(LOG_FILTER_NETWORKIO, "Petition (GUID: %u) renamed to '%s'", GUID_LOPART(petitionguid), newname.c_str());
    WorldPacket data(MSG_PETITION_RENAME, (8+newname.size()+1));
    data << uint64(petitionguid);
    data << newname;
    SendPacket(&data);
}
示例#20
0
void AuthSocket::LoadRealmlist(ByteBuffer &pkt, uint32 acctid)
{
    switch(_build)
    {
        case 5875:                                          // 1.12.1
        case 6005:                                          // 1.12.2
        {
            pkt << uint32(0);
            pkt << uint8(sRealmList.size());

            for(RealmList::RealmMap::const_iterator  i = sRealmList.begin(); i != sRealmList.end(); ++i)
            {
                uint8 AmountOfCharacters;

                // No SQL injection. id of realm is controlled by the database.
                QueryResult *result = loginDatabase.PQuery( "SELECT numchars FROM realmcharacters WHERE realmid = '%d' AND acctid='%u'", i->second.m_ID, acctid);
                if( result )
                {
                    Field *fields = result->Fetch();
                    AmountOfCharacters = fields[0].GetUInt8();
                    delete result;
                }
                else
                    AmountOfCharacters = 0;

                // Show offline state for unsupported client builds
                uint8 color = (std::find(i->second.realmbuilds.begin(), i->second.realmbuilds.end(), _build) != i->second.realmbuilds.end()) ? i->second.color : 2;
                color = (i->second.allowedSecurityLevel > _accountSecurityLevel) ? 2 : color;

                pkt << uint32(i->second.icon);                      // realm type
                pkt << uint8(color);                                // if 2, then realm is offline
                pkt << i->first;                                    // name
                pkt << i->second.address;                           // address
                pkt << float(i->second.populationLevel);
                pkt << uint8(AmountOfCharacters);
                pkt << uint8(i->second.timezone);                   // realm category
                pkt << uint8(0x00);                                 // unk, may be realm number/id?
            }

            pkt << uint8(0x00);
            pkt << uint8(0x02);
            break;
        }

        case 8606:                                          // 2.4.3
        case 10505:                                         // 3.2.2a
        case 11159:                                         // 3.3.0a
        case 11403:                                         // 3.3.2
        default:                                            // and later
        {
            pkt << uint32(0);
            pkt << uint16(sRealmList.size());

            for(RealmList::RealmMap::const_iterator  i = sRealmList.begin(); i != sRealmList.end(); ++i)
            {
                uint8 AmountOfCharacters;

                // No SQL injection. id of realm is controlled by the database.
                QueryResult *result = loginDatabase.PQuery( "SELECT numchars FROM realmcharacters WHERE realmid = '%d' AND acctid='%u'", i->second.m_ID, acctid);
                if( result )
                {
                    Field *fields = result->Fetch();
                    AmountOfCharacters = fields[0].GetUInt8();
                    delete result;
                }
                else
                    AmountOfCharacters = 0;

                uint8 lock = (i->second.allowedSecurityLevel > _accountSecurityLevel) ? 1 : 0;

                // Show offline state for unsupported client builds
                uint8 color = (std::find(i->second.realmbuilds.begin(), i->second.realmbuilds.end(), _build) != i->second.realmbuilds.end()) ? i->second.color : 2;

                pkt << uint8(i->second.icon);                       // realm type
                pkt << uint8(lock);                                 // if 1, then realm locked
                pkt << uint8(color);                                // if 2, then realm is offline
                pkt << i->first;                                    // name
                pkt << i->second.address;                           // address
                pkt << float(i->second.populationLevel);
                pkt << uint8(AmountOfCharacters);
                pkt << uint8(i->second.timezone);                   // realm category
                pkt << uint8(0x2C);                                 // unk, may be realm number/id?
            }

            pkt << uint8(0x10);
            pkt << uint8(0x00);
            break;
        }
    }
}
示例#21
0
void WorldSession::HandleOfferPetitionOpcode(WorldPacket & recv_data)
{
    sLog->outDebug(LOG_FILTER_NETWORKIO, "Received opcode CMSG_OFFER_PETITION");   // ok

    uint8 signs = 0;
    uint64 petitionguid, plguid;
    uint32 type, junk;
    Player* player;
    recv_data >> junk;                                      // this is not petition type!
    recv_data >> petitionguid;                              // petition guid
    recv_data >> plguid;                                    // player guid

    player = ObjectAccessor::FindPlayer(plguid);
    if (!player)
        return;

    QueryResult result = CharacterDatabase.PQuery("SELECT type FROM petition WHERE petitionguid = '%u'", GUID_LOPART(petitionguid));
    if (!result)
        return;

    Field *fields = result->Fetch();
    type = fields[0].GetUInt8();

    sLog->outDebug(LOG_FILTER_NETWORKIO, "OFFER PETITION: type %u, GUID1 %u, to player id: %u", type, GUID_LOPART(petitionguid), GUID_LOPART(plguid));

    if (!sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_GUILD) && GetPlayer()->GetTeam() != player->GetTeam())
    {
        if (type != GUILD_CHARTER_TYPE)
            SendArenaTeamCommandResult(ERR_ARENA_TEAM_INVITE_SS, "", "", ERR_ARENA_TEAM_NOT_ALLIED);
        else
            Guild::SendCommandResult(this, GUILD_CREATE_S, ERR_GUILD_NOT_ALLIED);
        return;
    }

    if (type != GUILD_CHARTER_TYPE)
    {
        if (player->getLevel() < sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL))
        {
            // player is too low level to join an arena team
            SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, player->GetName(), "", ERR_ARENA_TEAM_TARGET_TOO_LOW_S);
            return;
        }

        uint8 slot = ArenaTeam::GetSlotByType(type);
        if (slot >= MAX_ARENA_SLOT)
            return;

        if (player->GetArenaTeamId(slot))
        {
            // player is already in an arena team
            SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, player->GetName(), "", ERR_ALREADY_IN_ARENA_TEAM_S);
            return;
        }

        if (player->GetArenaTeamIdInvited())
        {
            SendArenaTeamCommandResult(ERR_ARENA_TEAM_INVITE_SS, "", _player->GetName(), ERR_ALREADY_INVITED_TO_ARENA_TEAM_S);
            return;
        }
    }
    else
    {
        if (player->GetGuildId())
        {
            Guild::SendCommandResult(this, GUILD_INVITE_S, ERR_ALREADY_IN_GUILD_S, _player->GetName());
            return;
        }

        if (player->GetGuildIdInvited())
        {
            Guild::SendCommandResult(this, GUILD_INVITE_S, ERR_ALREADY_INVITED_TO_GUILD_S, _player->GetName());
            return;
        }
    }

    result = CharacterDatabase.PQuery("SELECT playerguid FROM petition_sign WHERE petitionguid = '%u'", GUID_LOPART(petitionguid));
    // result == NULL also correct charter without signs
    if (result)
        signs = uint8(result->GetRowCount());

    WorldPacket data(SMSG_PETITION_SHOW_SIGNATURES, (8+8+4+signs+signs*12));
    data << uint64(petitionguid);                           // petition guid
    data << uint64(_player->GetGUID());                     // owner guid
    data << uint32(GUID_LOPART(petitionguid));              // guild guid
    data << uint8(signs);                                   // sign's count

    for (uint8 i = 1; i <= signs; ++i)
    {
        Field *fields2 = result->Fetch();
        plguid = fields2[0].GetUInt64();

        data << uint64(plguid);                             // Player GUID
        data << uint32(0);                                  // there 0 ...

        result->NextRow();
    }

    player->GetSession()->SendPacket(&data);
}
示例#22
0
void OutdoorPvPMgr::InitOutdoorPvP()
{
    uint32 oldMSTime = getMSTime();

    //                                                 0       1
    QueryResult result = WorldDatabase.Query("SELECT TypeId, ScriptName FROM outdoorpvp_template");

    if (!result)
    {
        TC_LOG_ERROR("server.loading", ">> Loaded 0 outdoor PvP definitions. DB table `outdoorpvp_template` is empty.");
        return;
    }

    uint32 count = 0;
    uint32 typeId = 0;

    do
    {
        Field* fields = result->Fetch();

        typeId = fields[0].GetUInt8();

        if (DisableMgr::IsDisabledFor(DISABLE_TYPE_OUTDOORPVP, typeId, NULL))
            continue;

        if (typeId >= MAX_OUTDOORPVP_TYPES)
        {
            TC_LOG_ERROR("sql.sql", "Invalid OutdoorPvPTypes value %u in outdoorpvp_template; skipped.", typeId);
            continue;
        }

        OutdoorPvPData* data = new OutdoorPvPData();
        OutdoorPvPTypes realTypeId = OutdoorPvPTypes(typeId);
        data->TypeId = realTypeId;
        data->ScriptId = sObjectMgr->GetScriptId(fields[1].GetCString());
        m_OutdoorPvPDatas[realTypeId] = data;

        ++count;
    }
    while (result->NextRow());

    OutdoorPvP* pvp;
    for (uint8 i = 1; i < MAX_OUTDOORPVP_TYPES; ++i)
    {
        OutdoorPvPDataMap::iterator iter = m_OutdoorPvPDatas.find(OutdoorPvPTypes(i));
        if (iter == m_OutdoorPvPDatas.end())
        {
            TC_LOG_ERROR("sql.sql", "Could not initialize OutdoorPvP object for type ID %u; no entry in database.", uint32(i));
            continue;
        }

        pvp = sScriptMgr->CreateOutdoorPvP(iter->second);
        if (!pvp)
        {
            TC_LOG_ERROR("outdoorpvp", "Could not initialize OutdoorPvP object for type ID %u; got NULL pointer from script.", uint32(i));
            continue;
        }

        if (!pvp->SetupOutdoorPvP())
        {
            TC_LOG_ERROR("outdoorpvp", "Could not initialize OutdoorPvP object for type ID %u; SetupOutdoorPvP failed.", uint32(i));
            delete pvp;
            continue;
        }

        m_OutdoorPvPSet.push_back(pvp);
    }

    TC_LOG_INFO("server.loading", ">> Loaded %u outdoor PvP definitions in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
}
示例#23
0
        void UpdateAI(const uint32 diff)
        {
            if (IsEventActive(EVENT_LOTTERY))
            {
                if (me->IsVisible())
                {
                    QueryResult qMaxID = WorldDatabase.Query("SELECT MAX(id) FROM lottery_bets");
                    if (!qMaxID)
                        return;

                    uint32 betMaxID = qMaxID->Fetch()->GetUInt32();
                    uint32 luckyNumber[5];
                    uint32 lotteryID;
                    uint32 jackpotWinners = 0;

                    QueryResult qlotteryID = WorldDatabase.Query("SELECT MAX(id) FROM lottery");
                    if (!qlotteryID)
                        lotteryID = 0;
                    else
                        lotteryID = qlotteryID->Fetch()->GetUInt32();

                    QueryResult qBets  = WorldDatabase.Query("SELECT guid, bet, name FROM lottery_bets");
                    if (qBets)
                    {
                        for (int8 n = 0; n < 5; ++n)
                        {
                            luckyNumber[n] = urand(1, sConfig->GetIntDefault("Lottery.MaxNumber", 30));
                        }

                        do
                        {
                            Field *fBets = qBets->Fetch();
                            uint32 guid = fBets[0].GetUInt32();
                            std::string bet = fBets[1].GetString();
                            std::string rBet = bet; 
                            std::string name = fBets[2].GetString();
                            uint32 points = 0;
                            uint32 cash;

                            int32 number[5];
                            char * tmp;

                            tmp = strtok ((char*)bet.c_str()," ");

                            for (int8 n = 0; n < 5; ++n)
                            {
                                if (tmp != NULL)
                                {
                                    number[n] = atoi(tmp);
                                    tmp = strtok (NULL, " ");
                                }
                            }

                            for (int8 n = 0; n < 5; ++n)
                            {
                                for (int8 i = 0; i < 5; ++i)
                                {
                                    if (number[n] == luckyNumber[i])
                                        ++points;
                                }
                            }

                            switch (points)
                            {
                                case 1:
                                {
                                    cash = uint32(betMaxID * sConfig->GetIntDefault("Lottery.BetCost", 500000) * 0.005f);
                                    break;
                                }
                                case 2:
                                {
                                    cash = uint32(betMaxID * sConfig->GetIntDefault("Lottery.BetCost", 500000) * 0.01f);
                                    break;
                                }
                                case 3:
                                {
                                    cash = uint32(betMaxID * sConfig->GetIntDefault("Lottery.BetCost", 500000) * 0.05f);
                                    break;
                                }
                                case 4:
                                {
                                    cash = uint32(betMaxID * sConfig->GetIntDefault("Lottery.BetCost", 500000) * 0.2f);
                                    break;
                                }
                                case 5:
                                {
                                    WorldDatabase.PExecute("INSERT INTO lottery_winners (id, name, guid, bet, betPoints) VALUES ('%u', '%s', '%u', '%s', '%u')", lotteryID+1, name.c_str(), guid, rBet.c_str(), points);
                                    ++jackpotWinners;
                                    continue;
                                }
                                default:
                                    continue;
                            }

                            Player *pWinner = sObjectMgr->GetPlayerByLowGUID(guid);
                            SQLTransaction trans = CharacterDatabase.BeginTransaction();
                            MailDraft("Выигрыш", "Поздравляем! Ваша комбинация чисел оказалась счастливой!")
                                .AddMoney(cash)
                                .SendMailTo(trans, MailReceiver(pWinner, GUID_LOPART(guid)), MailSender(MAIL_NORMAL, 0, MAIL_STATIONERY_GM));
                            CharacterDatabase.CommitTransaction(trans);

                            WorldDatabase.PExecute("INSERT INTO lottery_winners (id, name, guid, bet, betPoints) VALUES ('%u', '%s', '%u', '%s', '%u')", lotteryID+1, name.c_str(), guid, rBet.c_str(), points);
                        } while (qBets->NextRow());
                        uint64 jackpot;
                        uint64 rJackpot;
                        uint64 defJackpot = uint64(betMaxID * sConfig->GetIntDefault("Lottery.BetCost", 500000) * 0.7f);
                        QueryResult qJackpot  = WorldDatabase.PQuery("SELECT jackpot FROM lottery WHERE id = '%u'", lotteryID);
                        if (qJackpot)
                            jackpot = qJackpot->Fetch()->GetUInt32();
                        else
                            jackpot = 0;

                        rJackpot = jackpot;

                        if (jackpotWinners > 0)
                        {
                            QueryResult qJackpotWinners = WorldDatabase.PQuery("SELECT guid FROM lottery_winners WHERE betPoints = '5' and id = '%u'", lotteryID+1);
                            QueryResult qJackpotWinnersName;
                            if (jackpotWinners == 1)
                                qJackpotWinnersName = WorldDatabase.PQuery("SELECT name FROM lottery_winners WHERE betPoints = '5' and id = '%u'", lotteryID+1);

                            if (qJackpotWinners)
                            {
                                jackpot = uint64(jackpot / jackpotWinners);
                                do
                                {
                                    Field *fJackpotWinners = qJackpotWinners->Fetch();
                                    uint32 JPguid = fJackpotWinners[0].GetUInt32();

                                    Player *pJPWinner = sObjectMgr->GetPlayerByLowGUID(JPguid);
                                    SQLTransaction trans = CharacterDatabase.BeginTransaction();
                                    MailDraft("Джекпот!", "Вау! Да Вы просто везунчик! Вам удалось сорвать джекпот! Примите поздравление от организаторов лотареи")
                                        .AddMoney(jackpot = 0 ? uint64(betMaxID * sConfig->GetIntDefault("Lottery.BetCost", 500000) * 0.7f) : jackpot)
                                        .SendMailTo(trans, MailReceiver(pJPWinner, GUID_LOPART(JPguid)), MailSender(MAIL_NORMAL, 0, MAIL_STATIONERY_GM));
                                    CharacterDatabase.CommitTransaction(trans);
                                } while (qJackpotWinners->NextRow());
                            }

                            if (jackpotWinners == 1 && qJackpotWinnersName)
                            {
                                std::string wName = qJackpotWinnersName->Fetch()->GetString();
                                sWorld->SendWorldText(LANG_LOTTERY_ANNOUNCE_JACKPOT, betMaxID, luckyNumber[0], luckyNumber[1], luckyNumber[2], luckyNumber[3], luckyNumber[4], ((jackpot = 0 ? uint64(betMaxID * sConfig->GetIntDefault("Lottery.BetCost", 500000) * 0.7f) : rJackpot) * 0.0001f), wName.c_str());
                            }
                            else
                                sWorld->SendWorldText(LANG_LOTTERY_ANNOUNCE_JACKPOT_M_PLAYERS, betMaxID, luckyNumber[0], luckyNumber[1], luckyNumber[2], luckyNumber[3], luckyNumber[4], ((jackpot = 0 ? uint64(betMaxID * sConfig->GetIntDefault("Lottery.BetCost", 500000) * 0.7f) : rJackpot) * 0.0001f), jackpotWinners);

                            WorldDatabase.PExecute("INSERT INTO lottery (number_1, number_2, number_3, number_4, number_5, jackpot) VALUES ('%u', '%u', '%u', '%u', '%u', '%u')", luckyNumber[0], luckyNumber[1], luckyNumber[2], luckyNumber[3], luckyNumber[4], defJackpot);
                        }
                        else
                        {
                            sWorld->SendWorldText(LANG_LOTTERY_ANNOUNCE, betMaxID, luckyNumber[0], luckyNumber[1], luckyNumber[2], luckyNumber[3], luckyNumber[4], ((jackpot + defJackpot) * 0.0001f));
                            WorldDatabase.PExecute("INSERT INTO lottery (number_1, number_2, number_3, number_4, number_5, jackpot) VALUES ('%u', '%u', '%u', '%u', '%u', '%u')", luckyNumber[0], luckyNumber[1], luckyNumber[2], luckyNumber[3], luckyNumber[4], (jackpot + defJackpot));
                        }
                        WorldDatabase.PExecute("DELETE FROM lottery_bets");

                        me->SetVisible(false);
                    }
                }
            }
            else
            {
                if (!me->IsVisible())
                    me->SetVisible(true);
            }
        }
示例#24
0
void AccountMgr::LoadRBAC()
{
    ClearRBAC();

    TC_LOG_DEBUG("rbac", "AccountMgr::LoadRBAC");
    uint32 oldMSTime = getMSTime();
    uint32 count1 = 0;
    uint32 count2 = 0;
    uint32 count3 = 0;

    TC_LOG_DEBUG("rbac", "AccountMgr::LoadRBAC: Loading permissions");
    QueryResult result = LoginDatabase.Query("SELECT id, name FROM rbac_permissions");
    if (!result)
    {
        TC_LOG_INFO("server.loading", ">> Loaded 0 account permission definitions. DB table `rbac_permissions` is empty.");
        return;
    }

    do
    {
        Field* field = result->Fetch();
        uint32 id = field[0].GetUInt32();
        _permissions[id] = new rbac::RBACPermission(id, field[1].GetString());
        ++count1;
    }
    while (result->NextRow());

    TC_LOG_DEBUG("rbac", "AccountMgr::LoadRBAC: Loading linked permissions");
    result = LoginDatabase.Query("SELECT id, linkedId FROM rbac_linked_permissions ORDER BY id ASC");
    if (!result)
    {
        TC_LOG_INFO("server.loading", ">> Loaded 0 linked permissions. DB table `rbac_linked_permissions` is empty.");
        return;
    }

    uint32 permissionId = 0;
    rbac::RBACPermission* permission = NULL;

    do
    {
        Field* field = result->Fetch();
        uint32 newId = field[0].GetUInt32();
        if (permissionId != newId)
        {
            permissionId = newId;
            permission = _permissions[newId];
        }

        uint32 linkedPermissionId = field[1].GetUInt32();
        if (linkedPermissionId == permissionId)
        {
            TC_LOG_ERROR("sql.sql", "RBAC Permission %u has itself as linked permission. Ignored", permissionId);
            continue;
        }
        permission->AddLinkedPermission(linkedPermissionId);
        ++count2;
    }
    while (result->NextRow());

    TC_LOG_DEBUG("rbac", "AccountMgr::LoadRBAC: Loading default permissions");
    result = LoginDatabase.Query("SELECT secId, permissionId FROM rbac_default_permissions ORDER BY secId ASC");
    if (!result)
    {
        TC_LOG_INFO("server.loading", ">> Loaded 0 default permission definitions. DB table `rbac_default_permissions` is empty.");
        return;
    }

    uint8 secId = 255;
    rbac::RBACPermissionContainer* permissions = NULL;
    do
    {
        Field* field = result->Fetch();
        uint32 newId = field[0].GetUInt32();
        if (secId != newId)
        {
            secId = newId;
            permissions = &_defaultPermissions[secId];
        }

        permissions->insert(field[1].GetUInt32());
        ++count3;
    }
    while (result->NextRow());

    TC_LOG_INFO("server.loading", ">> Loaded %u permission definitions, %u linked permissions and %u default permissions in %u ms", count1, count2, count3, GetMSTimeDiffToNow(oldMSTime));
}
示例#25
0
void AcctContainer::LoadAll()
{
    // Load accounts
    QueryResult* result = dbRealmServer.PQuery("SELECT id,username,sha_pass_hash,gmlevel,last_ip,locked,expansion,locale FROM account ORDER BY id");
    uint32 count = 0;

    if(!result)
        return;

    //temp set for banned accid to avoid many sql querys
    std::set<uint32> BannedAcc;

    QueryResult* banresult = dbRealmServer.PQuery("SELECT id FROM account_banned WHERE active = 1");
    if(banresult)
    {
        do
        {
            Field *fields = banresult->Fetch();

            //check exist if exist skip;
            if (BannedAcc.find(fields[0].GetUInt32()) != BannedAcc.end())
                continue;
            BannedAcc.insert(fields[0].GetUInt32());

        } while (banresult->NextRow());

        delete banresult;
    }

    sLog.outString("Loading Accounts In Progress...");
    barGoLink bar( result->GetRowCount());

    // Periodic Database Update ...
    dbRealmServer.PExecute("UPDATE account_banned SET active = 0 WHERE unbandate <= UNIX_TIMESTAMP() AND unbandate <> bandate");
    dbRealmServer.PExecute("DELETE FROM ip_banned WHERE unbandate <= UNIX_TIMESTAMP() AND unbandate <> bandate");

    Account *acc;
    do
    {
        Field *fields = result->Fetch();

        bar.step();

        // Create the account by id
        acc = new Account();
        bool banned = false;
        if (BannedAcc.find(fields[0].GetUInt32()) != BannedAcc.end())
            banned = true;

        FillAccount(acc, fields[0].GetUInt32(), fields[3].GetUInt8(), fields[7].GetUInt8(), fields[6].GetUInt8(), banned, fields[5].GetUInt8(), fields[2].GetCppString(), fields[4].GetCppString());
        m_accounts[fields[1].GetCppString()] = acc;
        count++;

    } while (result->NextRow());

    sLog.outString();
    sLog.outString(">> Loaded %u accounts", count);

    //clean up set
    BannedAcc.clear();

    delete result;

    // Now load ip bans

    result = dbRealmServer.PQuery("SELECT ip FROM ip_banned");

    // If there is no ban don't load
    if(result)
    {
        sLog.outString();
        count = 0;

        sLog.outString("Loading Ban Ip In Progress...");

        barGoLink bar( result->GetRowCount());

        do
        {
            Field *fields = result->Fetch();
            bar.step();

            m_banips.insert(fields[0].GetCppString());
            count++;

        }while (result->NextRow());

        delete result;
        sLog.outString();

        sLog.outString(">> Loaded %u ip banned", count);

        count = 0;
    }

    // Now load Realm Characters

    result = dbRealmServer.PQuery("SELECT acctid, realmid, numchars FROM realmcharacters ORDER BY acctid");

    // If there is no ban don't load
    if(result)
    {
        sLog.outString();

        count = 0;

        sLog.outString("Loading Realm Characters In Progress...");

        barGoLink bar( result->GetRowCount());

        do
        {
            Field *fields = result->Fetch();

            bar.step();

            m_realmcharacters[MAKE_PAIR64(fields[0].GetUInt32(),fields[1].GetUInt32())] = fields[2].GetUInt8();
            count++;

        }while (result->NextRow());

        delete result;

        sLog.outString();

        sLog.outString(">> Loaded %u realm characters", count);
    }

}
示例#26
0
void InstanceSaveManager::LoadResetTimes()
{
    time_t now = time(NULL);
    time_t today = (now / DAY) * DAY;

    // NOTE: Use DirectPExecute for tables that will be queried later

    // get the current reset times for normal instances (these may need to be updated)
    // these are only kept in memory for InstanceSaves that are loaded later
    // resettime = 0 in the DB for raid/heroic instances so those are skipped
    typedef std::pair<uint32 /*PAIR32(map, difficulty)*/, time_t> ResetTimeMapDiffType;
    typedef std::map<uint32, ResetTimeMapDiffType> InstResetTimeMapDiffType;
    InstResetTimeMapDiffType instResetTime;

    // index instance ids by map/difficulty pairs for fast reset warning send
    typedef std::multimap<uint32 /*PAIR32(map, difficulty)*/, uint32 /*instanceid*/ > ResetTimeMapDiffInstances;
    typedef std::pair<ResetTimeMapDiffInstances::const_iterator, ResetTimeMapDiffInstances::const_iterator> ResetTimeMapDiffInstancesBounds;
    ResetTimeMapDiffInstances mapDiffResetInstances;

    QueryResult result = CharacterDatabase.Query("SELECT id, map, difficulty, resettime FROM instance ORDER BY id ASC");
    if (result)
    {
        do
        {
            Field* fields = result->Fetch();

            uint32 instanceId = fields[0].GetUInt32();

            // Instances are pulled in ascending order from db and nextInstanceId is initialized with 1,
            // so if the instance id is used, increment until we find the first unused one for a potential new instance
            if (sMapMgr->GetNextInstanceId() == instanceId)
                sMapMgr->SetNextInstanceId(instanceId + 1);

            // Mark instance id as being used
            sMapMgr->RegisterInstanceId(instanceId);

            if (time_t resettime = time_t(fields[3].GetUInt32()))
            {
                uint32 mapid = fields[1].GetUInt16();
                uint32 difficulty = fields[2].GetUInt8();

                instResetTime[instanceId] = ResetTimeMapDiffType(MAKE_PAIR32(mapid, difficulty), resettime);
                mapDiffResetInstances.insert(ResetTimeMapDiffInstances::value_type(MAKE_PAIR32(mapid, difficulty), instanceId));
            }
        }
        while (result->NextRow());

        // update reset time for normal instances with the max creature respawn time + X hours
        if (PreparedQueryResult result2 = CharacterDatabase.Query(CharacterDatabase.GetPreparedStatement(CHAR_SEL_MAX_CREATURE_RESPAWNS)))
        {
            do
            {
                Field* fields = result2->Fetch();
                uint32 instance = fields[1].GetUInt32();
                time_t resettime = time_t(fields[0].GetUInt32() + 2 * HOUR);
                InstResetTimeMapDiffType::iterator itr = instResetTime.find(instance);
                if (itr != instResetTime.end() && itr->second.second != resettime)
                {
                    CharacterDatabase.DirectPExecute("UPDATE instance SET resettime = '" UI64FMTD "' WHERE id = '%u'", uint64(resettime), instance);
                    itr->second.second = resettime;
                }
            }
            while (result->NextRow());
        }

        // schedule the reset times
        for (InstResetTimeMapDiffType::iterator itr = instResetTime.begin(); itr != instResetTime.end(); ++itr)
            if (itr->second.second > now)
                ScheduleReset(true, itr->second.second, InstResetEvent(0, PAIR32_LOPART(itr->second.first), Difficulty(PAIR32_HIPART(itr->second.first)), itr->first));
    }

    // load the global respawn times for raid/heroic instances
    uint32 diff = sWorld->getIntConfig(CONFIG_INSTANCE_RESET_TIME_HOUR) * HOUR;
    result = CharacterDatabase.Query("SELECT mapid, difficulty, resettime FROM instance_reset");
    if (result)
    {
        do
        {
            Field* fields = result->Fetch();
            uint32 mapid = fields[0].GetUInt16();
            Difficulty difficulty = Difficulty(fields[1].GetUInt8());
            uint64 oldresettime = fields[2].GetUInt32();

            MapDifficulty const* mapDiff = GetMapDifficultyData(mapid, difficulty);
            if (!mapDiff)
            {
                TC_LOG_ERROR("misc", "InstanceSaveManager::LoadResetTimes: invalid mapid(%u)/difficulty(%u) pair in instance_reset!", mapid, difficulty);
                CharacterDatabase.DirectPExecute("DELETE FROM instance_reset WHERE mapid = '%u' AND difficulty = '%u'", mapid, difficulty);
                continue;
            }

            // update the reset time if the hour in the configs changes
            uint64 newresettime = (oldresettime / DAY) * DAY + diff;
            if (oldresettime != newresettime)
                CharacterDatabase.DirectPExecute("UPDATE instance_reset SET resettime = '%u' WHERE mapid = '%u' AND difficulty = '%u'", uint32(newresettime), mapid, difficulty);

            InitializeResetTimeFor(mapid, difficulty, newresettime);
        } while (result->NextRow());
    }

    // calculate new global reset times for expired instances and those that have never been reset yet
    // add the global reset times to the priority queue
    for (MapDifficultyMap::const_iterator itr = sMapDifficultyMap.begin(); itr != sMapDifficultyMap.end(); ++itr)
    {
        uint32 map_diff_pair = itr->first;
        uint32 mapid = PAIR32_LOPART(map_diff_pair);
        Difficulty difficulty = Difficulty(PAIR32_HIPART(map_diff_pair));
        MapDifficulty const* mapDiff = &itr->second;
        if (!mapDiff->resetTime)
            continue;

        // the reset_delay must be at least one day
        uint32 period = uint32(((mapDiff->resetTime * sWorld->getRate(RATE_INSTANCE_RESET_TIME))/DAY) * DAY);
        if (period < DAY)
            period = DAY;

        time_t t = GetResetTimeFor(mapid, difficulty);
        if (!t)
        {
            // initialize the reset time
            t = today + period + diff;
            CharacterDatabase.DirectPExecute("INSERT INTO instance_reset VALUES ('%u', '%u', '%u')", mapid, difficulty, (uint32)t);
        }

        if (t < now)
        {
            // assume that expired instances have already been cleaned
            // calculate the next reset time
            t = (t / DAY) * DAY;
            t += ((today - t) / period + 1) * period + diff;
            CharacterDatabase.DirectPExecute("UPDATE instance_reset SET resettime = '" UI64FMTD "' WHERE mapid = '%u' AND difficulty= '%u'", (uint64)t, mapid, difficulty);
        }

        InitializeResetTimeFor(mapid, difficulty, t);

        // schedule the global reset/warning
        uint8 type;
        for (type = 1; type < 4; ++type)
            if (t - ResetTimeDelay[type-1] > now)
                break;

        ScheduleReset(true, t - ResetTimeDelay[type-1], InstResetEvent(type, mapid, difficulty, 0));

        ResetTimeMapDiffInstancesBounds range = mapDiffResetInstances.equal_range(map_diff_pair);
        for (; range.first != range.second; ++range.first)
            ScheduleReset(true, t - ResetTimeDelay[type-1], InstResetEvent(type, mapid, difficulty, range.first->second));
    }
}
示例#27
0
/// Read data from the network
void RASocket::OnRead()
{
    ///- Read data and check input length
    TcpSocket::OnRead();

    unsigned int sz=ibuf.GetLength();
    if(iInputLength+sz>=RA_BUFF_SIZE)
    {
        sLog.outRemote("Input buffer overflow, possible DOS attack.\n");
        SetCloseAndDelete();
        return;
    }

    char *inp = new char [sz+1];
    ibuf.Read(inp,sz);

    /// \todo Can somebody explain this 'Linux bugfix'?
    if(stage==NONE)
        if(sz>4)                                            //linux remote telnet
            if(memcmp(inp ,"USER ",5))
            {
                delete [] inp;return;
                printf("lin bugfix");
            }                                               //linux bugfix

    ///- Discard data after line break or line feed
    bool gotenter=false;
    unsigned int y=0;
    for (; y<sz; y++)
        if(inp[y]=='\r'||inp[y]=='\n')
    {
        gotenter=true;
        break;
    }

    //No buffer overflow (checked above)
    memcpy(&buff[iInputLength],inp,y);
    iInputLength+=y;
    delete [] inp;
    if(gotenter)
    {

        buff[iInputLength]=0;
        iInputLength=0;
        switch(stage)
        {
            /// <ul> <li> If the input is 'USER <username>'
            case NONE:
                if(!memcmp(buff,"USER ",5))                 //got "USER" cmd
                {
                    szLogin=&buff[5];

                    ///- Get the password from the account table
                    std::string login = szLogin;

                    ///- Convert Account name to Upper Format
                    AccountMgr::normalizeString(login);

                    ///- Escape the Login to allow quotes in names
                    LoginDatabase.escape_string(login);

                    QueryResult result = LoginDatabase.PQuery("SELECT a.id, aa.gmlevel, aa.RealmID FROM account a LEFT JOIN account_access aa ON (a.id = aa.id) WHERE a.username = '******'",login.c_str ());

                    ///- If the user is not found, deny access
                    if(!result)
                    {
                        Sendf("-No such user.\r\n");
                        sLog.outRemote("User %s does not exist.\n",szLogin.c_str());
                        if(bSecure)SetCloseAndDelete();
                    }
                    else
                    {
                        Field *fields = result->Fetch();

                        //szPass=fields[0].GetString();

                        ///- if gmlevel is too low, deny access
                        if(fields[1].GetUInt32()<iMinLevel || fields[1].GetUInt32() == NULL)
                        {
                            Sendf("-Not enough privileges.\r\n");
                            sLog.outRemote("User %s has no privilege.\n",szLogin.c_str());
                            if(bSecure)SetCloseAndDelete();
                        }
                        else if(fields[2].GetInt32() != -1)
                        {
                            ///- if RealmID isn't -1, deny access
                            Sendf("-Not enough privileges.\r\n");
                            sLog.outRemote("User %s has to be assigned on all realms (with RealmID = '-1').\n",szLogin.c_str());
                            if(bSecure)SetCloseAndDelete();
                        }
                        else
                        {
                            stage=LG;
                        }
                    }
                }
                break;
                ///<li> If the input is 'PASS <password>' (and the user already gave his username)
            case LG:
                if(!memcmp(buff,"PASS ",5))                 //got "PASS" cmd
                {                                           //login+pass ok
                    ///- If password is correct, increment the number of active administrators
                    std::string login = szLogin;
                    std::string pw = &buff[5];

                    AccountMgr::normalizeString(login);
                    AccountMgr::normalizeString(pw);
                    LoginDatabase.escape_string(login);
                    LoginDatabase.escape_string(pw);

                    QueryResult check = LoginDatabase.PQuery(
                        "SELECT 1 FROM account WHERE username = '******' AND sha_pass_hash=SHA1(CONCAT('%s',':','%s'))",
                        login.c_str(), login.c_str(), pw.c_str());

                    if(check)
                    {
                        GetSocket();
                        stage=OK;

                        Sendf("+Logged in.\r\n");
                        sLog.outRemote("User %s has logged in.\n",szLogin.c_str());
                        Sendf("SF>");
                    }
                    else
                    {
                        ///- Else deny access
                        Sendf("-Wrong pass.\r\n");
                        sLog.outRemote("User %s has failed to log in.\n",szLogin.c_str());
                        if(bSecure)SetCloseAndDelete();
                    }
                }
                break;
                ///<li> If user is logged, parse and execute the command
            case OK:
                if(strlen(buff))
                {
                    sLog.outRemote("Got '%s' cmd.\n",buff);
                       SetDeleteByHandler(false);
                    CliCommandHolder* cmd = new CliCommandHolder(this, buff, &RASocket::zprint, &RASocket::commandFinished);
                    sWorld.QueueCliCommand(cmd);
                    ++pendingCommands; 
                }
                else
                    Sendf("SF>");
                break;
                ///</ul>
        };

    }
}
示例#28
0
void WorldSession::HandlePetitionBuyOpcode(WorldPacket & recv_data)
{
    sLog.outDebug("Received opcode CMSG_PETITION_BUY");
    //recv_data.hexlike();

    uint64 guidNPC;
    uint64 unk1, unk3, unk4, unk5, unk6, unk7;
    uint32 unk2;
    std::string name;
    uint16 unk8;
    uint8  unk9;
    uint32 unk10;                                           // selected index
    uint32 unk11;
    recv_data >> guidNPC;                                   // NPC GUID
    recv_data >> unk1;                                      // 0
    recv_data >> unk2;                                      // 0
    recv_data >> name;                                      // name

    recv_data >> unk3;                                      // 0
    recv_data >> unk4;                                      // 0
    recv_data >> unk5;                                      // 0
    recv_data >> unk6;                                      // 0
    recv_data >> unk7;                                      // 0
    recv_data >> unk8;                                      // 0
    recv_data >> unk9;                                      // 0
    recv_data >> unk10;                                     // index
    recv_data >> unk11;                                     // 0
    sLog.outDebug("Petitioner with GUID %u tried sell petition: name %s", GUID_LOPART(guidNPC), name.c_str());

    // prevent cheating
    Creature *pCreature = GetPlayer()->GetNPCIfCanInteractWith(guidNPC,UNIT_NPC_FLAG_PETITIONER);
    if (!pCreature)
    {
        sLog.outDebug("WORLD: HandlePetitionBuyOpcode - Unit (GUID: %u) not found or you can't interact with him.", GUID_LOPART(guidNPC));
        return;
    }

    // remove fake death
    if(GetPlayer()->hasUnitState(UNIT_STAT_DIED))
        GetPlayer()->RemoveAurasByType(SPELL_AURA_FEIGN_DEATH);

    uint32 charterid = 0;
    uint32 cost = 0;
    uint32 type = 0;
    if(pCreature->isTabardDesigner())
    {
        // if tabard designer, then trying to buy a guild charter.
        // do not let if already in guild.
        if(_player->GetGuildId())
            return;

        charterid = GUILD_CHARTER;
        cost = GUILD_CHARTER_COST;
        type = 9;
    }
    else
    {
        // TODO: find correct opcode
        if(_player->getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
        {
            SendNotification(LANG_ARENA_ONE_TOOLOW, sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL));
            return;
        }

        switch(unk10)
        {
            case 1:
                charterid = ARENA_TEAM_CHARTER_2v2;
                cost = ARENA_TEAM_CHARTER_2v2_COST;
                type = 2;                                   // 2v2
                break;
            case 2:
                charterid = ARENA_TEAM_CHARTER_3v3;
                cost = ARENA_TEAM_CHARTER_3v3_COST;
                type = 3;                                   // 3v3
                break;
            case 3:
                charterid = ARENA_TEAM_CHARTER_5v5;
                cost = ARENA_TEAM_CHARTER_5v5_COST;
                type = 5;                                   // 5v5
                break;
            default:
                sLog.outDebug("unknown selection at buy petition: %u", unk10);
                return;
        }

        if(_player->GetArenaTeamId(unk10-1))
        {
            SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, name, "", ERR_ALREADY_IN_ARENA_TEAM);
            return;
        }
    }

    if(type == 9)
    {
        if(objmgr.GetGuildByName(name))
        {
            SendGuildCommandResult(GUILD_CREATE_S, name, GUILD_NAME_EXISTS);
            return;
        }
        if(objmgr.IsReservedName(name) || !ObjectMgr::IsValidCharterName(name))
        {
            SendGuildCommandResult(GUILD_CREATE_S, name, GUILD_NAME_INVALID);
            return;
        }
    }
    else
    {
        if(objmgr.GetArenaTeamByName(name))
        {
            SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, name, "", ERR_ARENA_TEAM_NAME_EXISTS_S);
            return;
        }
        if(objmgr.IsReservedName(name) || !ObjectMgr::IsValidCharterName(name))
        {
            SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, name, "", ERR_ARENA_TEAM_NAME_INVALID);
            return;
        }
    }

    ItemPrototype const *pProto = objmgr.GetItemPrototype(charterid);
    if(!pProto)
    {
        _player->SendBuyError(BUY_ERR_CANT_FIND_ITEM, NULL, charterid, 0);
        return;
    }

    if(_player->GetMoney() < cost)
    {                                                       //player hasn't got enough money
        _player->SendBuyError(BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, charterid, 0);
        return;
    }

    ItemPosCountVec dest;
    uint8 msg = _player->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, charterid, pProto->BuyCount );
    if(msg != EQUIP_ERR_OK)
    {
        _player->SendBuyError(msg, pCreature, charterid, 0);
        return;
    }

    _player->ModifyMoney(-(int32)cost);
    Item *charter = _player->StoreNewItem(dest, charterid, true);
    if(!charter)
        return;

    charter->SetUInt32Value(ITEM_FIELD_ENCHANTMENT_1_1, charter->GetGUIDLow());
    // ITEM_FIELD_ENCHANTMENT_1_1 is guild/arenateam id
    // ITEM_FIELD_ENCHANTMENT_1_1+1 is current signatures count (showed on item)
    charter->SetState(ITEM_CHANGED, _player);
    _player->SendNewItem(charter, 1, true, false);

    // a petition is invalid, if both the owner and the type matches
    // we checked above, if this player is in an arenateam, so this must be
    // datacorruption
    QueryResult *result = CharacterDatabase.PQuery("SELECT petitionguid FROM petition WHERE ownerguid = '%u'  AND type = '%u'", _player->GetGUIDLow(), type);

    std::ostringstream ssInvalidPetitionGUIDs;

    if (result)
    {

        do
        {
            Field *fields = result->Fetch();
            ssInvalidPetitionGUIDs << "'" << fields[0].GetUInt32() << "' , ";
        } while (result->NextRow());

        delete result;
    }

    // delete petitions with the same guid as this one
    ssInvalidPetitionGUIDs << "'" << charter->GetGUIDLow() << "'";

    sLog.outDebug("Invalid petition GUIDs: %s", ssInvalidPetitionGUIDs.str().c_str());
    CharacterDatabase.escape_string(name);
    CharacterDatabase.BeginTransaction();
    CharacterDatabase.PExecute("DELETE FROM petition WHERE petitionguid IN ( %s )",  ssInvalidPetitionGUIDs.str().c_str());
    CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE petitionguid IN ( %s )", ssInvalidPetitionGUIDs.str().c_str());
    CharacterDatabase.PExecute("INSERT INTO petition (ownerguid, petitionguid, name, type) VALUES ('%u', '%u', '%s', '%u')",
        _player->GetGUIDLow(), charter->GetGUIDLow(), name.c_str(), type);
    CharacterDatabase.CommitTransaction();
}
示例#29
0
void GroupMgr::LoadGroups()
{
    {
        uint32 oldMSTime = getMSTime();

        // Delete all groups whose leader does not exist
        CharacterDatabase.DirectExecute("DELETE FROM groups WHERE leaderGuid NOT IN (SELECT guid FROM characters)");
        // Delete all groups with less than 2 members (or less than 1 for lfg groups)
        CharacterDatabase.DirectExecute("DELETE groups FROM groups LEFT JOIN ((SELECT guid, count(*) as cnt FROM group_member GROUP BY guid) t) ON groups.guid = t.guid WHERE t.guid IS NULL OR (t.cnt<=1 AND groups.groupType <> 12)");
        // Delete invalid lfg_data
        CharacterDatabase.DirectExecute("DELETE lfg_data FROM lfg_data LEFT JOIN groups ON lfg_data.guid = groups.guid WHERE groups.guid IS NULL OR groups.groupType <> 12");
        // CharacterDatabase.DirectExecute("DELETE groups FROM groups LEFT JOIN lfg_data ON groups.guid = lfg_data.guid WHERE groups.groupType=12 AND lfg_data.guid IS NULL"); // group should be left so binds are cleared when disbanded

        InitGroupIds();

        //                                                        0              1           2             3                 4      5          6      7         8       9
        QueryResult result = CharacterDatabase.Query("SELECT g.leaderGuid, g.lootMethod, g.looterGuid, g.lootThreshold, g.icon1, g.icon2, g.icon3, g.icon4, g.icon5, g.icon6"
            //  10         11          12         13              14                  15            16        17          18
            ", g.icon7, g.icon8, g.groupType, g.difficulty, g.raiddifficulty, g.masterLooterGuid, g.guid, lfg.dungeon, lfg.state FROM groups g LEFT JOIN lfg_data lfg ON lfg.guid = g.guid ORDER BY g.guid ASC");

        if (!result)
        {
            sLog->outString(">> Loaded 0 group definitions. DB table `groups` is empty!");
            sLog->outString();
        }
        else
        {
            uint32 count = 0;
            do
            {
                Field* fields = result->Fetch();
                Group* group = new Group;
                if (!group->LoadGroupFromDB(fields))
                {
                    delete group;
                    continue;
                }
                AddGroup(group);

                RegisterGroupId(group->GetLowGUID());

                ++count;
            }
            while (result->NextRow());

            sLog->outString(">> Loaded %u group definitions in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
            sLog->outString();
        }
    }

    sLog->outString("Loading Group members...");
    {
        uint32 oldMSTime = getMSTime();

        // Delete all rows from group_member with no group
        CharacterDatabase.DirectExecute("DELETE FROM group_member WHERE guid NOT IN (SELECT guid FROM groups)");
        // Delete all members that does not exist
        CharacterDatabase.DirectExecute("DELETE FROM group_member WHERE memberGuid NOT IN (SELECT guid FROM characters)");

        //                                                    0        1           2            3       4
        QueryResult result = CharacterDatabase.Query("SELECT guid, memberGuid, memberFlags, subgroup, roles FROM group_member ORDER BY guid");
        if (!result)
        {
            sLog->outString(">> Loaded 0 group members. DB table `group_member` is empty!");
            sLog->outString();
        }
        else
        {
            uint32 count = 0;
            do
            {
                Field* fields = result->Fetch();
                Group* group = GetGroupByGUID(fields[0].GetUInt32());

                if (group)
                    group->LoadMemberFromDB(fields[1].GetUInt32(), fields[2].GetUInt8(), fields[3].GetUInt8(), fields[4].GetUInt8());
                //else
                //    sLog->outError("GroupMgr::LoadGroups: Consistency failed, can't find group (storage id: %u)", fields[0].GetUInt32());

                ++count;
            }
            while (result->NextRow());

            sLog->outString(">> Loaded %u group members in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
            sLog->outString();
        }
    }
}
示例#30
0
bool Guild::LoadFromDB(Field * f)
{
    m_guildId = f[0].GetUInt32();
    m_guildName = strdup(f[1].GetString());
    m_guildLeader = f[2].GetUInt32();
    m_emblemStyle = f[3].GetUInt32();
    m_emblemColor = f[4].GetUInt32();
    m_borderStyle = f[5].GetUInt32();
    m_borderColor = f[6].GetUInt32();
    m_backgroundColor = f[7].GetUInt32();
    m_guildInfo = strlen(f[8].GetString()) ? strdup(f[8].GetString()) : NULL;
    m_motd = strlen(f[9].GetString()) ? strdup(f[9].GetString()) : NULL;
    m_creationTimeStamp = f[10].GetUInt32();
    m_bankTabCount = f[11].GetUInt32();
    m_bankBalance = f[12].GetUInt32();

    // load ranks
    uint32 j;
    QueryResult * result = CharacterDatabase.Query("SELECT * FROM guild_ranks WHERE guildId = %u ORDER BY rankId ASC", m_guildId);
    if (result == NULL)
        return false;

    uint32 sid = 0;

    do
    {
        GuildRank * r = new GuildRank;
        Field * f2 = result->Fetch();
        r->iId = f2[1].GetUInt32();
        if (r->iId != sid)
        {
            Log.Notice("Guild", "Renaming rank %u of guild %s to %u.", r->iId, m_guildName, sid);
            CharacterDatabase.Execute("UPDATE guild_ranks SET rankId = %u WHERE guildId = %u AND rankName = \"%s\"", r->iId,
                                      m_guildId, CharacterDatabase.EscapeString(std::string(f2[2].GetString())).c_str());

            r->iId = sid;
        }
        sid++;
        r->szRankName = strdup(f2[2].GetString());
        r->iRights = f2[3].GetUInt32();
        r->iGoldLimitPerDay = f2[4].GetUInt32();

        for (j = 0; j < MAX_GUILD_BANK_TABS; ++j)
        {
            r->iTabPermissions[j].iFlags = f2[5 + (j * 2)].GetUInt32();
            r->iTabPermissions[j].iStacksPerDay = f2[6 + (j * 2)].GetUInt32();
        }

        //m_ranks.push_back(r);
        ASSERT(m_ranks[r->iId] == NULL);
        m_ranks[r->iId] = r;

    }
    while (result->NextRow());
    delete result;

    // load members
    result = CharacterDatabase.Query("SELECT * FROM guild_data WHERE guildid = %u", m_guildId);
    if (result == NULL)
        return false;

    do
    {
        Field * f3 = result->Fetch();
        GuildMember * gm = new GuildMember;
        gm->pPlayer = objmgr.GetPlayerInfo(f3[1].GetUInt32());
        if (gm->pPlayer == NULL)
        {
            delete gm;
            continue;
        }

        if (f3[2].GetUInt32() >= MAX_GUILD_RANKS || m_ranks[f3[2].GetUInt32()] == NULL)
        {
            delete gm;
            continue;
        }

        gm->pRank = m_ranks[f3[2].GetUInt32()];
        if (gm->pRank == NULL)
            gm->pRank = FindLowestRank();
        gm->pPlayer->guild = this;
        gm->pPlayer->guildRank = gm->pRank;
        gm->pPlayer->guildMember = gm;

        if (strlen(f3[3].GetString()))
            gm->szPublicNote = strdup(f3[3].GetString());
        else
            gm->szPublicNote = NULL;

        if (strlen(f3[4].GetString()))
            gm->szOfficerNote = strdup(f3[4].GetString());
        else
            gm->szOfficerNote = NULL;

        gm->uLastWithdrawReset = f3[5].GetUInt32();
        gm->uWithdrawlsSinceLastReset = f3[6].GetUInt32();
        for (j = 0; j < MAX_GUILD_BANK_TABS; ++j)
        {
            gm->uLastItemWithdrawReset[j] = f3[7 + (j * 2)].GetUInt32();
            gm->uItemWithdrawlsSinceLastReset[j] = f3[8 + (j * 2)].GetUInt32();
        }

        m_members.insert(std::make_pair(gm->pPlayer, gm));

    }
    while (result->NextRow());
    delete result;

    result = CharacterDatabase.Query("SELECT MAX(log_id) FROM guild_logs WHERE guildid = %u", m_guildId);
    m_hiLogId = 1;
    if (result != NULL)
    {
        m_hiLogId = result->Fetch()[0].GetUInt32() + 1;
        delete result;
    }

    result = CharacterDatabase.Query("SELECT MAX(log_id) FROM guild_banklogs WHERE guildid = %u", m_guildId);
    if (result)
    {
        if ((result->Fetch()[0].GetUInt32() + 1) > m_hiLogId)
            m_hiLogId = result->Fetch()[0].GetUInt32() + 1;
        delete result;
    }

    // load log
    result = CharacterDatabase.Query("SELECT * FROM guild_logs WHERE guildid = %u ORDER BY timestamp ASC", m_guildId);
    if (result)
    {
        do
        {
            GuildLogEvent * li = new GuildLogEvent;
            li->iLogId = result->Fetch()[0].GetUInt32();
            li->iEvent = result->Fetch()[3].GetUInt32();
            li->iTimeStamp = result->Fetch()[2].GetUInt32();
            li->iEventData[0] = result->Fetch()[4].GetUInt32();
            li->iEventData[1] = result->Fetch()[5].GetUInt32();
            li->iEventData[2] = result->Fetch()[6].GetUInt32();
            m_log.push_back(li);
        }
        while (result->NextRow());
        delete result;
    }

    result = CharacterDatabase.Query("SELECT * FROM guild_banktabs WHERE guildId = %u ORDER BY tabId ASC", m_guildId);
    sid = 0;
    if (result)
    {
        do
        {
            if ((sid++) != result->Fetch()[1].GetUInt32())
            {
#ifdef WIN32
                MessageBox(0, "Guild bank tabs are out of order!", "Internal error", MB_OK);
                TerminateProcess(GetCurrentProcess(), 0);
                return false;
#else
                printf("Guild bank tabs are out of order!\n");
                exit(0);
#endif
            }

            QueryResult * res2 = CharacterDatabase.Query("SELECT * FROM guild_bankitems WHERE guildId = %u AND tabId = %u", m_guildId, result->Fetch()[1].GetUInt32());
            GuildBankTab * pTab = new GuildBankTab;
            pTab->iTabId = (uint8)result->Fetch()[1].GetUInt32();
            pTab->szTabName = (strlen(result->Fetch()[2].GetString()) > 0) ? strdup(result->Fetch()[2].GetString()) : NULL;
            pTab->szTabIcon = (strlen(result->Fetch()[3].GetString()) > 0) ? strdup(result->Fetch()[3].GetString()) : NULL;

            memset(pTab->pSlots, 0, sizeof(Item*) * MAX_GUILD_BANK_SLOTS);

            if (res2)
            {
                do
                {
                    Item * pItem = objmgr.LoadItem(res2->Fetch()[3].GetUInt64());
                    if (pItem == NULL)
                    {
                        CharacterDatabase.Execute("DELETE FROM guild_bankitems WHERE itemGuid = %u AND guildId = %u AND tabId = %u", res2->Fetch()[3].GetUInt32(), m_guildId, (uint32)pTab->iTabId);
                        continue;
                    }

                    pTab->pSlots[res2->Fetch()[2].GetUInt32()] = pItem;

                }
                while (res2->NextRow());
                delete res2;
            }

            res2 = CharacterDatabase.Query("SELECT * FROM guild_banklogs WHERE guildid = %u AND tabid = %u ORDER BY timestamp ASC", m_guildId, result->Fetch()[1].GetUInt32());
            if (res2 != NULL)
            {
                do
                {
                    GuildBankEvent * ev = new GuildBankEvent;
                    ev->iLogId = res2->Fetch()[0].GetUInt32();
                    ev->iAction = res2->Fetch()[3].GetUInt8();
                    ev->uPlayer = res2->Fetch()[4].GetUInt32();
                    ev->uEntry = res2->Fetch()[5].GetUInt32();
                    ev->iStack = res2->Fetch()[6].GetUInt8();
                    ev->uTimeStamp = res2->Fetch()[7].GetUInt32();

                    pTab->lLog.push_back(ev);

                }
                while (res2->NextRow());
                delete res2;
            }

            m_bankTabs.push_back(pTab);

        }
        while (result->NextRow());
        delete result;
    }

    result = CharacterDatabase.Query("SELECT * FROM guild_banklogs WHERE guildid = %u AND tabid = 6 ORDER BY timestamp ASC", m_guildId);
    if (result != NULL)
    {
        do
        {
            GuildBankEvent * ev = new GuildBankEvent;
            ev->iLogId = result->Fetch()[0].GetUInt32();
            ev->iAction = result->Fetch()[3].GetUInt8();
            ev->uPlayer = result->Fetch()[4].GetUInt32();
            ev->uEntry = result->Fetch()[5].GetUInt32();
            ev->iStack = result->Fetch()[6].GetUInt8();
            ev->uTimeStamp = result->Fetch()[7].GetUInt32();

            m_moneyLog.push_back(ev);

        }
        while (result->NextRow());
        delete result;
    }

    Log.Debug("Guild", "Loaded guild %s, %u members.", m_guildName, m_members.size());
    return true;
}