void Item::LoadFromDB(Field* fields, Player* plr, bool light )
{
    int32 count;
    uint32 itemid = fields[2].GetUInt32(), random_prop = fields[9].GetUInt32(), random_suffix = fields[10].GetUInt32();
    m_itemProto = ItemPrototypeStorage.LookupEntry( itemid );

    ASSERT( m_itemProto );

    if(m_itemProto->LockId > 1)
        locked = true;
    else
        locked = false;

    SetUInt32Value( OBJECT_FIELD_ENTRY, itemid );
    m_owner = plr;

    wrapped_item_id=fields[3].GetUInt32();
    m_uint32Values[ITEM_FIELD_GIFTCREATOR] = fields[4].GetUInt32();
    m_uint32Values[ITEM_FIELD_CREATOR] = fields[5].GetUInt32();

    count = fields[6].GetUInt32();
    if(m_itemProto->MaxCount > 0 && count > m_itemProto->MaxCount)
        count = m_itemProto->MaxCount;
    SetUInt32Value( ITEM_FIELD_STACK_COUNT, count);

    // Again another for that did not indent to make it do anything for more than
    // one iteration x == 0 was the only one executed
    for( uint32 x = 0; x < 5; x++ )
    {
        if( m_itemProto->Spells[x].Id )
        {
            SetUInt32Value( ITEM_FIELD_SPELL_CHARGES + x , fields[7].GetUInt32() );
            break;
        }
    }

    SetUInt32Value( ITEM_FIELD_FLAGS, fields[8].GetUInt32() );
    Bind(ITEM_BIND_ON_PICKUP); // Check if we need to bind our shit.

    if( random_prop )
        SetRandomProperty( random_prop );
    else if( random_suffix )
        SetRandomSuffix( random_suffix );

    SetTextID( fields[11].GetUInt32() );

    SetUInt32Value( ITEM_FIELD_MAXDURABILITY, m_itemProto->MaxDurability );
    SetUInt32Value( ITEM_FIELD_DURABILITY, fields[12].GetUInt32() );

    if( light )
        return;

    string enchant_field = fields[15].GetString();
    vector< string > enchants = StrSplit( enchant_field, ";" );
    uint32 enchant_id;
    EnchantEntry* entry;
    uint32 time_left;
    uint32 enchslot;
    uint32 dummy = 0;

    for( vector<string>::iterator itr = enchants.begin(); itr != enchants.end(); itr++ )
    {
        if( sscanf( (*itr).c_str(), "%u,%u,%u,%u", (unsigned int*)&enchant_id, (unsigned int*)&time_left, (unsigned int*)&enchslot, (unsigned int*)&dummy) > 3 )
        {
            entry = dbcEnchant.LookupEntry( enchant_id );
            if( entry && entry->Id == enchant_id )
            {
                AddEnchantment( entry, time_left, ( time_left == 0 ), false, false, enchslot, 0, ((dummy > 0) ? true : false) );
                //(enchslot != 2) ? false : true, false);
            }
        }
    }

    string gem_field = fields[16].GetString();
    for( uint8 k = 0; k < 3; k++ )
        sscanf( gem_field.c_str(), GemReadFormat[k], &Gems[k]);

    ApplyRandomProperties( false );

    Charter* charter = guildmgr.GetCharterByItemGuid(GetLowGUID());
    if(charter != NULL)
    {
        SetUInt32Value(ITEM_FIELD_ENCHANTMENT_1_1, charter->GetID());

        // Charter stuff
        if(m_uint32Values[OBJECT_FIELD_ENTRY] == ITEM_ENTRY_GUILD_CHARTER)
        {
            SetUInt32Value( ITEM_FIELD_STACK_COUNT, 1 );
            SetUInt32Value( ITEM_FIELD_PROPERTY_SEED, 57813883 );
            if( plr->m_playerInfo->charterId[CHARTER_TYPE_GUILD] )
                SetUInt32Value( ITEM_FIELD_ENCHANTMENT_1_1, plr->m_playerInfo->charterId[CHARTER_TYPE_GUILD] );
        }

        if( m_uint32Values[OBJECT_FIELD_ENTRY] == ARENA_TEAM_CHARTER_2v2 )
        {
            SetUInt32Value( ITEM_FIELD_STACK_COUNT, 1 );
            SetUInt32Value( ITEM_FIELD_PROPERTY_SEED, 57813883 );
            if( plr->m_playerInfo->charterId[CHARTER_TYPE_ARENA_2V2] )
                SetUInt32Value( ITEM_FIELD_ENCHANTMENT_1_1, plr->m_playerInfo->charterId[CHARTER_TYPE_ARENA_2V2] );
        }

        if( m_uint32Values[OBJECT_FIELD_ENTRY] == ARENA_TEAM_CHARTER_3v3 )
        {
            SetUInt32Value( ITEM_FIELD_STACK_COUNT, 1 );
            SetUInt32Value( ITEM_FIELD_PROPERTY_SEED, 57813883 );
            if( plr->m_playerInfo->charterId[CHARTER_TYPE_ARENA_3V3] )
                SetUInt32Value( ITEM_FIELD_ENCHANTMENT_1_1, plr->m_playerInfo->charterId[CHARTER_TYPE_ARENA_3V3] );
        }

        if( m_uint32Values[OBJECT_FIELD_ENTRY] == ARENA_TEAM_CHARTER_5v5 )
        {
            SetUInt32Value( ITEM_FIELD_STACK_COUNT, 1 );
            SetUInt32Value( ITEM_FIELD_PROPERTY_SEED, 57813883 );
            if( plr->m_playerInfo->charterId[CHARTER_TYPE_ARENA_5V5] )
                SetUInt32Value( ITEM_FIELD_ENCHANTMENT_1_1, plr->m_playerInfo->charterId[CHARTER_TYPE_ARENA_5V5] );
        }
    }
}
void LocalizationMgr::Reload(bool first)
{
	if(first)
		return;

	QueryResult * result;
	set<string> languages;
	map<string, string> bound_languages;
	GetDistinctLanguages(languages, "creature_names_localized");
	GetDistinctLanguages(languages, "gameobject_names_localized");
	GetDistinctLanguages(languages, "items_localized");
	GetDistinctLanguages(languages, "quests_localized");
	GetDistinctLanguages(languages, "npc_text_localized");
	GetDistinctLanguages(languages, "itempages_localized");

	/************************************************************************/
	/* Read Language Bindings From Config                                   */
	/************************************************************************/
	string ls = Config.MainConfig.GetStringDefault("Localization", "LocaleBindings", "");
	vector<string> tbindings = StrSplit(ls, " ");
	for(vector<string>::iterator ztr = tbindings.begin(); ztr != tbindings.end(); ++ztr)
	{
		char lb[200];
		string ll1,ll2;
		strcpy(lb,(*ztr).c_str());

		char * lbp = strchr(lb,'=');
		if(lbp==NULL)
			continue;
		*lbp=0;
		lbp++;

		ll1 = string(lb);
		ll2 = string(lbp);
		Lower(ll1);
		Lower(ll2);

		if(languages.find(ll1) == languages.end())
		{
			bound_languages[ll1] = ll2;
			languages.insert(ll1);
		}
	}

	/************************************************************************/
	/* Generate Language IDs                                                */
	/************************************************************************/

	uint32 langid=1;
	pair<uint32,uint32> dpr;
	for(set<string>::iterator sitr = languages.begin(); sitr != languages.end(); ++sitr)
	{
		if((*sitr)=="enus")		// Default
		{
			dpr.first = *(uint32*)sitr->c_str();
			dpr.second = 0;
		}
		else
		{
			dpr.first = *(uint32*)sitr->c_str();
			dpr.second = langid++;
		}

		m_languages.push_back(dpr);
	}

	if(m_languages.size() == 0)
	{
		m_disabled = true;
		return;		// No localizations
	}
	else
		m_disabled = false;

	m_CreatureNames = new HM_NAMESPACE::hash_map<uint32, LocalizedCreatureName>[langid];
	m_GameObjectNames = new HM_NAMESPACE::hash_map<uint32, LocalizedGameObjectName>[langid];
	m_Quests = new HM_NAMESPACE::hash_map<uint32, LocalizedQuest>[langid];
	m_NpcTexts = new HM_NAMESPACE::hash_map<uint32, LocalizedNpcText>[langid];
	m_Items = new HM_NAMESPACE::hash_map<uint32, LocalizedItem>[langid];
	m_ItemPages = new HM_NAMESPACE::hash_map<uint32, LocalizedItemPage>[langid];

	/************************************************************************/
	/* Creature Names                                                       */
	/************************************************************************/
	{
		LocalizedCreatureName cn;
		string str;
		uint32 entry;
		Field * f;
		uint32 lid;

		result = WorldDatabase.Query("SELECT * FROM creature_names_localized");
		if(result)
		{
			do
			{
				f = result->Fetch();
				str = string(f[1].GetString());
				entry = f[0].GetUInt32();

				lid = GetLanguageId(str);
				if(lid == 0)
					continue;		// no loading enus stuff.. lawl

				cn.Name = strdup(f[2].GetString());
				cn.SubName = strdup(f[3].GetString());
				m_CreatureNames[lid].insert(make_pair(entry, cn));
			} while(result->NextRow());
			delete result;
		}
	}

	/************************************************************************/
	/* GameObject Names                                                     */
	/************************************************************************/
	{
		LocalizedGameObjectName gn;
		string str;
		uint32 entry;
		Field * f;
		uint32 lid;

		result = WorldDatabase.Query("SELECT * FROM gameobject_names_localized");
		if(result)
		{
			do
			{
				f = result->Fetch();
				str = string(f[1].GetString());
				entry = f[0].GetUInt32();

				lid = GetLanguageId(str);
				if(lid == 0)
					continue;		// no loading enus stuff.. lawl

				gn.Name = strdup(f[2].GetString());
				m_GameObjectNames[lid].insert(make_pair(entry, gn));
			} while(result->NextRow());
			delete result;
		}
	}

	/************************************************************************/
	/* Items                                                                */
	/************************************************************************/
	{
		LocalizedItem it;
		string str;
		uint32 entry;
		Field * f;
		uint32 lid;

		result = WorldDatabase.Query("SELECT * FROM items_localized");
		if(result)
		{
			do
			{
				f = result->Fetch();
				str = string(f[1].GetString());
				entry = f[0].GetUInt32();

				lid = GetLanguageId(str);
				if(lid == 0)
					continue;		// no loading enus stuff.. lawl

				if(m_Items[lid].find(entry) != m_Items[lid].end())
				{
					continue;
				}

				it.Name = strdup(f[2].GetString());
				it.Description = strdup(f[3].GetString());
				m_Items[lid].insert(make_pair(entry, it));
			} while(result->NextRow());
			delete result;
		}
	}

	/************************************************************************/
	/* Quests                                                               */
	/************************************************************************/
	{
		LocalizedQuest q;
		string str;
		uint32 entry;
		Field * f;
		uint32 lid;

		result = WorldDatabase.Query("SELECT * FROM quests_localized");
		if(result)
		{
			do
			{
				f = result->Fetch();
				str = string(f[1].GetString());
				entry = f[0].GetUInt32();

				lid = GetLanguageId(str);
				if(lid == 0)
					continue;		// no loading enus stuff.. lawl

				q.Title = strdup(f[2].GetString());
				q.Details = strdup(f[3].GetString());
				q.Objectives = strdup(f[4].GetString());
				q.CompletionText = strdup(f[5].GetString());
				q.IncompleteText = strdup(f[6].GetString());
				q.EndText = strdup(f[7].GetString());
				q.ObjectiveText[0] = strdup(f[8].GetString());
				q.ObjectiveText[1] = strdup(f[9].GetString());
				q.ObjectiveText[2] = strdup(f[10].GetString());
				q.ObjectiveText[3] = strdup(f[11].GetString());

				m_Quests[lid].insert(make_pair(entry, q));
			} while(result->NextRow());
			delete result;
		}
	}

	/************************************************************************/
	/* NPC Texts                                                            */
	/************************************************************************/
	{
		LocalizedNpcText nt;
		string str;
		uint32 entry;
		Field * f;
		uint32 lid;
		uint32 counter;

		result = WorldDatabase.Query("SELECT * FROM npc_text_localized");
		if(result)
		{
			do
			{
				f = result->Fetch();
				str = string(f[1].GetString());
				entry = f[0].GetUInt32();

				lid = GetLanguageId(str);
				if(lid == 0)
					continue;		// no loading enus stuff.. lawl

				counter = 2;
				for(uint32 i = 0; i < 8; i++)
				{
					nt.Texts[i][0] = strdup(f[counter++].GetString());
					nt.Texts[i][1] = strdup(f[counter++].GetString());
				}

				m_NpcTexts[lid].insert(make_pair(entry, nt));
			} while(result->NextRow());
			delete result;
		}
	}
	/************************************************************************/
	/* Item Pages                                                           */
	/************************************************************************/
	{
		LocalizedItemPage nt;
		string str;
		uint32 entry;
		Field * f;
		uint32 lid;

		result = WorldDatabase.Query("SELECT * FROM itempages_localized");
		if(result)
		{
			do
			{
				f = result->Fetch();
				str = string(f[1].GetString());
				entry = f[0].GetUInt32();

				lid = GetLanguageId(str);
				if(lid == 0)
					continue;		// no loading enus stuff.. lawl

				nt.Text = strdup(f[2].GetString());
				m_ItemPages[lid].insert(make_pair(entry, nt));
			} while(result->NextRow());
			delete result;
		}
	}

	/************************************************************************/
	/* Apply all the language bindings.                                     */
	/************************************************************************/
	for(map<string,string>::iterator itr = bound_languages.begin(); itr != bound_languages.end(); itr++)
	{
		uint32 source_language_id = GetLanguageId(itr->second);
		uint32 dest_language_id = GetLanguageId(itr->first);
		if(source_language_id==0 || dest_language_id == 0)
		{
			Log.Error("LocalizationMgr", "Invalid locale conversion string specified: %u->%u (%s->%s)", source_language_id, dest_language_id, itr->second.c_str(), itr->first.c_str());
			continue;
		}

		/* duplicate the hashmaps (we can save the pointers here) */
		CopyHashMap<LocalizedItem>(&m_Items[source_language_id], &m_Items[dest_language_id]);
		CopyHashMap<LocalizedCreatureName>(&m_CreatureNames[source_language_id], &m_CreatureNames[dest_language_id]);
		CopyHashMap<LocalizedGameObjectName>(&m_GameObjectNames[source_language_id], &m_GameObjectNames[dest_language_id]);
		CopyHashMap<LocalizedItemPage>(&m_ItemPages[source_language_id], &m_ItemPages[dest_language_id]);
		CopyHashMap<LocalizedQuest>(&m_Quests[source_language_id], &m_Quests[dest_language_id]);
		CopyHashMap<LocalizedNpcText>(&m_NpcTexts[source_language_id], &m_NpcTexts[dest_language_id]);
	}
}
Exemple #3
0
void ObjectMgr::LoadExtraCreatureProtoStuff()
{
	{
		StorageContainerIterator<CreatureProto> * itr = CreatureProtoStorage.MakeIterator();
		CreatureProto * cn;
		while(!itr->AtEnd())
		{
			cn = itr->Get();
			if(itr->Get()->aura_string)
			{
				string auras = string(itr->Get()->aura_string);
				vector<string> aurs = StrSplit(auras, " ");
				for(vector<string>::iterator it = aurs.begin(); it != aurs.end(); ++it)
				{
					uint32 id = atol((*it).c_str());
					if(id)
						itr->Get()->start_auras.insert( id );
				}
			}

			if(!itr->Get()->MinHealth)
				itr->Get()->MinHealth = 1;
			if(!itr->Get()->MaxHealth)
				itr->Get()->MaxHealth = 1;
			if (itr->Get()->AttackType > SCHOOL_ARCANE)
				itr->Get()->AttackType = SCHOOL_NORMAL;

			cn->m_canFlee = cn->m_canRangedAttack = cn->m_canCallForHelp = false;
			cn->m_fleeHealth = 0.0f;
			// please.... m_fleeDuration is a uint32...
			//cn->m_fleeDuration = 0.0f;
			cn->m_fleeDuration = 0;

			if(!itr->Inc())
				break;
		}

		itr->Destruct();
	}

	{
		StorageContainerIterator<CreatureInfo> * itr = CreatureNameStorage.MakeIterator();
		CreatureInfo * ci;
		while(!itr->AtEnd())
		{
			ci = itr->Get();

			ci->lowercase_name = string(ci->Name);
			for(uint32 j = 0; j < ci->lowercase_name.length(); ++j)
				ci->lowercase_name[j] = tolower(ci->lowercase_name[j]); // Darvaleo 2008/08/15 - Copied lowercase conversion logic from ItemPrototype task

			ci->gossip_script = sScriptMgr.GetDefaultGossipScript();

			if(!itr->Inc())
				break;
		}
		itr->Destruct();
	}

	{
		StorageContainerIterator<Quest> * itr = QuestStorage.MakeIterator();
		Quest * qst;
		while(!itr->AtEnd())
		{
			qst = itr->Get();
			qst->pQuestScript = NULL;

			if( !itr->Inc() )
				break;
		}
		itr->Destruct();
	}

	// Load AI Agents
	QueryResult * result = WorldDatabase.Query( "SELECT * FROM ai_agents" );
	CreatureProto * cn;

	if( result != NULL )
	{
		AI_Spell *sp;
		SpellEntry * spe;
		uint32 entry;

		if(Config.OptionsConfig.GetBoolDefault("Server", "LoadAIAgents", true))
		{
			do
			{
				Field *fields = result->Fetch();
				entry = fields[0].GetUInt32();
				cn = CreatureProtoStorage.LookupEntry(entry);
				spe = dbcSpell.LookupEntryForced(fields[5].GetUInt32());
				if( spe == NULL )
				{
					Log.Warning("AIAgent", "For %u has nonexistant spell %u.", fields[0].GetUInt32(), fields[5].GetUInt32());
				}
				if(!cn)
					continue;

				sp = new AI_Spell;
				sp->entryId = fields[0].GetUInt32();
				sp->agent = fields[1].GetUInt16();
				sp->procChance = fields[3].GetUInt32();
				sp->procCount = fields[4].GetUInt32();
				sp->spell = spe;
				sp->spellType = fields[6].GetUInt32();
				sp->spelltargetType = fields[7].GetUInt32();
				sp->cooldown = fields[8].GetUInt32();
				sp->floatMisc1 = fields[9].GetFloat();
				sp->autocast_type=(uint32)-1;
				sp->custom_pointer=false;
				sp->cooldowntime=getMSTime();
				sp->procCounter=0;

		/*		if (!sp->procCountDB) 
					sp->procCount = uint32(-1);
				else sp->procCount = sp->procCountDB;*/
				sp->Misc2 = fields[10].GetUInt32();
				if(sp->agent == AGENT_SPELL)
				{
					if(!sp->spell)
					{
						//printf("SpellId %u in ai_agent for %u is invalid.\n", (unsigned int)fields[5].GetUInt32(), (unsigned int)sp->entryId);
						delete sp;
						continue;
					}
					
					if(sp->spell->Effect[0] == SPELL_EFFECT_LEARN_SPELL || sp->spell->Effect[1] == SPELL_EFFECT_LEARN_SPELL ||
						sp->spell->Effect[2] == SPELL_EFFECT_LEARN_SPELL)
					{
						//printf("Teaching spell %u in ai_agent for %u\n", (unsigned int)fields[5].GetUInt32(), (unsigned int)sp->entryId);
						delete sp;
						continue;
					}

					sp->minrange = GetMinRange(dbcSpellRange.LookupEntry(sp->spell->rangeIndex));
					sp->maxrange = GetMaxRange(dbcSpellRange.LookupEntry(sp->spell->rangeIndex));

					//omg the poor darling has no clue about making ai_agents
					if(sp->cooldown==0xffffffff)
					{
						//now this will not be exact cooldown but maybe a bigger one to not make him spam spells to often
						int cooldown;
						SpellDuration *sd=dbcSpellDuration.LookupEntry(sp->spell->DurationIndex);
						int Dur=0;
						int Casttime=0;//most of the time 0
						int RecoveryTime=sp->spell->RecoveryTime;
						if(sp->spell->DurationIndex)
							Dur =::GetDuration(sd);
						Casttime=GetCastTime(dbcSpellCastTime.LookupEntry(sp->spell->CastingTimeIndex));
						cooldown=Dur+Casttime+RecoveryTime;
						if(cooldown<0)
							sp->cooldown=0;//huge value that should not loop while adding some timestamp to it
						else sp->cooldown=cooldown;
					}

					/*
					//now apply the morron filter
					if(sp->procChance==0)
					{
						//printf("SpellId %u in ai_agent for %u is invalid.\n", (unsigned int)fields[5].GetUInt32(), (unsigned int)sp->entryId);
						delete sp;
						continue;
					}
					if(sp->spellType==0)
					{
						//right now only these 2 are used
						if(IsBeneficSpell(sp->spell))
							sp->spellType==STYPE_HEAL;
						else sp->spellType==STYPE_BUFF;
					}
					if(sp->spelltargetType==0)
						sp->spelltargetType = RecommandAISpellTargetType(sp->spell);
						*/
				}

				if(sp->agent == AGENT_RANGED)
				{
					cn->m_canRangedAttack = true;
					delete sp;
				}
				else if(sp->agent == AGENT_FLEE)
				{
					cn->m_canFlee = true;
					if(sp->floatMisc1)
						cn->m_canFlee = (sp->floatMisc1>0.0f ? true : false);
					else
						cn->m_fleeHealth = 0.2f;

					if(sp->Misc2)
						cn->m_fleeDuration = sp->Misc2;
					else
						cn->m_fleeDuration = 10000;

					delete sp;
				}
				else if(sp->agent == AGENT_CALLFORHELP)
				{
					cn->m_canCallForHelp = true;
					if(sp->floatMisc1)
						cn->m_callForHelpHealth = 0.2f;
					delete sp;
				}
				else
				{
					cn->spells.push_back(sp);
				}
			} while( result->NextRow() );
		}

		delete result;
	}
}
Exemple #4
0
int extractConnectInfo(FILE *fp, ConnectNotice &cn)
{
    // First, clear out the connect notice.
    cn.noticeID = 0;
    cn.customerID = 0;
    cn.ticketNo = 0;
    strcpy(cn.noticeDate, "");
    strcpy(cn.connType, "");
    strcpy(cn.custName, "");
    strcpy(cn.addr1, "");
    strcpy(cn.addr2, "");
    strcpy(cn.addr3, "");
    strcpy(cn.isSelect, "");
    strcpy(cn.cbr, "");
    strcpy(cn.dueDate, "");
    strcpy(cn.custCirc, "");
    strcpy(cn.hostCirc, "");
    strcpy(cn.speed, "");
    strcpy(cn.vpi, "");
    strcpy(cn.vci, "");

    // Create our buffers and work variables.
    int     retVal = 0;
    int     bufsize = 65536;
    char    *buf = new char[bufsize];
    __gnu_cxx::StrSplitMap tmpList;
    __gnu_cxx::StrSplitMap bodyLines;
    int         lineCount;
    string      tmpStr1;
    string      tmpStr2;
    int         splitCount;
    size_t      byteCount;
    time_t      msgUnixTime;

    // Load the entire message into memory.
    byteCount = fread((void *)buf, sizeof(char), bufsize, fp);
    if (!byteCount) return(retVal);

    // Okay the whole file should be in memory now.  Parse it as a DwMessage
    DwMessage   msg(buf);
    msg.Parse();
    msgUnixTime = msg.Headers().Date().AsCalendarTime();
    tm *t = localtime(&msgUnixTime);
    int theYear = t->tm_year + 1900;
    sprintf(cn.noticeDate, "%04d-%02d-%02d %02d:%02d:%02d",
            theYear, t->tm_mon+1, t->tm_mday,
            t->tm_hour, t->tm_min, t->tm_sec);

    lineCount = StrSplit(msg.Body().AsString().c_str(), "\n", bodyLines);

    // Loop through the file until EOF.
    //while ((fgets(buf, bufsize, fp) != NULL)) {
    for (int i = 0; i < lineCount; i++) {
        strcpy(buf, bodyLines[i].c_str());
        // Strip off the whitespace.
        tmpList.clear();
        tmpStr1 = buf;
        StripWhiteSpace(tmpStr1);
        splitCount = StrSplit(tmpStr1.c_str(), " ", tmpList, 2);
        
        // Look for any of our values
        if (!strncasecmp(buf, "ACTION", strlen("ACTION"))) {
            strcpy(cn.connType, tmpList[1].c_str());
        }
        if (!strncasecmp(buf, "NAME", strlen("NAME"))) {
            strcpy(cn.custName, tmpList[1].c_str());
        }
        if (!strncasecmp(buf, "ADDR1", strlen("ADDR1"))) {
            strcpy(cn.addr1, tmpList[1].c_str());
        }
        if (!strncasecmp(buf, "ADDR2", strlen("ADDR2"))) {
            strcpy(cn.addr2, tmpList[1].c_str());
        }
        if (!strncasecmp(buf, "ADDR3", strlen("ADDR3"))) {
            strcpy(cn.addr3, tmpList[1].c_str());
        }
        if (!strncasecmp(buf, "SELECT256", strlen("SELECT256"))) {
            strcpy(cn.isSelect, tmpList[1].c_str());
        }
        if (!strncasecmp(buf, "CBR", strlen("CBR"))) {
            strcpy(cn.cbr, tmpList[1].c_str());
        }
        if (!strncasecmp(buf, "DUEDATE", strlen("DUEDATE"))) {
            strcpy(cn.dueDate, tmpList[1].c_str());
        }
        if (!strncasecmp(buf, "CKTTN", strlen("CKTTN"))) {
            strcpy(cn.custCirc, tmpList[1].c_str());
        }
        if (!strncasecmp(buf, "HOSTCKT", strlen("HOSTCKT"))) {
            strcpy(cn.hostCirc, tmpList[1].c_str());
        }
        if (!strncasecmp(buf, "SPEED", strlen("SPEED"))) {
            strcpy(cn.speed, tmpList[1].c_str());
        }
        if (!strncasecmp(buf, "VPI", strlen("VPI"))) {
            strcpy(cn.vpi, tmpList[1].c_str());
        }
        if (!strncasecmp(buf, "VCI", strlen("VCI"))) {
            strcpy(cn.vci, tmpList[1].c_str());
        }
    }

    // Now, if we got a CKKTN, and an ACTION, it is good.
    if (strlen(cn.connType) && strlen(cn.custCirc)) retVal = 1;

    return retVal;
}
Exemple #5
0
void Item::LoadFromDB(Field* fields, Player* plr, bool light )
{
	uint32 itemid = fields[2].GetUInt32();
	uint32 random_prop, random_suffix;
	m_itemProto = ItemPrototypeStorage.LookupEntry( itemid );

	ASSERT( m_itemProto );
	
	if(m_itemProto->LockId > 1)
		locked = true;
	else
		locked = false;
	
	SetUInt32Value( OBJECT_FIELD_ENTRY, itemid );
	m_owner = plr;

	wrapped_item_id=fields[3].GetUInt32();
	m_uint32Values[ITEM_FIELD_GIFTCREATOR] = fields[4].GetUInt32();
	m_uint32Values[ITEM_FIELD_CREATOR] = fields[5].GetUInt32();

	SetUInt32Value( ITEM_FIELD_STACK_COUNT,  fields[6].GetUInt32());

	// Again another for that did not indent to make it do anything for more than 
	// one iteration x == 0 was the only one executed
	for( uint32 x = 0; x < 5; x++ )
	{
		if( m_itemProto->Spells[x].Id )
		{
			SetUInt32Value( ITEM_FIELD_SPELL_CHARGES + x , fields[7].GetUInt32() );
			break;
		}
	}

	SetUInt32Value( ITEM_FIELD_FLAGS, fields[8].GetUInt32() );
	random_prop = fields[9].GetUInt32();
	random_suffix = fields[10].GetUInt32();

	if( random_prop )
		SetRandomProperty( random_prop );
	else if( random_suffix )
		SetRandomSuffix( random_suffix );

	SetUInt32Value( ITEM_FIELD_ITEM_TEXT_ID, fields[11].GetUInt32() );

	SetUInt32Value( ITEM_FIELD_MAXDURABILITY, m_itemProto->MaxDurability );
	SetUInt32Value( ITEM_FIELD_DURABILITY, fields[12].GetUInt32() );

	if( light )
		return;

	string enchant_field = fields[15].GetString();
	vector< string > enchants = StrSplit( enchant_field, ";" );
	uint32 enchant_id;
	EnchantEntry* entry;
	uint32 time_left;
	uint32 enchslot;

	for( vector<string>::iterator itr = enchants.begin(); itr != enchants.end(); ++itr )
	{
		if( sscanf( (*itr).c_str(), "%u,%u,%u", (unsigned int*)&enchant_id, (unsigned int*)&time_left, (unsigned int*)&enchslot) == 3 )
		{
			entry = dbcEnchant.LookupEntry( enchant_id );
			if( entry && entry->Id == enchant_id )
			{
				AddEnchantment( entry, time_left, ( time_left == 0 ), false, false, enchslot );
				//(enchslot != 2) ? false : true, false);
			}
			else
			{
				/*
				EnchantEntry *pEnchant = new EnchantEntry;
				memset(pEnchant,0,sizeof(EnchantEntry));

				pEnchant->Id = enchant_id;
				if(enchslot != 2)
					AddEnchantment(pEnchant,0,true, false);
				else
					AddEnchantment(pEnchant,0,false,false);
				*/
			}
		}
	}	

	ApplyRandomProperties( false );

	// Charter stuff
	if(m_uint32Values[OBJECT_FIELD_ENTRY] == ITEM_ENTRY_GUILD_CHARTER)
	{
		SetUInt32Value( ITEM_FIELD_FLAGS, 1 );
		SetUInt32Value( ITEM_FIELD_STACK_COUNT, 1 );
		SetUInt32Value( ITEM_FIELD_PROPERTY_SEED, 57813883 );
		if( plr->m_playerInfo->charterId[CHARTER_TYPE_GUILD] )
			SetUInt32Value( ITEM_FIELD_ENCHANTMENT, plr->m_playerInfo->charterId[CHARTER_TYPE_GUILD] );
	}

	if( m_uint32Values[OBJECT_FIELD_ENTRY] == ARENA_TEAM_CHARTER_2v2 )
	{
		SetUInt32Value( ITEM_FIELD_FLAGS, 1 );
		SetUInt32Value( ITEM_FIELD_STACK_COUNT, 1 );
		SetUInt32Value( ITEM_FIELD_PROPERTY_SEED, 57813883 );
		if( plr->m_playerInfo->charterId[CHARTER_TYPE_ARENA_2V2] )
			SetUInt32Value( ITEM_FIELD_ENCHANTMENT, plr->m_playerInfo->charterId[CHARTER_TYPE_ARENA_2V2] );
	}

	if( m_uint32Values[OBJECT_FIELD_ENTRY] == ARENA_TEAM_CHARTER_3v3 )
	{
		SetUInt32Value( ITEM_FIELD_FLAGS, 1 );
		SetUInt32Value( ITEM_FIELD_STACK_COUNT, 1 );
		SetUInt32Value( ITEM_FIELD_PROPERTY_SEED, 57813883 );
		if( plr->m_playerInfo->charterId[CHARTER_TYPE_ARENA_3V3] )
			SetUInt32Value( ITEM_FIELD_ENCHANTMENT, plr->m_playerInfo->charterId[CHARTER_TYPE_ARENA_3V3] );
	}

	if( m_uint32Values[OBJECT_FIELD_ENTRY] == ARENA_TEAM_CHARTER_5v5 )
	{
		SetUInt32Value( ITEM_FIELD_FLAGS, 1 );
		SetUInt32Value( ITEM_FIELD_STACK_COUNT, 1 );
		SetUInt32Value( ITEM_FIELD_PROPERTY_SEED, 57813883 );
		if( plr->m_playerInfo->charterId[CHARTER_TYPE_ARENA_5V5] )
			SetUInt32Value( ITEM_FIELD_ENCHANTMENT, plr->m_playerInfo->charterId[CHARTER_TYPE_ARENA_5V5] );
	}
}
Exemple #6
0
void Item::LoadFromDB(Field* fields, Player* plr, bool light )
{
	uint32 itemid = fields[2].GetUInt32();
	uint32 random_prop, random_suffix;
	uint32 count;

	m_itemProto = ItemPrototypeStorage.LookupEntry( itemid );

	ASSERT( m_itemProto );
	
	if(m_itemProto->LockId > 1)
		locked = true;
	else
		locked = false;
	
	SetUInt32Value( OBJECT_FIELD_ENTRY, itemid );
	m_owner = plr;

	wrapped_item_id=fields[3].GetUInt32();
	m_uint32Values[ITEM_FIELD_GIFTCREATOR] = fields[4].GetUInt32();
	m_uint32Values[ITEM_FIELD_CREATOR] = fields[5].GetUInt32();

	count = fields[6].GetUInt32();
	if( count > m_itemProto->MaxCount && (m_owner && !m_owner->ItemStackCheat) )
		count = m_itemProto->MaxCount;
	SetUInt32Value( ITEM_FIELD_STACK_COUNT, count);

	// Again another for that did not indent to make it do anything for more than 
	// one iteration x == 0 was the only one executed
	for( uint32 x = 0; x < 5; x++ )
	{
		if( m_itemProto->Spells[x].Id )
		{
			SetUInt32Value( ITEM_FIELD_SPELL_CHARGES + x , fields[7].GetUInt32() );
			break;
		}
	}

	SetUInt32Value( ITEM_FIELD_FLAGS, fields[8].GetUInt32() );
	random_prop = fields[9].GetUInt32();
	random_suffix = fields[10].GetUInt32();

	if( random_prop )
		SetRandomProperty( random_prop );
	else if( random_suffix )
		SetRandomSuffix( random_suffix );

	SetUInt32Value( ITEM_FIELD_ITEM_TEXT_ID, fields[11].GetUInt32() );

	SetUInt32Value( ITEM_FIELD_MAXDURABILITY, m_itemProto->MaxDurability );
	SetUInt32Value( ITEM_FIELD_DURABILITY, fields[12].GetUInt32() );

	if( light )
		return;

	string enchant_field = fields[15].GetString();
	vector< string > enchants = StrSplit( enchant_field, ";" );
	uint32 enchant_id;
	EnchantEntry* entry;
	uint32 time_left;
	uint32 enchslot;

	for( vector<string>::iterator itr = enchants.begin(); itr != enchants.end(); ++itr )
	{
		if( sscanf( (*itr).c_str(), "%u,%u,%u", (unsigned int*)&enchant_id, (unsigned int*)&time_left, (unsigned int*)&enchslot) == 3 )
		{
			entry = dbcEnchant.LookupEntry( enchant_id );
			if( entry && entry->Id == enchant_id && m_itemProto->SubClass != ITEM_SUBCLASS_WEAPON_THROWN)
			{
				AddEnchantment( entry, time_left, ( time_left == 0 ), false, false, enchslot );
				//(enchslot != 2) ? false : true, false);
			}
			else
			{
				/*
				EnchantEntry *pEnchant = new EnchantEntry;
				memset(pEnchant,0,sizeof(EnchantEntry));

				pEnchant->Id = enchant_id;
				if(enchslot != 2)
					AddEnchantment(pEnchant,0,true, false);
				else
					AddEnchantment(pEnchant,0,false,false);
				*/
			}
		}
	}

    ItemExpiresOn = fields[16].GetUInt32();
    
///////////////////////////////////////////////////// Refund stuff ////////////////////////
    std::pair< time_t, uint32 > refundentry;

    refundentry.first = fields[17].GetUInt32();
    refundentry.second = fields[18].GetUInt32();

    uint32 *played = this->GetOwner()->GetPlayedtime();

    if( refundentry.first != 0 && refundentry.second != 0 ){
        if( played[1] < ( refundentry.first + 60*60*2 ) )
            m_owner->GetItemInterface()->AddRefundable( this, refundentry.second, refundentry.first );
    }

///////////////////////////////////////////////////////////////////////////////////////////
    
	ApplyRandomProperties( false );

	// Charter stuff
	if(m_uint32Values[OBJECT_FIELD_ENTRY] == ITEM_ENTRY_GUILD_CHARTER)
	{
		SetUInt32Value( ITEM_FIELD_FLAGS, 1 );
		SetUInt32Value( ITEM_FIELD_STACK_COUNT, 1 );
		SetUInt32Value( ITEM_FIELD_PROPERTY_SEED, 57813883 );
		if( plr != NULL && plr->m_charters[CHARTER_TYPE_GUILD] )
			SetUInt32Value( ITEM_FIELD_ENCHANTMENT_1_1, plr->m_charters[CHARTER_TYPE_GUILD]->GetID() );
	}

	if( m_uint32Values[OBJECT_FIELD_ENTRY] == ARENA_TEAM_CHARTER_2v2 )
	{
		SetUInt32Value( ITEM_FIELD_FLAGS, 1 );
		SetUInt32Value( ITEM_FIELD_STACK_COUNT, 1 );
		SetUInt32Value( ITEM_FIELD_PROPERTY_SEED, 57813883 );
		if( plr != NULL && plr->m_charters[CHARTER_TYPE_ARENA_2V2] )
			SetUInt32Value( ITEM_FIELD_ENCHANTMENT_1_1, plr->m_charters[CHARTER_TYPE_ARENA_2V2]->GetID() );
	}

	if( m_uint32Values[OBJECT_FIELD_ENTRY] == ARENA_TEAM_CHARTER_3v3 )
	{
		SetUInt32Value( ITEM_FIELD_FLAGS, 1 );
		SetUInt32Value( ITEM_FIELD_STACK_COUNT, 1 );
		SetUInt32Value( ITEM_FIELD_PROPERTY_SEED, 57813883 );
		if( plr != NULL && plr->m_charters[CHARTER_TYPE_ARENA_3V3] )
			SetUInt32Value( ITEM_FIELD_ENCHANTMENT_1_1, plr->m_charters[CHARTER_TYPE_ARENA_3V3]->GetID() );
	}

	if( m_uint32Values[OBJECT_FIELD_ENTRY] == ARENA_TEAM_CHARTER_5v5 )
	{
		SetUInt32Value( ITEM_FIELD_FLAGS, 1 );
		SetUInt32Value( ITEM_FIELD_STACK_COUNT, 1 );
		SetUInt32Value( ITEM_FIELD_PROPERTY_SEED, 57813883 );
		if( plr != NULL && plr->m_charters[CHARTER_TYPE_ARENA_5V5] )
			SetUInt32Value( ITEM_FIELD_ENCHANTMENT_1_1, plr->m_charters[CHARTER_TYPE_ARENA_5V5]->GetID() );
	}
}
Exemple #7
0
bool Corpse::LoadFromDB(uint32 guid, Field *fields)
{
    ////                                                    0            1       2                  3                  4                  5                   6
    //QueryResult *result = CharacterDatabase.Query("SELECT corpse.guid, player, corpse.position_x, corpse.position_y, corpse.position_z, corpse.orientation, corpse.map,"
    ////   7     8            9         10         11      12    13     14           15            16              17       18
    //    "time, corpse_type, instance, phaseMask, gender, race, class, playerBytes, playerBytes2, equipmentCache, guildId, playerFlags FROM corpse"
    uint32 playerGuid   = fields[1].GetUInt32();
    float positionX     = fields[2].GetFloat();
    float positionY     = fields[3].GetFloat();
    float positionZ     = fields[4].GetFloat();
    float orientation   = fields[5].GetFloat();
    uint32 mapid        = fields[6].GetUInt32();

    Object::_Create(guid, 0, HIGHGUID_CORPSE);

    m_time = time_t(fields[7].GetUInt64());
    m_type = CorpseType(fields[8].GetUInt32());

    if (m_type >= MAX_CORPSE_TYPE)
    {
        sLog.outError("Corpse (guidlow %d, owner %d) have wrong corpse type, not load.",GetGUIDLow(),GUID_LOPART(GetOwnerGUID()));
        return false;
    }

    uint32 instanceid   = fields[9].GetUInt32();
    uint32 phaseMask    = fields[10].GetUInt32();
    uint8 gender        = fields[11].GetUInt8();
    uint8 race          = fields[12].GetUInt8();
    uint8 _class        = fields[13].GetUInt8();
    uint32 playerBytes  = fields[14].GetUInt32();
    uint32 playerBytes2 = fields[15].GetUInt32();
    uint32 guildId      = fields[17].GetUInt32();
    uint32 playerFlags  = fields[18].GetUInt32();

    // overwrite possible wrong/corrupted guid
    SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_CORPSE));
    SetUInt64Value(CORPSE_FIELD_OWNER, MAKE_NEW_GUID(playerGuid, 0, HIGHGUID_PLAYER));

    SetObjectScale(DEFAULT_OBJECT_SCALE);

    PlayerInfo const *info = sObjectMgr.GetPlayerInfo(race, _class);
    if (!info)
    {
        sLog.outError("Player %u has incorrect race/class pair.", GetGUIDLow());
        return false;
    }
    SetUInt32Value(CORPSE_FIELD_DISPLAY_ID, gender == GENDER_FEMALE ? info->displayId_f : info->displayId_m);

    // Load equipment
    Tokens data = StrSplit(fields[16].GetCppString(), " ");
    for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; slot++)
    {
        uint32 visualbase = slot * 2;
        uint32 item_id = GetUInt32ValueFromArray(data, visualbase);
        const ItemPrototype * proto = ObjectMgr::GetItemPrototype(item_id);
        if (!proto)
        {
            SetUInt32Value(CORPSE_FIELD_ITEM + slot, 0);
            continue;
        }

        SetUInt32Value(CORPSE_FIELD_ITEM + slot, proto->DisplayInfoID | (proto->InventoryType << 24));
    }

    uint8 skin       = (uint8)(playerBytes);
    uint8 face       = (uint8)(playerBytes >> 8);
    uint8 hairstyle  = (uint8)(playerBytes >> 16);
    uint8 haircolor  = (uint8)(playerBytes >> 24);
    uint8 facialhair = (uint8)(playerBytes2);
    SetUInt32Value( CORPSE_FIELD_BYTES_1, ((0x00) | (race << 8) | (gender << 16) | (skin << 24)) );
    SetUInt32Value( CORPSE_FIELD_BYTES_2, ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24)) );

    SetUInt32Value(CORPSE_FIELD_GUILD, guildId);

    uint32 flags = CORPSE_FLAG_UNK2;
    if (playerFlags & PLAYER_FLAGS_HIDE_HELM)
        flags |= CORPSE_FLAG_HIDE_HELM;
    if (playerFlags & PLAYER_FLAGS_HIDE_CLOAK)
        flags |= CORPSE_FLAG_HIDE_CLOAK;
    SetUInt32Value( CORPSE_FIELD_FLAGS, flags );

    // no need to mark corpse as lootable, because corpses are not saved in battle grounds

    // place
    SetLocationInstanceId(instanceid);
    SetLocationMapId(mapid);
    SetPhaseMask(phaseMask, false);
    Relocate(positionX, positionY, positionZ, orientation);

    if (!IsPositionValid())
    {
        sLog.outError("Corpse (guidlow %d, owner %d) not created. Suggested coordinates isn't valid (X: %f Y: %f)",
            GetGUIDLow(), GUID_LOPART(GetOwnerGUID()), GetPositionX(), GetPositionY());
        return false;
    }

    m_grid = MaNGOS::ComputeGridPair(GetPositionX(), GetPositionY());

    return true;
}
Exemple #8
0
bool Guild::FillPlayerData(uint64 guid, MemberSlot* memslot)
{
    std::string plName;
    uint32 plLevel;
    uint32 plClass;
    uint32 plZone;

    Player* pl = objmgr.GetPlayer(guid);
    if(pl)
    {
        plName  = pl->GetName();
        plLevel = pl->getLevel();
        plClass = pl->getClass();
        plZone  = pl->GetZoneId();
    }
    else
    {
        QueryResult *result = CharacterDatabase.PQuery("SELECT name,data,zone,class FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
        if(!result)
            return false;                                   // player doesn't exist

        Field *fields = result->Fetch();

        plName = fields[0].GetCppString();

        Tokens data = StrSplit(fields[1].GetCppString(), " ");
        plLevel = Player::GetUInt32ValueFromArray(data,UNIT_FIELD_LEVEL);

        plZone = fields[2].GetUInt32();
        plClass = fields[3].GetUInt32();
        delete result;

        if(plLevel<1||plLevel>STRONG_MAX_LEVEL)             // can be at broken `data` field
        {
            sLog.outError("Player (GUID: %u) has a broken data in field `characters`.`data`.",GUID_LOPART(guid));
            return false;
        }

        if(!plZone)
        {
            sLog.outError("Player (GUID: %u) has broken zone-data",GUID_LOPART(guid));
            //here it will also try the same, to get the zone from characters-table, but additional it tries to find
            plZone = Player::GetZoneIdFromDB(guid);
            //the zone through xy coords.. this is a bit redundant, but
            //shouldn't be called often
        }

        if(plClass<CLASS_WARRIOR||plClass>=MAX_CLASSES)     // can be at broken `class` field
        {
            sLog.outError("Player (GUID: %u) has a broken data in field `characters`.`class`.",GUID_LOPART(guid));
            return false;
        }
    }

    memslot->name = plName;
    memslot->level = plLevel;
    memslot->Class = plClass;
    memslot->zoneId = plZone;

    return(true);
}
Exemple #9
0
bool StrSplit(CCharPtr src, std::list<uint32>& strList, std::string sep)
{
	std::string sr = src;
	return StrSplit(sr, strList, sep);
}
Exemple #10
0
bool Rehash()
{
#ifdef WIN32
	char * config_file = "configs/logon.conf";
#else
	char * config_file = (char*)CONFDIR "/logon.conf";
#endif
	if(!Config.MainConfig.SetSource(config_file))
	{
		LOG_ERROR("Config file could not be rehashed.");
		return false;
	}

	// re-set the allowed server IP's
	string ips = Config.MainConfig.GetStringDefault("LogonServer", "AllowedIPs", "");
	string ipsmod = Config.MainConfig.GetStringDefault("LogonServer", "AllowedModIPs", "");

	vector<string> vips = StrSplit(ips, " ");
	vector<string> vipsmod = StrSplit(ips, " ");

	m_allowedIpLock.Acquire();
	m_allowedIps.clear();
	m_allowedModIps.clear();
	vector<string>::iterator itr;
	for(itr = vips.begin(); itr != vips.end(); ++itr)
	{
		string::size_type i = itr->find("/");
		if( i == string::npos )
		{
			LOG_ERROR("IP: %s could not be parsed. Ignoring", itr->c_str());
			continue;
		}

		string stmp = itr->substr(0, i);
		string smask = itr->substr(i+1);

		unsigned int ipraw = MakeIP(stmp.c_str());
		unsigned char ipmask = (char)atoi(smask.c_str());
		if( ipraw == 0 || ipmask == 0 )
		{
			LOG_ERROR("IP: %s could not be parsed. Ignoring", itr->c_str());
			continue;
		}

		AllowedIP tmp;
		tmp.Bytes = ipmask;
		tmp.IP = ipraw;
		m_allowedIps.push_back(tmp);
	}

	for(itr = vipsmod.begin(); itr != vipsmod.end(); ++itr)
	{
		string::size_type i = itr->find("/");
		if( i == string::npos )
		{
			LOG_ERROR("IP: %s could not be parsed. Ignoring", itr->c_str());
			continue;
		}

		string stmp = itr->substr(0, i);
		string smask = itr->substr(i+1);

		unsigned int ipraw = MakeIP(stmp.c_str());
		unsigned char ipmask = (char)atoi(smask.c_str());
		if( ipraw == 0 || ipmask == 0 )
		{
			LOG_ERROR("IP: %s could not be parsed. Ignoring", itr->c_str());
			continue;
		}

		AllowedIP tmp;
		tmp.Bytes = ipmask;
		tmp.IP = ipraw;
		m_allowedModIps.push_back(tmp);
	}

	if( InformationCore::getSingletonPtr() != NULL )
		sInfoCore.CheckServers();

	m_allowedIpLock.Release();

	return true;
}
Exemple #11
0
bool DatabaseMysql::Initialize(const char *infoString)
{

    if(!Database::Initialize(infoString))
        return false;

    tranThread = NULL;
    MYSQL *mysqlInit;
    mysqlInit = mysql_init(NULL);
    if (!mysqlInit)
    {
        sLog.outError( "Could not initialize Mysql connection" );
        return false;
    }

    InitDelayThread();

    Tokens tokens = StrSplit(infoString, ";");

    Tokens::iterator iter;

    std::string host, port_or_socket, user, password, database;
    int port;
    char const* unix_socket;

    iter = tokens.begin();

    if(iter != tokens.end())
        host = *iter++;
    if(iter != tokens.end())
        port_or_socket = *iter++;
    if(iter != tokens.end())
        user = *iter++;
    if(iter != tokens.end())
        password = *iter++;
    if(iter != tokens.end())
        database = *iter++;

    mysql_options(mysqlInit,MYSQL_SET_CHARSET_NAME,"utf8");
    #ifdef WIN32
    if(host==".")                                           // named pipe use option (Windows)
    {
        unsigned int opt = MYSQL_PROTOCOL_PIPE;
        mysql_options(mysqlInit,MYSQL_OPT_PROTOCOL,(char const*)&opt);
        port = 0;
        unix_socket = 0;
    }
    else                                                    // generic case
    {
        port = atoi(port_or_socket.c_str());
        unix_socket = 0;
    }
    #else
    if(host==".")                                           // socket use option (Unix/Linux)
    {
        unsigned int opt = MYSQL_PROTOCOL_SOCKET;
        mysql_options(mysqlInit,MYSQL_OPT_PROTOCOL,(char const*)&opt);
        host = "localhost";
        port = 0;
        unix_socket = port_or_socket.c_str();
    }
    else                                                    // generic case
    {
        port = atoi(port_or_socket.c_str());
        unix_socket = 0;
    }
    #endif

    mMysql = mysql_real_connect(mysqlInit, host.c_str(), user.c_str(),
        password.c_str(), database.c_str(), port, unix_socket, 0);

    if (mMysql)
    {
        DETAIL_LOG( "Connected to MySQL database at %s",
            host.c_str());
        sLog.outString( "MySQL client library: %s", mysql_get_client_info());
        sLog.outString( "MySQL server ver: %s ", mysql_get_server_info( mMysql));

        /*----------SET AUTOCOMMIT ON---------*/
        // It seems mysql 5.0.x have enabled this feature
        // by default. In crash case you can lose data!!!
        // So better to turn this off
        // ---
        // This is wrong since mangos use transactions,
        // autocommit is turned of during it.
        // Setting it to on makes atomic updates work
        if (!mysql_autocommit(mMysql, 1))
            DETAIL_LOG("AUTOCOMMIT SUCCESSFULLY SET TO 1");
        else
            DETAIL_LOG("AUTOCOMMIT NOT SET TO 1");
        /*-------------------------------------*/

        // set connection properties to UTF8 to properly handle locales for different
        // server configs - core sends data in UTF8, so MySQL must expect UTF8 too
        PExecute("SET NAMES `utf8`");
        PExecute("SET CHARACTER SET `utf8`");

#if MYSQL_VERSION_ID >= 50003
         my_bool my_true = (my_bool)1;
         if (mysql_options(mMysql, MYSQL_OPT_RECONNECT, &my_true))
         {
             sLog.outDetail("Failed to turn on MYSQL_OPT_RECONNECT.");
         }
         else
         {
             sLog.outDetail("Successfully turned on MYSQL_OPT_RECONNECT.");
         }
#else
         sLog.outDetail("Your mySQL client lib version does not support reconnecting after a timeout.");
         sLog.outDetail("If this causes you any trouble we advice you to upgrade");
         sLog.outDetail("Your mySQL client libs to at least mySQL 5.0.13 to resolve this problem.");
#endif

        return true;
    }
    else
    {
        sLog.outError( "Could not connect to MySQL database at %s: %s\n",
            host.c_str(),mysql_error(mysqlInit));
        mysql_close(mysqlInit);
        return false;
    }
}
Exemple #12
0
bool DatabaseMysql::Initialize(const char *infoString)
{

    if(!Database::Initialize(infoString))
        return false;

    tranThread = NULL;
    MYSQL *mysqlInit;
    mysqlInit = mysql_init(NULL);
    if (!mysqlInit)
    {
        sLog.outError( "Could not initialize Mysql connection" );
        return false;
    }

    InitDelayThread();

    Tokens tokens = StrSplit(infoString, ";");

    Tokens::iterator iter;

    std::string host, port_or_socket, user, password, database;
    int port;
    char const* unix_socket;

    iter = tokens.begin();

    if(iter != tokens.end())
        host = *iter++;
    if(iter != tokens.end())
        port_or_socket = *iter++;
    if(iter != tokens.end())
        user = *iter++;
    if(iter != tokens.end())
        password = *iter++;
    if(iter != tokens.end())
        database = *iter++;

    mysql_options(mysqlInit,MYSQL_SET_CHARSET_NAME,"utf8");
#ifdef WIN32
    if(host==".")                                           // named pipe use option (Windows)
    {
        unsigned int opt = MYSQL_PROTOCOL_PIPE;
        mysql_options(mysqlInit,MYSQL_OPT_PROTOCOL,(char const*)&opt);
        port = 0;
        unix_socket = 0;
    }
    else                                                    // generic case
    {
        port = atoi(port_or_socket.c_str());
        unix_socket = 0;
    }
#else
    if(host==".")                                           // socket use option (Unix/Linux)
    {
        unsigned int opt = MYSQL_PROTOCOL_SOCKET;
        mysql_options(mysqlInit,MYSQL_OPT_PROTOCOL,(char const*)&opt);
        host = "localhost";
        port = 0;
        unix_socket = port_or_socket.c_str();
    }
    else                                                    // generic case
    {
        port = atoi(port_or_socket.c_str());
        unix_socket = 0;
    }
#endif

    mMysql = mysql_real_connect(mysqlInit, host.c_str(), user.c_str(),
        password.c_str(), database.c_str(), port, unix_socket, 0);

    if (mMysql)
    {
        sLog.outDetail( "Connected to MySQL database at %s\r\n",
            host.c_str());
        sLog.outString( "MySQL client library: %s", mysql_get_client_info());
        sLog.outString( "MySQL server ver: %s ", mysql_get_server_info( mMysql));

        /*----------SET AUTOCOMMIT ON---------*/
        // It seems mysql 5.0.x have enabled this feature
        // by default. In crash case you can lose data!!!
        // So better to turn this off
        // ---
        // This is wrong since mangos use transactions,
        // autocommit is turned of during it.
        // Setting it to on makes atomic updates work
        if (!mysql_autocommit(mMysql, 1))
            sLog.outDetail("AUTOCOMMIT SUCCESSFULLY SET TO 1");
        else
            sLog.outDetail("AUTOCOMMIT NOT SET TO 1");
        /*-------------------------------------*/
        return true;
    }
    else
    {
        sLog.outError( "Could not connect to MySQL database at %s: %s\n",
            host.c_str(),mysql_error(mysqlInit));
        mysql_close(mysqlInit);
        return false;
    }
}
Exemple #13
0
void ObjectMgr::LoadExtraCreatureProtoStuff()
{
	{
		StorageContainerIterator<CreatureProto> * itr = CreatureProtoStorage.MakeIterator();
		CreatureProto* cn;
		while(!itr->AtEnd())
		{
			cn = itr->Get();

			// Process spell fields
			for( uint32 i = 0; i < MAX_CREATURE_PROTO_SPELLS; i++ ){
				if( cn->AISpells[ i ] == 0 )
					continue;

				SpellEntry *sp = dbcSpell.LookupEntryForced( cn->AISpells[ i ] );
				if( sp == NULL )
					continue;

				if( ( sp->Attributes & ATTRIBUTES_PASSIVE ) == 0 )
					cn->castable_spells.push_back( sp->Id );
				else
					cn->start_auras.insert( sp->Id );

			}

			// process creature spells from creaturespelldata.dbc
			if( cn->spelldataid != 0 ){
				CreatureSpellDataEntry* spe = dbcCreatureSpellData.LookupEntry( cn->spelldataid );
				for( uint32 i = 0; i < 3; i++ ){
					if( spe->Spells[ i ] == 0 )
						continue;

					SpellEntry *sp = dbcSpell.LookupEntryForced( spe->Spells[ i ] );
					if( sp == NULL )
						continue;

					if( ( sp->Attributes & ATTRIBUTES_PASSIVE ) == 0 )
						cn->castable_spells.push_back( sp->Id );
					else
						cn->start_auras.insert( sp->Id );
				}
			}

			if(cn->aura_string)
			{
				string auras = string(cn->aura_string);
				vector<string> aurs = StrSplit(auras, " ");
				for(vector<string>::iterator it = aurs.begin(); it != aurs.end(); ++it)
				{
					uint32 id = atol((*it).c_str());
					if(id)
						cn->start_auras.insert(id);
				}
			}

			if(!cn->MinHealth)
				cn->MinHealth = 1;
			if(!cn->MaxHealth)
				cn->MaxHealth = 1;
			if(cn->AttackType > SCHOOL_ARCANE)
				cn->AttackType = SCHOOL_NORMAL;

			cn->m_canFlee = cn->m_canRangedAttack = cn->m_canCallForHelp = false;
			cn->m_fleeHealth = 0.0f;
			// please.... m_fleeDuration is a uint32...
			//cn->m_fleeDuration = 0.0f;
			cn->m_fleeDuration = 0;

			if(!itr->Inc())
				break;
		}

		itr->Destruct();
	}

	{
		StorageContainerIterator<CreatureInfo> * itr = CreatureNameStorage.MakeIterator();
		CreatureInfo* ci;
		while(!itr->AtEnd())
		{
			ci = itr->Get();

			ci->lowercase_name = string(ci->Name);
			for(uint32 j = 0; j < ci->lowercase_name.length(); ++j)
				ci->lowercase_name[j] = static_cast<char>(tolower(ci->lowercase_name[j]));   // Darvaleo 2008/08/15 - Copied lowercase conversion logic from ItemPrototype task

			for(int i = 0; i < NUM_MONSTER_SAY_EVENTS; i++)
				ci->MonsterSay[i] = objmgr.HasMonsterSay(ci->Id, MONSTER_SAY_EVENTS(i));

			if(!itr->Inc())
				break;
		}
		itr->Destruct();
	}

	// Load AI Agents
	if(Config.MainConfig.GetBoolDefault("Server", "LoadAIAgents", true))
	{
		QueryResult* result = WorldDatabase.Query("SELECT * FROM ai_agents");
		CreatureProto* cn;

		if(result != NULL)
		{
			AI_Spell* sp;
			SpellEntry* spe;
			uint32 entry;

			do
			{
				Field* fields = result->Fetch();
				entry = fields[0].GetUInt32();
				cn = CreatureProtoStorage.LookupEntry(entry);
				spe = dbcSpell.LookupEntryForced(fields[6].GetUInt32());
				if(spe == NULL)
				{
					Log.Error("AIAgent", "For %u has nonexistent spell %u.", fields[0].GetUInt32(), fields[6].GetUInt32());
					continue;
				}
				if(!cn)
					continue;

				sp = new AI_Spell;
				sp->entryId = fields[0].GetUInt32();
				sp->instance_mode = fields[1].GetUInt32();
				sp->agent = fields[2].GetUInt16();
				sp->procChance = fields[4].GetUInt32();
				sp->procCount = fields[5].GetUInt32();
				sp->spell = spe;
				sp->spellType = static_cast<uint8>(fields[7].GetUInt32());

				int32  targettype = fields[8].GetInt32();
				if(targettype == -1)
					sp->spelltargetType = static_cast<uint8>(GetAiTargetType(spe));
				else sp->spelltargetType = static_cast<uint8>(targettype);

				sp->cooldown = fields[9].GetInt32();
				sp->floatMisc1 = fields[10].GetFloat();
				sp->autocast_type = (uint32) - 1;
				sp->cooldowntime = getMSTime();
				sp->procCounter = 0;
				sp->Misc2 = fields[11].GetUInt32();
				if(sp->agent == AGENT_SPELL)
				{
					if(!sp->spell)
					{
						LOG_DEBUG("SpellId %u in ai_agent for %u is invalid.", (unsigned int)fields[6].GetUInt32(), (unsigned int)sp->entryId);
						delete sp;
						sp = NULL;
						continue;
					}

					if(sp->spell->Effect[0] == SPELL_EFFECT_LEARN_SPELL || sp->spell->Effect[1] == SPELL_EFFECT_LEARN_SPELL ||
					        sp->spell->Effect[2] == SPELL_EFFECT_LEARN_SPELL)
					{
						LOG_DEBUG("Teaching spell %u in ai_agent for %u", (unsigned int)fields[6].GetUInt32(), (unsigned int)sp->entryId);
						delete sp;
						sp = NULL;
						continue;
					}

					sp->minrange = GetMinRange(dbcSpellRange.LookupEntry(sp->spell->rangeIndex));
					sp->maxrange = GetMaxRange(dbcSpellRange.LookupEntry(sp->spell->rangeIndex));

					//omg the poor darling has no clue about making ai_agents
					if(sp->cooldown == (uint32) - 1)
					{
						//now this will not be exact cooldown but maybe a bigger one to not make him spam spells to often
						int cooldown;
						SpellDuration* sd = dbcSpellDuration.LookupEntry(sp->spell->DurationIndex);
						int Dur = 0;
						int Casttime = 0; //most of the time 0
						int RecoveryTime = sp->spell->RecoveryTime;
						if(sp->spell->DurationIndex)
							Dur =::GetDuration(sd);
						Casttime = GetCastTime(dbcSpellCastTime.LookupEntry(sp->spell->CastingTimeIndex));
						cooldown = Dur + Casttime + RecoveryTime;
						if(cooldown < 0)
							sp->cooldown = 2000; //huge value that should not loop while adding some timestamp to it
						else sp->cooldown = cooldown;
					}

					/*
					//now apply the moron filter
					if(sp->procChance== 0)
					{
						//printf("SpellId %u in ai_agent for %u is invalid.\n", (unsigned int)fields[5].GetUInt32(), (unsigned int)sp->entryId);
						delete sp;
						sp = NULL;
						continue;
					}
					if(sp->spellType== 0)
					{
						//right now only these 2 are used
						if(IsBeneficSpell(sp->spell))
							sp->spellType==STYPE_HEAL;
						else sp->spellType==STYPE_BUFF;
					}
					if(sp->spelltargetType== 0)
						sp->spelltargetType = RecommandAISpellTargetType(sp->spell);
						*/
				}

				if(sp->agent == AGENT_RANGED)
				{
					cn->m_canRangedAttack = true;
					delete sp;
					sp = NULL;
				}
				else if(sp->agent == AGENT_FLEE)
				{
					cn->m_canFlee = true;
					if(sp->floatMisc1)
						cn->m_canFlee = (sp->floatMisc1 > 0.0f ? true : false);
					else
						cn->m_fleeHealth = 0.2f;

					if(sp->Misc2)
						cn->m_fleeDuration = sp->Misc2;
					else
						cn->m_fleeDuration = 10000;

					delete sp;
					sp = NULL;
				}
				else if(sp->agent == AGENT_CALLFORHELP)
				{
					cn->m_canCallForHelp = true;
					if(sp->floatMisc1)
						cn->m_callForHelpHealth = 0.2f;
					delete sp;
					sp = NULL;
				}
				else
				{
					cn->spells.push_back(sp);
				}
			}
			while(result->NextRow());

			delete result;
		}
	}
}
Exemple #14
0
bool Item::LoadFromDB(uint32 guid, uint64 owner_guid, QueryResult_AutoPtr result, uint32 entry)
{
    //                                                    0                1      2         3        4      5             6                 7           8           9    10
    //result = CharacterDatabase.PQuery("SELECT creatorGuid, giftCreatorGuid, count, duration, charges, flags, enchantments, randomPropertyId, durability, playedTime, text FROM item_instance WHERE guid = '%u'", guid);

    // create item before any checks for store correct guid
    // and allow use "FSetState(ITEM_REMOVED); SaveToDB();" for deleting item from DB
    Object::_Create(guid, 0, HIGHGUID_ITEM);

    // Set entry, MUST be before proto check
    SetEntry(entry);
    SetFloatValue(OBJECT_FIELD_SCALE_X, 1.0f);

    ItemPrototype const* proto = GetProto();
    if (!proto)
        return false;

    if (!result)
    {
        sLog.outError("Item (GUID: %u owner: %u) not found in table `item_instance`, can't load. ", guid, GUID_LOPART(owner_guid));
        return false;
    }

    // set owner (not if item is only loaded for gbank/auction/mail
    if (owner_guid != 0)
        SetOwnerGUID(owner_guid);

    Field *fields = result->Fetch();
    bool need_save = false;                                 // need explicit save data at load fixes
    SetUInt64Value(ITEM_FIELD_CREATOR, MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER));
    SetUInt64Value(ITEM_FIELD_GIFTCREATOR, MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_PLAYER));
    SetCount(fields[2].GetUInt32());

    uint32 duration = fields[3].GetUInt32();
    SetUInt32Value(ITEM_FIELD_DURATION, duration);
    // update duration if need, and remove if not need
    if ((proto->Duration == 0) != (duration == 0))
    {
        SetUInt32Value(ITEM_FIELD_DURATION, abs(proto->Duration));
        need_save = true;
    }

    Tokens tokens = StrSplit(fields[4].GetCppString(), " ");
    if (tokens.size() == MAX_ITEM_PROTO_SPELLS)
        for (uint8 i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
            SetSpellCharges(i, atoi(tokens[i].c_str()));

    SetUInt32Value(ITEM_FIELD_FLAGS, fields[5].GetUInt32());
    // Remove bind flag for items vs NO_BIND set
    if (IsSoulBound() && proto->Bonding == NO_BIND)
    {
        ApplyModFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_BINDED, false);
        need_save = true;
    }

    _LoadIntoDataField(fields[6].GetString(), ITEM_FIELD_ENCHANTMENT_1_1, MAX_ENCHANTMENT_SLOT * MAX_ENCHANTMENT_OFFSET);
    SetInt32Value(ITEM_FIELD_RANDOM_PROPERTIES_ID, fields[7].GetInt32());
    // recalculate suffix factor
    if (GetItemRandomPropertyId() < 0)
        UpdateItemSuffixFactor();

    uint32 durability = fields[8].GetUInt32();
    SetUInt32Value(ITEM_FIELD_DURABILITY, durability);
    // update max durability (and durability) if need
    SetUInt32Value(ITEM_FIELD_MAXDURABILITY, proto->MaxDurability);
    if (durability > proto->MaxDurability)
    {
        SetUInt32Value(ITEM_FIELD_DURABILITY, proto->MaxDurability);
        need_save = true;
    }

    SetUInt32Value(ITEM_FIELD_CREATE_PLAYED_TIME, fields[9].GetUInt32());
    SetText(fields[10].GetCppString());

    if (need_save)                                           // normal item changed state set not work at loading
    {
        std::ostringstream ss;
        ss << "UPDATE item_instance SET duration = " << GetUInt32Value(ITEM_FIELD_DURABILITY)
            << ", flags = " << GetUInt32Value(ITEM_FIELD_FLAGS)
            << ", durability = " << GetUInt32Value(ITEM_FIELD_DURABILITY)
            << " WHERE guid = " << guid;

        CharacterDatabase.Execute(ss.str().c_str());
    }

    return true;
}
Exemple #15
0
bool Database::Initialize(const char *infoString)
{
    // Enable logging of SQL commands (usally only GM commands)
    // (See method: PExecuteLog)
    m_logSQL = sConfig.GetBoolDefault("LogSQL", false);
    m_logsDir = sConfig.GetStringDefault("LogsDir","");
    if (!m_logsDir.empty())
    {
        if ((m_logsDir.at(m_logsDir.length()-1)!='/') && (m_logsDir.at(m_logsDir.length()-1)!='\\'))
            m_logsDir.append("/");
    }

    tranThread = NULL;
    MYSQL *mysqlInit;
    mysqlInit = mysql_init(NULL);
    if (!mysqlInit)
    {
        sLog.outError("Could not initialize Mysql connection");
        sleep(5);
        return false;
    }

    InitDelayThread();

    Tokens tokens = StrSplit(infoString, ";");

    Tokens::iterator iter;

    std::string host, port_or_socket, user, password, database;
    int port;
    char const* unix_socket;

    iter = tokens.begin();

    if (iter != tokens.end())
        host = *iter++;
    if (iter != tokens.end())
        port_or_socket = *iter++;
    if (iter != tokens.end())
        user = *iter++;
    if (iter != tokens.end())
        password = *iter++;
    if (iter != tokens.end())
        database = *iter++;

    mysql_options(mysqlInit, MYSQL_SET_CHARSET_NAME, "utf8");
    #ifdef _WIN32
    if (host==".")                                           // named pipe use option (Windows)
    {
        unsigned int opt = MYSQL_PROTOCOL_PIPE;
        mysql_options(mysqlInit, MYSQL_OPT_PROTOCOL, (char const*)&opt);
        port = 0;
        unix_socket = 0;
    }
    else                                                    // generic case
    {
        port = atoi(port_or_socket.c_str());
        unix_socket = 0;
    }
    #else
    if (host==".")                                           // socket use option (Unix/Linux)
    {
        unsigned int opt = MYSQL_PROTOCOL_SOCKET;
        mysql_options(mysqlInit, MYSQL_OPT_PROTOCOL, (char const*)&opt);
        host = "localhost";
        port = 0;
        unix_socket = port_or_socket.c_str();
    }
    else                                                    // generic case
    {
        port = atoi(port_or_socket.c_str());
        unix_socket = 0;
    }
    #endif

    mMysql = mysql_real_connect(mysqlInit, host.c_str(), user.c_str(),
        password.c_str(), database.c_str(), port, unix_socket, 0);

    if (mMysql)
    {
        sLog.outDetail("Connected to MySQL database at %s", host.c_str());
        sLog.outString("MySQL client library: %s", mysql_get_client_info());
        sLog.outString("MySQL server ver: %s ", mysql_get_server_info( mMysql));

        if (!mysql_autocommit(mMysql, 1))
            sLog.outDetail("AUTOCOMMIT SUCCESSFULLY SET TO 1");
        else
            sLog.outDetail("AUTOCOMMIT NOT SET TO 1");

        // set connection properties to UTF8 to properly handle locales for different
        // server configs - core sends data in UTF8, so MySQL must expect UTF8 too
        PExecute("SET NAMES `utf8`");
        PExecute("SET CHARACTER SET `utf8`");

    #if MYSQL_VERSION_ID >= 50003
        my_bool my_true = (my_bool)1;
        if (mysql_options(mMysql, MYSQL_OPT_RECONNECT, &my_true))
            sLog.outDetail("Failed to turn on MYSQL_OPT_RECONNECT.");
        else
           sLog.outDetail("Successfully turned on MYSQL_OPT_RECONNECT.");
    #else
        #warning "Your mySQL client lib version does not support reconnecting after a timeout.\nIf this causes you any trouble we advice you to upgrade your mySQL client libs to at least mySQL 5.0.13 to resolve this problem."
    #endif
        return true;
    }
    else
    {
        sLog.outError("BC> %s", mysql_error(mysqlInit));
        mysql_close(mysqlInit);
        sleep(5);
        return false;
    }
}
Exemple #16
0
void LocalizationMgr::Reload(bool first)
{
    if (first)
        return;

    QueryResult* result;
    std::set<std::string> languages;
    std::map<std::string, std::string> bound_languages;
    GetDistinctLanguages(languages, "creature_names_localized");
    GetDistinctLanguages(languages, "gameobject_names_localized");
    GetDistinctLanguages(languages, "items_localized");
    GetDistinctLanguages(languages, "quests_localized");
    GetDistinctLanguages(languages, "npc_text_localized");
    GetDistinctLanguages(languages, "itempages_localized");
    GetDistinctLanguages(languages, "gossip_menu_option_localized");
    GetDistinctLanguages(languages, "worldstring_tables_localized");
    GetDistinctLanguages(languages, "worldbroadcast_localized");
    GetDistinctLanguages(languages, "worldmap_info_localized");
    GetDistinctLanguages(languages, "npc_monstersay_localized");

    /// Read Language Bindings From Config
    std::string ls = Config.MainConfig.GetStringDefault("Localization", "LocaleBindings", "");
    std::vector<std::string> tbindings = StrSplit(ls, " ");
    for (std::vector<std::string>::iterator ztr = tbindings.begin(); ztr != tbindings.end(); ++ztr)
    {
        char lb[MAX_LOCALIZED_CHAR];
        std::string ll1, ll2;
        strncpy(lb, (*ztr).c_str(), MAX_LOCALIZED_CHAR);
        lb[MAX_LOCALIZED_CHAR - 1] = '\0';

        char* lbp = strchr(lb, '=');
        if (lbp == NULL)
            continue;
        *lbp = 0;
        lbp++;

        ll1 = std::string(lb);
        ll2 = std::string(lbp);
        Lower(ll1);
        Lower(ll2);

        if (languages.find(ll1) == languages.end())
        {
            bound_languages[ll1] = ll2;
            languages.insert(ll1);
        }
    }

    /// Generate Language IDs
    uint32 langid = 1;
    std::pair<uint32, uint32> dpr;
    for (std::set<std::string>::iterator sitr = languages.begin(); sitr != languages.end(); ++sitr)
    {
        if ((*sitr) == "enus")        // Default
        {
            dpr.first = *(uint32*)sitr->c_str();
            dpr.second = 0;
        }
        else
        {
            dpr.first = *(uint32*)sitr->c_str();
            dpr.second = langid++;
        }

        m_languages.push_back(dpr);
    }

    if (m_languages.size() == 0)
    {
        m_disabled = true;
        return;                 // No localizations
    }
    else
        m_disabled = false;

    m_CreatureNames = new std::unordered_map<uint32, LocalizedCreatureName>[langid];
    m_GameObjectNames = new std::unordered_map<uint32, LocalizedGameObjectName>[langid];
    m_Quests = new std::unordered_map<uint32, LocalizedQuest>[langid];
    m_NpcTexts = new std::unordered_map<uint32, LocalizedNpcText>[langid];
    m_Items = new std::unordered_map<uint32, LocalizedItem>[langid];
    m_ItemPages = new std::unordered_map<uint32, LocalizedItemPage>[langid];
    m_CreatureText = new std::unordered_map<uint32, LocalizedCreatureText>[langid];
    m_GossipMenuOption = new std::unordered_map<uint32, LocalizedGossipMenuOption>[langid];
    m_WorldStrings = new std::unordered_map<uint32, LocalizedWorldStringTable>[langid];
    m_WorldBroadCast = new std::unordered_map<uint32, LocalizedWorldBroadCast>[langid];
    m_WorldMapInfo = new std::unordered_map<uint32, LocalizedWorldMapInfo>[langid];
    m_MonsterSay = new std::unordered_map<uint32, LocalizedMonstersay>[langid];

    //////////////////////////////////////////////////////////////////////////////////////////
    // Creature Names
    {
        LocalizedCreatureName cn;
        std::string str;
        uint32 entry;
        Field* f;
        uint32 lid;

        result = WorldDatabase.Query("SELECT * FROM creature_names_localized");
        if (result)
        {
            do
            {
                f = result->Fetch();
                str = std::string(f[1].GetString());
                entry = f[0].GetUInt32();

                lid = GetLanguageId(str);
                if (lid == 0)
                    continue;        // no loading enUS stuff.. lawl

                cn.Name = strdup(f[2].GetString());
                cn.SubName = strdup(f[3].GetString());
                m_CreatureNames[lid].insert(std::make_pair(entry, cn));
            }
            while (result->NextRow());
            delete result;
        }
    }

    //////////////////////////////////////////////////////////////////////////////////////////
    // GameObject Names
    {
        LocalizedGameObjectName gn;
        std::string str;
        uint32 entry;
        Field* f;
        uint32 lid;

        result = WorldDatabase.Query("SELECT * FROM gameobject_names_localized");
        if (result)
        {
            do
            {
                f = result->Fetch();
                str = std::string(f[1].GetString());
                entry = f[0].GetUInt32();

                lid = GetLanguageId(str);
                if (lid == 0)
                    continue;        // no loading enUS stuff.. lawl

                gn.Name = strdup(f[2].GetString());
                m_GameObjectNames[lid].insert(std::make_pair(entry, gn));
            }
            while (result->NextRow());
            delete result;
        }
    }

    //////////////////////////////////////////////////////////////////////////////////////////
    // Items
    {
        LocalizedItem it;
        std::string str;
        uint32 entry;
        Field* f;
        uint32 lid;

        result = WorldDatabase.Query("SELECT * FROM items_localized");
        if (result)
        {
            do
            {
                f = result->Fetch();
                str = std::string(f[1].GetString());
                entry = f[0].GetUInt32();

                lid = GetLanguageId(str);
                if (lid == 0)
                    continue;        // no loading enUS stuff.. lawl

                if (m_Items[lid].find(entry) != m_Items[lid].end())
                {
                    continue;
                }

                it.Name = strdup(f[2].GetString());
                it.Description = strdup(f[3].GetString());
                m_Items[lid].insert(std::make_pair(entry, it));
            }
            while (result->NextRow());
            delete result;
        }
    }

    //////////////////////////////////////////////////////////////////////////////////////////
    // Quests
    {
        LocalizedQuest q;
        std::string str;
        uint32 entry;
        Field* f;
        uint32 lid;

        result = WorldDatabase.Query("SELECT * FROM quests_localized");
        if (result)
        {
            do
            {
                f = result->Fetch();
                str = std::string(f[1].GetString());
                entry = f[0].GetUInt32();

                lid = GetLanguageId(str);
                if (lid == 0)
                    continue;        // no loading enUS stuff.. lawl

                q.Title = strdup(f[2].GetString());
                q.Details = strdup(f[3].GetString());
                q.Objectives = strdup(f[4].GetString());
                q.CompletionText = strdup(f[5].GetString());
                q.IncompleteText = strdup(f[6].GetString());
                q.EndText = strdup(f[7].GetString());
                q.ObjectiveText[0] = strdup(f[8].GetString());
                q.ObjectiveText[1] = strdup(f[9].GetString());
                q.ObjectiveText[2] = strdup(f[10].GetString());
                q.ObjectiveText[3] = strdup(f[11].GetString());

                m_Quests[lid].insert(std::make_pair(entry, q));
            }
            while (result->NextRow());
            delete result;
        }
    }

    //////////////////////////////////////////////////////////////////////////////////////////
    // NPC Texts
    {
        LocalizedNpcText nt;
        std::string str;
        uint32 entry;
        Field* f;
        uint32 lid;
        uint32 counter;

        result = WorldDatabase.Query("SELECT * FROM npc_text_localized");
        if (result)
        {
            do
            {
                f = result->Fetch();
                str = std::string(f[1].GetString());
                entry = f[0].GetUInt32();

                lid = GetLanguageId(str);
                if (lid == 0)
                    continue;        // no loading enUS stuff.. lawl

                counter = 2;
                for (uint8 i = 0; i < 8; ++i)
                {
                    nt.Texts[i][0] = strdup(f[counter++].GetString());
                    nt.Texts[i][1] = strdup(f[counter++].GetString());
                }

                m_NpcTexts[lid].insert(std::make_pair(entry, nt));
            }
            while (result->NextRow());
            delete result;
        }
    }
    //////////////////////////////////////////////////////////////////////////////////////////
    // Item Pages
    {
        LocalizedItemPage nt;
        std::string str;
        uint32 entry;
        Field* f;
        uint32 lid;

        result = WorldDatabase.Query("SELECT * FROM itempages_localized");
        if (result)
        {
            do
            {
                f = result->Fetch();
                str = std::string(f[1].GetString());
                entry = f[0].GetUInt32();

                lid = GetLanguageId(str);
                if (lid == 0)
                    continue;        // no loading enUS stuff.. lawl

                nt.Text = strdup(f[2].GetString());
                m_ItemPages[lid].insert(std::make_pair(entry, nt));
            }
            while (result->NextRow());
            delete result;
        }
    }

    //////////////////////////////////////////////////////////////////////////////////////////
    // Creature Text
    {
        LocalizedCreatureText nt;
        std::string str;
        uint32 entry;
        Field* f;
        uint32 lid;

        result = WorldDatabase.Query("SELECT * FROM npc_script_text_localized");
        if (result)
        {
            do
            {
                f = result->Fetch();
                str = std::string(f[1].GetString());
                entry = f[0].GetUInt32();

                lid = GetLanguageId(str);
                if (lid == 0)
                    continue;

                nt.Text = strdup(f[2].GetString());
                m_CreatureText[lid].insert(std::make_pair(entry, nt));
            }
            while (result->NextRow());
            delete result;
        }
    }

    //////////////////////////////////////////////////////////////////////////////////////////
    // Gossip Menu Option
    {
        LocalizedGossipMenuOption nt;
        std::string str;
        uint32 entry;
        Field* f;
        uint32 lid;

        result = WorldDatabase.Query("SELECT * FROM gossip_menu_option_localized");
        if (result)
        {
            do
            {
                f = result->Fetch();
                str = std::string(f[1].GetString());
                entry = f[0].GetUInt32();

                lid = GetLanguageId(str);
                if (lid == 0)
                    continue;

                nt.Text = strdup(f[2].GetString());
                m_GossipMenuOption[lid].insert(std::make_pair(entry, nt));
            }
            while (result->NextRow());
            delete result;
        }
    }

    //////////////////////////////////////////////////////////////////////////////////////////
    // World Common Message
    {
        LocalizedWorldStringTable nt;
        std::string str;
        uint32 entry;
        Field* f;
        uint32 lid;

        result = WorldDatabase.Query("SELECT * FROM worldstring_tables_localized");
        if (result)
        {
            do
            {
                f = result->Fetch();
                str = std::string(f[1].GetString());
                entry = f[0].GetUInt32();

                lid = GetLanguageId(str);
                if (lid == 0)
                    continue;

                nt.Text = strdup(f[2].GetString());
                m_WorldStrings[lid].insert(std::make_pair(entry, nt));
            }
            while (result->NextRow());
            delete result;
        }
    }

    //////////////////////////////////////////////////////////////////////////////////////////
    // World BroadCast Messages
    {
        LocalizedWorldBroadCast nt;
        std::string str;
        uint32 entry;
        Field* f;
        uint32 lid;

        result = WorldDatabase.Query("SELECT * FROM worldbroadcast_localized");
        if (result)
        {
            do
            {
                f = result->Fetch();
                str = std::string(f[1].GetString());
                entry = f[0].GetUInt32();

                lid = GetLanguageId(str);
                if (lid == 0)
                    continue;

                nt.Text = strdup(f[2].GetString());
                m_WorldBroadCast[lid].insert(std::make_pair(entry, nt));
            }
            while (result->NextRow());
            delete result;
        }
    }

    //////////////////////////////////////////////////////////////////////////////////////////
    // World MapInfo Entry Name
    {
        LocalizedWorldMapInfo nt;
        std::string str;
        uint32 entry;
        Field* f;
        uint32 lid;

        result = WorldDatabase.Query("SELECT * FROM worldmap_info_localized");
        if (result)
        {
            do
            {
                f = result->Fetch();
                str = std::string(f[1].GetString());
                entry = f[0].GetUInt32();

                lid = GetLanguageId(str);
                if (lid == 0)
                    continue;

                nt.Text = strdup(f[2].GetString());
                m_WorldMapInfo[lid].insert(std::make_pair(entry, nt));
            }
            while (result->NextRow());
            delete result;
        }
    }

    //////////////////////////////////////////////////////////////////////////////////////////
    // NPC Monstersay
    {
        LocalizedMonstersay ms;
        std::string str;
        uint32 entry;
        Field* f;
        uint32 lid;

        sLog.outString("Loading npc_monstersay_localized rows...");
        result = WorldDatabase.Query("SELECT * FROM npc_monstersay_localized");
        if (result)
        {
            do
            {
                f = result->Fetch();
                str = std::string(f[1].GetString());
                entry = f[0].GetUInt32();

                lid = GetLanguageId(str);
                if (lid == 0)
                    continue;        // no loading enUS stuff.. lawl

                ms.monstername = strdup(f[2].GetString());
                ms.text0 = strdup(f[3].GetString());
                ms.text1 = strdup(f[4].GetString());
                ms.text2 = strdup(f[5].GetString());
                ms.text3 = strdup(f[6].GetString());
                ms.text4 = strdup(f[7].GetString());

                m_MonsterSay[lid].insert(std::make_pair(entry, ms));
            }
            while (result->NextRow());
            delete result;
        }
    }


    //////////////////////////////////////////////////////////////////////////////////////////
    // Apply all the language bindings.
    for (std::map<std::string, std::string>::iterator itr = bound_languages.begin(); itr != bound_languages.end(); ++itr)
    {
        uint32 source_language_id = GetLanguageId(itr->second);
        uint32 dest_language_id = GetLanguageId(itr->first);
        if (source_language_id == 0 || dest_language_id == 0)
        {
            sLog.Error("LocalizationMgr", "Invalid locale conversion string specified: %u->%u (%s->%s)", source_language_id, dest_language_id, itr->second.c_str(), itr->first.c_str());
            continue;
        }

        // duplicate the hashmaps (we can save the pointers here)
        CopyHashMap<LocalizedItem>(&m_Items[source_language_id], &m_Items[dest_language_id]);
        CopyHashMap<LocalizedCreatureName>(&m_CreatureNames[source_language_id], &m_CreatureNames[dest_language_id]);
        CopyHashMap<LocalizedGameObjectName>(&m_GameObjectNames[source_language_id], &m_GameObjectNames[dest_language_id]);
        CopyHashMap<LocalizedItemPage>(&m_ItemPages[source_language_id], &m_ItemPages[dest_language_id]);
        CopyHashMap<LocalizedQuest>(&m_Quests[source_language_id], &m_Quests[dest_language_id]);
        CopyHashMap<LocalizedNpcText>(&m_NpcTexts[source_language_id], &m_NpcTexts[dest_language_id]);
        CopyHashMap<LocalizedCreatureText>(&m_CreatureText[source_language_id], &m_CreatureText[dest_language_id]);
        CopyHashMap<LocalizedGossipMenuOption>(&m_GossipMenuOption[source_language_id], &m_GossipMenuOption[dest_language_id]);
        CopyHashMap<LocalizedWorldStringTable>(&m_WorldStrings[source_language_id], &m_WorldStrings[dest_language_id]);
        CopyHashMap<LocalizedWorldBroadCast>(&m_WorldBroadCast[source_language_id], &m_WorldBroadCast[dest_language_id]);
        CopyHashMap<LocalizedWorldMapInfo>(&m_WorldMapInfo[source_language_id], &m_WorldMapInfo[dest_language_id]);
        CopyHashMap<LocalizedMonstersay>(&m_MonsterSay[source_language_id], &m_MonsterSay[dest_language_id]);
    }
}
Exemple #17
0
Channel::Channel(const std::string& name, uint32 channel_id, uint32 Team)
 : m_announce(true), m_moderate(false), m_name(name), m_password(""), m_flags(0), m_channelId(channel_id), m_ownerGUID(0), m_Team(Team)
{
    // set special flags if built-in channel
    ChatChannelsEntry const* ch = GetChannelEntryFor(channel_id);
    if (ch)                                                  // it's built-in channel
    {
        channel_id = ch->ChannelID;                         // built-in channel
        m_announce = false;                                 // no join/leave announces

        m_flags |= CHANNEL_FLAG_GENERAL;                    // for all built-in channels

        if (ch->flags & CHANNEL_DBC_FLAG_TRADE)              // for trade channel
            m_flags |= CHANNEL_FLAG_TRADE;

        if (ch->flags & CHANNEL_DBC_FLAG_CITY_ONLY2)         // for city only channels
            m_flags |= CHANNEL_FLAG_CITY;

        if (ch->flags & CHANNEL_DBC_FLAG_LFG)                // for LFG channel
            m_flags |= CHANNEL_FLAG_LFG;
        else                                                // for all other channels
            m_flags |= CHANNEL_FLAG_NOT_LFG;
        m_IsSaved = false;
    }
    else                                                    // it's custom channel
    {
        m_flags |= CHANNEL_FLAG_CUSTOM;
        //load not built in channel if saved
        std::string _name(name);
        CharacterDatabase.escape_string(_name);
        QueryResult result = CharacterDatabase.PQuery("SELECT m_announce, m_moderate, m_public, m_password, BannedList FROM channels WHERE m_name = '%s' AND m_team = '%u'", _name.c_str(), m_Team);
        if (result)//load
        {
            Field *fields = result->Fetch();
            m_announce = fields[0].GetBool();
            m_moderate = fields[1].GetBool();
            m_public = fields[2].GetBool();
            m_password  = fields[3].GetString();
            const char* db_BannedList = fields[4].GetCString();

            m_IsSaved = true;

            if (db_BannedList)
            {
                Tokens tokens = StrSplit(db_BannedList, " ");
                Tokens::iterator iter;
                for (iter = tokens.begin(); iter != tokens.end(); ++iter)
                {
                    uint64 banned_guid = atol((*iter).c_str());
                    if (banned_guid)
                    {
                        sLog.outDebug("Channel(%s) loaded banned guid:" UI64FMTD "",name.c_str(), banned_guid);
                        banned.insert(banned_guid);
                    }
                }
            }
        }
        else // save
        {
            // _name is already escaped at this point.
            CharacterDatabase.PExecute("INSERT INTO channels (m_name, m_team, m_announce, m_moderate, m_public, m_password) "
                "VALUES ('%s', '%u', '1', '0', '1', '')", _name.c_str(), m_Team);
            sLog.outDebug("New Channel(%s) saved", name.c_str());
            m_IsSaved = true;
        }
    }
}
Exemple #18
0
void Item::LoadFromDB(Field* fields, Player* plr, bool light)
{
    uint32 itemid = fields[2].GetUInt32();
    uint32 random_prop, random_suffix;
    uint32 count;

    m_itemProto = ItemPrototypeStorage.LookupEntry(itemid);

    ARCEMU_ASSERT(m_itemProto != NULL);
    locked = m_itemProto->LockId ? true : false;

    SetEntry(itemid);
    m_owner = plr;

    wrapped_item_id = fields[3].GetUInt32();
    SetGiftCreatorGUID(fields[4].GetUInt32());
    SetCreatorGUID(fields[5].GetUInt32());

    count = fields[6].GetUInt32();
    if (count > m_itemProto->MaxCount && (m_owner && !m_owner->ItemStackCheat))
        count = m_itemProto->MaxCount;
    SetStackCount(count);

    SetChargesLeft(fields[7].GetUInt32());

    SetUInt32Value(ITEM_FIELD_FLAGS, fields[8].GetUInt32());
    random_prop = fields[9].GetUInt32();
    random_suffix = fields[10].GetUInt32();

    SetItemRandomPropertyId(random_prop);

    int32 rprop = int32(random_prop);
    // If random properties point is negative that means the item uses random suffix as random enchantment
    if (rprop < 0)
        SetItemRandomSuffixFactor(random_suffix);
    else
        SetItemRandomSuffixFactor(0);

    //SetTextId( fields[11].GetUInt32() );

    SetDurabilityMax(m_itemProto->MaxDurability);
    SetDurability(fields[12].GetUInt32());

    if (light)
        return;

    string enchant_field = fields[15].GetString();
    vector< string > enchants = StrSplit(enchant_field, ";");
    uint32 enchant_id;
    EnchantEntry* entry;
    uint32 time_left;
    uint32 enchslot;

    for (vector<string>::iterator itr = enchants.begin(); itr != enchants.end(); ++itr)
    {
        if (sscanf((*itr).c_str(), "%u,%u,%u", (unsigned int*)&enchant_id, (unsigned int*)&time_left, (unsigned int*)&enchslot) == 3)
        {
            entry = dbcEnchant.LookupEntryForced(enchant_id);
            if (entry && entry->Id == enchant_id && m_itemProto->SubClass != ITEM_SUBCLASS_WEAPON_THROWN)
            {
                AddEnchantment(entry, time_left, (time_left == 0), false, false, enchslot);
                //(enchslot != 2) ? false : true, false);
            }
            else
            {
                /*
                EnchantEntry *pEnchant = new EnchantEntry;
                memset(pEnchant,0,sizeof(EnchantEntry));

                pEnchant->Id = enchant_id;
                if(enchslot != 2)
                AddEnchantment(pEnchant,0,true, false);
                else
                AddEnchantment(pEnchant,0,false,false);
                */
            }
        }
    }

    ItemExpiresOn = fields[16].GetUInt32();

    ///////////////////////////////////////////////////// Refund stuff ////////////////////////
    std::pair< time_t, uint32 > refundentry;

    refundentry.first = fields[17].GetUInt32();
    refundentry.second = fields[18].GetUInt32();

    if (refundentry.first != 0 && refundentry.second != 0 && GetOwner() != NULL)
    {
        uint32* played = GetOwner()->GetPlayedtime();
        if (played[1] < uint32(refundentry.first + 60 * 60 * 2))
            m_owner->GetItemInterface()->AddRefundable(this, refundentry.second, refundentry.first);
    }

    ///////////////////////////////////////////////////////////////////////////////////////////

    text = fields[19].GetString();

    ApplyRandomProperties(false);

    // Charter stuff
    if (GetEntry() == ITEM_ENTRY_GUILD_CHARTER)
    {
        SoulBind();
        SetStackCount(1);
        SetItemRandomSuffixFactor(57813883);
        if (plr != NULL && plr->m_charters[CHARTER_TYPE_GUILD])
            SetEnchantmentId(0, plr->m_charters[CHARTER_TYPE_GUILD]->GetID());
    }

    if (GetEntry() == ARENA_TEAM_CHARTER_2v2)
    {
        SoulBind();
        SetStackCount(1);
        SetItemRandomSuffixFactor(57813883);
        if (plr != NULL && plr->m_charters[CHARTER_TYPE_ARENA_2V2])
            SetEnchantmentId(0, plr->m_charters[CHARTER_TYPE_ARENA_2V2]->GetID());
    }

    if (GetEntry() == ARENA_TEAM_CHARTER_3v3)
    {
        SoulBind();
        SetStackCount(1);
        SetItemRandomSuffixFactor(57813883);
        if (plr != NULL && plr->m_charters[CHARTER_TYPE_ARENA_3V3])
            SetEnchantmentId(0, plr->m_charters[CHARTER_TYPE_ARENA_3V3]->GetID());
    }

    if (GetEntry() == ARENA_TEAM_CHARTER_5v5)
    {
        SoulBind();
        SetStackCount(1);
        SetItemRandomSuffixFactor(57813883);
        if (plr != NULL && plr->m_charters[CHARTER_TYPE_ARENA_5V5])
            SetEnchantmentId(0, plr->m_charters[CHARTER_TYPE_ARENA_5V5]->GetID());
    }
}
Exemple #19
0
bool Rehash()
{
    char * config_file = "conf/AuthServer.conf";

    if(!Config.MainConfig.SetSource(config_file))
    {
        printf("Config file could not be rehashed.\n");
        return false;
    }

    m_encryptedPasswords = Config.MainConfig.GetBoolDefault("LogonServer", "UseEncryptedPasswords", false);

    // re-set the allowed server IP's
    string ips = Config.MainConfig.GetStringDefault("LogonServer", "AllowedIPs", "");
    string ipsmod = Config.MainConfig.GetStringDefault("LogonServer", "AllowedModIPs", "");

    vector<string> vips = StrSplit(ips, " ");
    vector<string> vipsmod = StrSplit(ips, " ");

    m_allowedIpLock.Acquire();
    m_allowedIps.clear();
    m_allowedModIps.clear();
    vector<string>::iterator itr;
    for(itr = vips.begin(); itr != vips.end(); ++itr)
    {
        string::size_type i = itr->find("/");
        if(i == string::npos)
        {
            printf("IP: %s could not be parsed. Ignoring\n", itr->c_str());
            continue;
        }

        string stmp = itr->substr(0, i);
        string smask = itr->substr(i+1);

        unsigned int ipraw = MakeIP(stmp.c_str());
        unsigned int ipmask = atoi(smask.c_str());
        if(ipraw == 0 || ipmask == 0)
        {
            printf("IP: %s could not be parsed. Ignoring\n", itr->c_str());
            continue;
        }

        AllowedIP tmp;
        tmp.Bytes = ipmask;
        tmp.IP = ipraw;
        m_allowedIps.push_back(tmp);
    }

    for(itr = vipsmod.begin(); itr != vipsmod.end(); ++itr)
    {
        string::size_type i = itr->find("/");
        if( i == string::npos )
        {
            printf("IP: %s could not be parsed. Ignoring\n", itr->c_str());
            continue;
        }

        string stmp = itr->substr(0, i);
        string smask = itr->substr(i+1);

        unsigned int ipraw = MakeIP(stmp.c_str());
        unsigned int ipmask = atoi(smask.c_str());
        if( ipraw == 0 || ipmask == 0 )
        {
            printf("IP: %s could not be parsed. Ignoring\n", itr->c_str());
            continue;
        }

        AllowedIP tmp;
        tmp.Bytes = ipmask;
        tmp.IP = ipraw;
        m_allowedModIps.push_back(tmp);
    }

    if(InformationCore::getSingletonPtr() != NULL)
        sInfoCore.CheckServers();

    m_allowedIpLock.Release();

    return true;
}
bool MySQLConnection::Open(const std::string& infoString)
{
    MYSQL *mysqlInit;
    mysqlInit = mysql_init(NULL);
    if (!mysqlInit)
    {
        sLog.outError("Could not initialize Mysql connection");
        return false;
    }

    Tokens tokens = StrSplit(infoString, ";");

    Tokens::iterator iter;

    std::string host, port_or_socket, user, password, database;
    int port;
    char const* unix_socket;

    iter = tokens.begin();

    if (iter != tokens.end())
        host = *iter++;
    if (iter != tokens.end())
        port_or_socket = *iter++;
    if (iter != tokens.end())
        user = *iter++;
    if (iter != tokens.end())
        password = *iter++;
    if (iter != tokens.end())
        database = *iter++;

    mysql_options(mysqlInit, MYSQL_SET_CHARSET_NAME, "utf8");
    #ifdef _WIN32
    if (host==".")                                           // named pipe use option (Windows)
    {
        unsigned int opt = MYSQL_PROTOCOL_PIPE;
        mysql_options(mysqlInit, MYSQL_OPT_PROTOCOL, (char const*)&opt);
        port = 0;
        unix_socket = 0;
    }
    else                                                    // generic case
    {
        port = atoi(port_or_socket.c_str());
        unix_socket = 0;
    }
    #else
    if (host==".")                                           // socket use option (Unix/Linux)
    {
        unsigned int opt = MYSQL_PROTOCOL_SOCKET;
        mysql_options(mysqlInit, MYSQL_OPT_PROTOCOL, (char const*)&opt);
        host = "localhost";
        port = 0;
        unix_socket = port_or_socket.c_str();
    }
    else                                                    // generic case
    {
        port = atoi(port_or_socket.c_str());
        unix_socket = 0;
    }
    #endif

    m_Mysql = mysql_real_connect(mysqlInit, host.c_str(), user.c_str(),
        password.c_str(), database.c_str(), port, unix_socket, 0);

    if (m_Mysql)
    {
        sLog.outSQLDriver("MySQL client library: %s", mysql_get_client_info());
        sLog.outSQLDriver("MySQL server ver: %s ", mysql_get_server_info(m_Mysql));
        if (mysql_get_server_version(m_Mysql) != mysql_get_client_version())
            sLog.outSQLDriver("[WARNING] MySQL client/server version mismatch; may conflict with behaviour of prepared statements.");

        sLog.outDetail("Connected to MySQL database at %s", host.c_str());
        if (!mysql_autocommit(m_Mysql, 1))
            sLog.outSQLDriver("AUTOCOMMIT SUCCESSFULLY SET TO 1");
        else
            sLog.outSQLDriver("AUTOCOMMIT NOT SET TO 1");

        // set connection properties to UTF8 to properly handle locales for different
        // server configs - core sends data in UTF8, so MySQL must expect UTF8 too
        Execute("SET NAMES `utf8`");
        Execute("SET CHARACTER SET `utf8`");

    #if MYSQL_VERSION_ID >= 50003
        my_bool my_true = (my_bool)1;
        if (mysql_options(m_Mysql, MYSQL_OPT_RECONNECT, &my_true))
            sLog.outSQLDriver("Failed to turn on MYSQL_OPT_RECONNECT.");
        else
            sLog.outSQLDriver("Successfully turned on MYSQL_OPT_RECONNECT.");
    #else
        #warning "Your mySQL client lib version does not support reconnecting after a timeout.\nIf this causes you any trouble we advice you to upgrade your mySQL client libs to at least mySQL 5.0.13 to resolve this problem."
    #endif
        return true;
    }
    else
    {
        sLog.outError("Could not connect to MySQL database at %s: %s\n", host.c_str(), mysql_error(mysqlInit));
        mysql_close(mysqlInit);
        return false;
    }
}
Exemple #21
0
bool MySQLConnection::Initialize(const char *infoString)
{
    MYSQL * mysqlInit = mysql_init(NULL);
    if (!mysqlInit)
    {
        sLog.outError( "Could not initialize Mysql connection" );
        return false;
    }

    Tokens tokens = StrSplit(infoString, ";");

    Tokens::iterator iter;

    std::string host, port_or_socket, user, password, database;
    int port;
    char const* unix_socket;

    iter = tokens.begin();

    if(iter != tokens.end())
        host = *iter++;
    if(iter != tokens.end())
        port_or_socket = *iter++;
    if(iter != tokens.end())
        user = *iter++;
    if(iter != tokens.end())
        password = *iter++;
    if(iter != tokens.end())
        database = *iter++;

    mysql_options(mysqlInit,MYSQL_SET_CHARSET_NAME,"utf8");
#ifdef WIN32
    if(host==".")                                           // named pipe use option (Windows)
    {
        unsigned int opt = MYSQL_PROTOCOL_PIPE;
        mysql_options(mysqlInit,MYSQL_OPT_PROTOCOL,(char const*)&opt);
        port = 0;
        unix_socket = 0;
    }
    else                                                    // generic case
    {
        port = atoi(port_or_socket.c_str());
        unix_socket = 0;
    }
#else
    if(host==".")                                           // socket use option (Unix/Linux)
    {
        unsigned int opt = MYSQL_PROTOCOL_SOCKET;
        mysql_options(mysqlInit,MYSQL_OPT_PROTOCOL,(char const*)&opt);
        host = "localhost";
        port = 0;
        unix_socket = port_or_socket.c_str();
    }
    else                                                    // generic case
    {
        port = atoi(port_or_socket.c_str());
        unix_socket = 0;
    }
#endif

    mMysql = mysql_real_connect(mysqlInit, host.c_str(), user.c_str(),
                                password.c_str(), database.c_str(), port, unix_socket, 0);

    if (!mMysql)
    {
        sLog.outError( "Could not connect to MySQL database at %s: %s\n",
                       host.c_str(),mysql_error(mysqlInit));
        mysql_close(mysqlInit);
        return false;
    }

    DETAIL_LOG("Connected to MySQL database %s@%s:%s/%s", user.c_str(), host.c_str(), port_or_socket.c_str(), database.c_str());
    sLog.outString("MySQL client library: %s", mysql_get_client_info());
    sLog.outString("MySQL server ver: %s ", mysql_get_server_info( mMysql));

    /*----------SET AUTOCOMMIT ON---------*/
    // It seems mysql 5.0.x have enabled this feature
    // by default. In crash case you can lose data!!!
    // So better to turn this off
    // ---
    // This is wrong since mangos use transactions,
    // autocommit is turned of during it.
    // Setting it to on makes atomic updates work
    // ---
    // LEAVE 'AUTOCOMMIT' MODE ALWAYS ENABLED!!!
    // W/O IT EVEN 'SELECT' QUERIES WOULD REQUIRE TO BE WRAPPED INTO 'START TRANSACTION'<>'COMMIT' CLAUSES!!!
    if (!mysql_autocommit(mMysql, 1))
        DETAIL_LOG("AUTOCOMMIT SUCCESSFULLY SET TO 1");
    else
        DETAIL_LOG("AUTOCOMMIT NOT SET TO 1");
    /*-------------------------------------*/

    // set connection properties to UTF8 to properly handle locales for different
    // server configs - core sends data in UTF8, so MySQL must expect UTF8 too
    Execute("SET NAMES `utf8`");
    Execute("SET CHARACTER SET `utf8`");

    return true;
}
Exemple #22
0
	void DirectoryWriter::RecursiveList(string szPath, bool bRecursive)
	{
		DirectoryReader* reader = new DirectoryReader();
		DIR* pDir = NULL;

		pDir = reader->open(szPath, pDir);
		
		struct dirent* pEnt = NULL;

		int count = 0;
		while (pEnt = readdir(pDir))
		{
			if (strcmp(pEnt->d_name, ".") == 0 || strcmp(pEnt->d_name, "..") == 0)
				continue;

			string szCurrent(szPath);
			szCurrent.append("/");
			szCurrent.append(pEnt->d_name);
			szCurrent = ConvertPath(szCurrent);
			if (reader->isDir(szCurrent))
			{
				if (bRecursive)
				{
					// not sure...
					//delete reader;
					RecursiveList(ConvertPath(szCurrent), true);
				}
			}
			if (reader->isFile(szCurrent))
			{
				vector<string> segments = vector<string>();
				string currentPath = ConvertPath(szCurrent);
				StrSplit(currentPath, segments);

				string path = "";
				vector<string>temp = segments;
				for (size_t i = 0; i < temp.size(); i++)
				{
					if (strcmp(temp[i].c_str(),"mapje")==0)
					{
						break;
					}
					else
					{
						segments.erase(segments.begin());
					}
				}

				for (size_t i = 0; i < segments.size(); i++)
				{
					path.append(segments[i]);
					if (i!=segments.size()-1)
					{
						path.append("/");
					}
				}

				time_t iLastModified = reader->getLastModifiedTime(szCurrent);
				WriteNode(pEnt->d_name, path, to_string(iLastModified));
			}
			count++;
		}
		
		closedir(pDir);
		delete reader;
	}