Esempio n. 1
0
bool BaseGuildManager::GetEntireGuild(uint32 guild_id, std::vector<CharGuildInfo *> &members) {
	members.clear();

	if(m_db == nullptr)
		return(false);

	//load up the rank info for each guild.
	std::string query = StringFormat(GuildMemberBaseQuery " WHERE g.guild_id=%d", guild_id);
	auto results = m_db->QueryDatabase(query);
	if (!results.Success()) {
		_log(GUILDS__ERROR, "Error loading guild member list '%s': %s", query.c_str(), results.ErrorMessage().c_str());
		return false;
	}

    for (auto row = results.begin(); row != results.end(); ++row) {
		CharGuildInfo *ci = new CharGuildInfo;
		ProcessGuildMember(row, *ci);
		members.push_back(ci);
	}

	_log(GUILDS__DB, "Retreived entire guild member list for guild %d from the database", guild_id);

	return true;
}
Esempio n. 2
0
bool Group::LearnMembers() {
	std::string query = StringFormat("SELECT name FROM group_id WHERE groupid = %lu", (unsigned long)GetID());
	auto results = database.QueryDatabase(query);
	if (!results.Success())
        return false;

    if (results.RowCount() == 0) {
        Log.Out(Logs::General, Logs::Error, "Error getting group members for group %lu: %s", (unsigned long)GetID(), results.ErrorMessage().c_str());
			return false;
    }

	int memberIndex = 0;
    for(auto row = results.begin(); row != results.end(); ++row) {
		if(!row[0])
			continue;

		members[memberIndex] = nullptr;
		strn0cpy(membername[memberIndex], row[0], 64);

		memberIndex++;
	}

	return true;
}
Esempio n. 3
0
bool BaseGuildManager::DBSetPublicNote(uint32 charid, const char* note) {
	if(m_db == nullptr)
		return(false);

	//escape our strings.
	uint32 len = strlen(note);
	char *esc = new char[len*2+1];
	m_db->DoEscapeString(esc, note, len);

	//insert the new `guilds` entry
	std::string query = StringFormat("UPDATE guild_members SET public_note='%s' WHERE char_id=%d", esc, charid);
	safe_delete_array(esc);
	auto results = m_db->QueryDatabase(query);

	if (!results.Success())
	{
		_log(GUILDS__ERROR, "Error setting public note for char %d '%s': %s", charid, query.c_str(), results.ErrorMessage().c_str());
		return false;
	}

	_log(GUILDS__DB, "Set public not for char %d", charid);

	return true;
}
Esempio n. 4
0
Error ClientState::commit(ClientStateCommitType commitType, 
                          const ::core::FilePath& stateDir,
                          const ::core::FilePath& projectStateDir)
{
   // remove and re-create the stateDirs
   Error error = removeAndRecreateStateDir(stateDir);
   if (error)
      return error;
   error = removeAndRecreateStateDir(projectStateDir);
   if (error)
      return error;

   // always commit persistent state
   commitState(persistentState_, kPersistentExt, stateDir);
   commitState(projectPersistentState_, kProjPersistentExt, projectStateDir);
  
   // commit all state if requested
   if (commitType == ClientStateCommitAll)
      commitState(temporaryState_, kTemporaryExt, stateDir);
   else
      temporaryState_.clear();
   
   return Success();
}
Esempio n. 5
0
// Given a path, searches for the document in the Documents collection that
// has the path given. The out parameter is set to that document's IDispatch
// pointer, or NULL if no document with the path could be found.
Error WordViewer::getDocumentByPath(QString& path, IDispatch** pidispDoc)
{
   Error errorHR = Success();
   HRESULT hr = S_OK;

   IDispatch* idispDocs = NULL;
   IDispatch* idispDoc = NULL;
   VARIANT varDocIdx;
   VARIANT varResult;
   int docCount = 0;

   *pidispDoc = NULL;

   VERIFY_HRESULT(getIDispatchProp(idispWord_, L"Documents", &idispDocs));
   VERIFY_HRESULT(getIntProp(idispDocs, L"Count", &docCount));

   varDocIdx.vt = VT_INT;
   for (int i = 1; i <= docCount; i++)
   {
      VariantInit(&varResult);
      varDocIdx.intVal = i;
      VERIFY_HRESULT(invokeDispatch(DISPATCH_METHOD, &varResult, idispDocs,
                                    L"Item", 1, varDocIdx));
      idispDoc = varResult.pdispVal;
      VERIFY_HRESULT(invokeDispatch(DISPATCH_PROPERTYGET, &varResult, idispDoc,
                                    L"FullName", 0));
      if (path.toStdWString() == varResult.bstrVal)
      {
         *pidispDoc = idispDoc;
         break;
      }
   }

LErrExit:
   return errorHR;
}
Esempio n. 6
0
bool EQEmu::ProfanityManager::RemoveProfanity(DBcore *db, const char *profanity) {
	if (!db || !profanity)
		return false;

	std::string entry(profanity);

	std::transform(entry.begin(), entry.end(), entry.begin(), [](unsigned char c) -> unsigned char { return tolower(c); });

	if (!check_for_existing_entry(entry.c_str()))
		return true;

	profanity_list.remove(entry);

	std::string query = "DELETE FROM `profanity_list` WHERE `word` LIKE '";
	query.append(entry);
	query.append("'");
	auto results = db->QueryDatabase(query);
	if (!results.Success())
		return false;

	update_originator_flag = true;

	return true;
}
Esempio n. 7
0
void RuleManager::_SaveRule(Database *db, RuleType type, uint16 index) {
	char vstr[100];

	switch(type) {
	case IntRule:
		sprintf(vstr, "%d", m_RuleIntValues[index]);
		break;
	case RealRule:
		sprintf(vstr, "%.13f", m_RuleRealValues[index]);
		break;
	case BoolRule:
		sprintf(vstr, "%s", m_RuleBoolValues[index]?"true":"false");
		break;
	}

	std::string query = StringFormat("REPLACE INTO rule_values "
                                    "(ruleset_id, rule_name, rule_value) "
                                    " VALUES(%d, '%s', '%s')",
                                    m_activeRuleset, _GetRuleName(type, index), vstr);
    auto results = db->QueryDatabase(query);
	if (!results.Success())
		_log(RULES__ERROR, "Fauled to set rule in the database: %s: %s", query.c_str(), results.ErrorMessage().c_str());

}
Esempio n. 8
0
// Add new Zone Object (theoretically only called for items dropped to ground)
uint32 ZoneDatabase::AddObject(uint32 type, uint32 icon, const Object_Struct& object, const ItemInst* inst)
{
	uint32 database_id = 0;
	uint32 item_id = 0;
	int16 charges = 0;

	if (inst && inst->GetItem()) {
		item_id = inst->GetItem()->ID;
		charges = inst->GetCharges();
	}

	// SQL Escape object_name
	uint32 len = strlen(object.object_name) * 2 + 1;
	char* object_name = new char[len];
	DoEscapeString(object_name, object.object_name, strlen(object.object_name));

    // Save new record for object
	std::string query = StringFormat("INSERT INTO object "
                                    "(zoneid, xpos, ypos, zpos, heading, "
                                    "itemid, charges, objectname, type, icon) "
                                    "values (%i, %f, %f, %f, %f, %i, %i, '%s', %i, %i)",
                                    object.zone_id, object.x, object.y, object.z, object.heading,
                                    item_id, charges, object_name, type, icon);
    safe_delete_array(object_name);
	auto results = QueryDatabase(query);
	if (!results.Success()) {
		LogFile->write(EQEMuLog::Error, "Unable to insert object: %s", results.ErrorMessage().c_str());
		return 0;
	}

    // Save container contents, if container
    if (inst && inst->IsType(ItemClassContainer))
        SaveWorldContainer(object.zone_id, database_id, inst);

	return database_id;
}
Esempio n. 9
0
void Database::CreateLSAccount(std::string name, std::string password, std::string email, unsigned int created_by, std::string LastIPAddress, std::string creationIP)
{
	bool activate = 0;
	if (LoadServerSettings("options", "auto_account_activate") == "TRUE")
	{
		activate = 1;
	}
	std::string query;

	char tmpUN[1024];
	DoEscapeString(tmpUN, name.c_str(), (int)name.length());

	query = StringFormat("INSERT INTO %s "
		"SET AccountName = '%s', "
		"AccountPassword = sha('%s'), "
		"AccountCreateDate = now(), "
		"LastLoginDate = now(), "
		"LastIPAddress = '%s', "
		"client_unlock = '%s', "
		"created_by = '%s', "
		"creationIP = '%s'",
		LoadServerSettings("schema", "account_table").c_str(),
		tmpUN,
		password.c_str(),
		LastIPAddress.c_str(),
		std::to_string(activate).c_str(),
		std::to_string(created_by).c_str(),
		creationIP.c_str()
		);

	auto results = QueryDatabase(query);
	if (!results.Success())
	{
		server_log->Log(log_database_error, "Mysql query failed: %s", query.c_str());
	}
}
Esempio n. 10
0
int16 SpawnConditionManager::GetCondition(const char *zone_short, uint32 instance_id, uint16 condition_id) {
	if(!strcasecmp(zone_short, zone->GetShortName()) && instance_id == zone->GetInstanceID())
	{
		//this is a local spawn condition
		std::map<uint16, SpawnCondition>::iterator condi;
		condi = spawn_conditions.find(condition_id);
		if(condi == spawn_conditions.end())
		{
			Log(Logs::Detail, Logs::Spawns, "Unable to find local condition %d in Get request.", condition_id);
			return(0);	//unable to find the spawn condition
		}

		SpawnCondition &cond = condi->second;
		return cond.value;
	}

	//this is a remote spawn condition, grab it from the DB
    //load spawn conditions
    std::string query = StringFormat("SELECT value FROM spawn_condition_values "
                                    "WHERE zone = '%s' AND instance_id = %u AND id = %d",
                                    zone_short, instance_id, condition_id);
    auto results = database.QueryDatabase(query);
    if (!results.Success()) {
        Log(Logs::Detail, Logs::Spawns, "Unable to query remote condition %d from zone %s in Get request.", condition_id, zone_short);
		return 0;	//dunno a better thing to do...
    }

    if (results.RowCount() == 0) {
        Log(Logs::Detail, Logs::Spawns, "Unable to load remote condition %d from zone %s in Get request.", condition_id, zone_short);
		return 0;	//dunno a better thing to do...
    }

    auto row = results.begin();

    return atoi(row[0]);
}
Esempio n. 11
0
Error ConnectionHistory::readConnections(json::Array* pConnections)
{
   FilePath connectionListFile = connectionsDir_.childPath(kConnectionListFile);
   if (connectionListFile.exists())
   {
      std::string contents;
      Error error = core::readStringFromFile(connectionListFile, &contents);
      if (error)
         return error;

      json::Value parsedJson;
      if (!json::parse(contents, &parsedJson) ||
          !json::isType<json::Array>(parsedJson))
      {
         return systemError(boost::system::errc::protocol_error,
                            "Error parsing connections json file",
                            ERROR_LOCATION);
      }

      *pConnections = parsedJson.get_value<json::Array>();
   }

   return Success();
}
Esempio n. 12
0
bool Database::SetServerSettings(std::string type, std::string category, std::string defaults)
{
	std::string query;

	Config* newval = new Config;
	std::string loadINIvalue = newval->LoadOption(category, type, "login.ini");
	query = StringFormat(
		"UPDATE tblloginserversettings "
		"SET value = '%s' "
		"WHERE type = '%s' "
		"AND category = '%s' "
		"LIMIT 1", 
		loadINIvalue.empty() ? defaults.c_str() : loadINIvalue.c_str(), type.c_str(), category.c_str());
	safe_delete(newval);

	auto results = QueryDatabase(query);

	if (!results.Success())
	{
		server_log->Log(log_database_error, "SetServerSettings Mysql check_query failed: %s", query.c_str());
		return false;
	}
	return true;
}
Esempio n. 13
0
bool Database::GetLoginDataFromAccountName(std::string name, std::string &password, unsigned int &id)
{
	std::string query;

	char tmpUN[1024];
	DoEscapeString(tmpUN, name.c_str(), (int)name.length()); (tmpUN, name.c_str(), (int)name.length());

	query = StringFormat("SELECT LoginServerID, AccountPassword "
		"FROM %s WHERE "
		"AccountName = '%s'",
		LoadServerSettings("schema", "account_table").c_str(),
		tmpUN
		);

	auto results = QueryDatabase(query);

	if (!results.Success())
	{
		server_log->Log(log_database_error, "Mysql query failed: %s", query.c_str());
		return false;
	}
	if (results.RowCount() > 0)
	{
		auto row = results.begin();
		if (row[0] != nullptr)
		{
			id = atoi(row[0]);
			password = row[1];
			return true;
		}
		server_log->Log(log_database_error, "Unknown error, no result for: %s", query.c_str());
		return false;
	}
	server_log->Log(log_database_error, "Mysql query returned no result for: %s", query.c_str());
	return false;
}
Esempio n. 14
0
void Database::LogPlayerItemMove(QSPlayerLogItemMove_Struct* QS, uint32 items)
{
	if (items == 0)
	{
		return;
	}

    for(uint32 i = 0; i < items; i++)
	{
        std::string query = StringFormat(
			"INSERT INTO `qs_player_item_move_log` SET "
				"`char_id` = '%i', "
				"`from_slot` = '%i', "
				"`to_slot` = '%i', "
				"`item_id` = '%i', "
				"`charges` = '%i', "
				"`stack_size` = '%i', "
				"`char_items` = '%i', "
				"`postaction` = '%i', "
				"`time` = now()",
				QS->char_id,
				QS->items[i].from_slot,
				QS->items[i].to_slot,
				QS->items[i].item_id,
				QS->items[i].charges,
				QS->stack_size,
				QS->char_count,
				QS->postaction);

        auto results = QueryDatabase(query);
        if(!results.Success())
		{
			Log.Out(Logs::Detail, Logs::QS_Server, "Failed Move Log Record Entry Insert: %s\n%s", results.ErrorMessage().c_str(), query.c_str());
        }
    }
}
Esempio n. 15
0
void Database::AddSpeech(const char* from, const char* to, const char* message, uint16 minstatus, uint32 guilddbid, uint8 type) {

	char *escapedFrom = new char[strlen(from) * 2 + 1];
	char *escapedTo = new char[strlen(to) * 2 + 1];
	char *escapedMessage = new char[strlen(message) * 2 + 1];
	DoEscapeString(escapedFrom, from, strlen(from));
	DoEscapeString(escapedTo, to, strlen(to));
	DoEscapeString(escapedMessage, message, strlen(message));

    std::string query = StringFormat("INSERT INTO `qs_player_speech` "
                                    "SET `from` = '%s', `to` = '%s', `message`='%s', "
                                    "`minstatus`='%i', `guilddbid`='%i', `type`='%i'",
                                    escapedFrom, escapedTo, escapedMessage, minstatus, guilddbid, type);
    safe_delete_array(escapedFrom);
	safe_delete_array(escapedTo);
	safe_delete_array(escapedMessage);
	auto results = QueryDatabase(query);
	if(!results.Success()) {
		Log.Out(Logs::Detail, Logs::QS_Server, "Failed Speech Entry Insert: %s", results.ErrorMessage().c_str());
		Log.Out(Logs::Detail, Logs::QS_Server, "%s", query.c_str());
	}


}
Esempio n. 16
0
bool Database::GetWorldRegistration(unsigned int &id, std::string &desc, unsigned int &trusted, unsigned int &list_id, 
									std::string &account, std::string &password, std::string long_name, std::string short_name)	
{
	char escaped_short_name[101];
	DoEscapeString(escaped_short_name, short_name.substr(0, 100).c_str(), (int)strlen(short_name.substr(0, 100).c_str()));

	std::string query;

	query = StringFormat("SELECT "
		"ServerID, ServerTagDescription, ServerTrusted, ServerListTypeID, ServerAdminID "
		"FROM %s WHERE ServerShortName = '%s'",
		LoadServerSettings("schema", "world_registration_table").c_str(),
		escaped_short_name
		);

	auto results = QueryDatabase(query);

	if (!results.Success())
	{
		server_log->Log(log_database_error, "Mysql query failed: %s", query.c_str());
		return false;
	}

	auto row = results.begin();

	if (results.RowCount() > 0)
	{
		id = atoi(row[0]);
		desc = row[1];
		trusted = atoi(row[2]);
		list_id = atoi(row[3]);
		int db_account_id = atoi(row[5]);

		if (db_account_id > 0)
		{
			std::string query;
			query = StringFormat("SELECT AccountName, AccountPassword "
				"FROM %s WHERE ServerAdminID = %s",
				LoadServerSettings("schema", "world_admin_registration_table").c_str(),
				std::to_string(db_account_id).c_str()
				);
			auto results = QueryDatabase(query);

			if (!results.Success())
			{
				server_log->Log(log_database_error, "Mysql query failed: %s", query.c_str());
				return false;
			}

			auto row = results.begin();
			if (results.RowCount() > 0)
			{
				account = row[0];
				password = row[1];
				return true;
			}
			server_log->Log(log_database_trace, "Mysql query returned no result: %s", query.c_str());
			return false;
		}
		return true;
	}
	server_log->Log(log_database_error, "Mysql query returned no result: %s", query.c_str());
	return false;
}
Esempio n. 17
0
bool Database::CreateServerSettings()
{
	std::string query;
	std::string query2;
	server_log->Log(log_database_trace, "Entering Server Settings database setup.");

	query = StringFormat("SHOW TABLES LIKE 'tblloginserversettings'");

	auto results = QueryDatabase(query);

	if (!results.Success())
	{
		server_log->Log(log_database_error, "CreateServerSettings Mysql query failed to search for table: %s", query.c_str());
		return false;
	}

	server_log->Log(log_database, "CreateServerSettings: table does not exist, creating: %s", query.c_str());

	if (results.RowCount() <= 0)
	{
		server_log->Log(log_database, "Server Settings table does not exist, creating.");

		query = StringFormat(
				"CREATE TABLE `tblloginserversettings` ("
				"`type` varchar(50) NOT NULL,"
				"`value` varchar(50),"
				"`category` varchar(20) NOT NULL,"
				"`description` varchar(99) NOT NULL,"
				"`defaults` varchar(50)"
				") ENGINE=InnoDB DEFAULT CHARSET=latin1");

		auto results = QueryDatabase(query);

		if (!results.Success())
		{
			server_log->Log(log_database_error, "CreateServerSettings Mysql query failed to create table: %s", query.c_str());
			return false;
		}

		query2 = StringFormat(
			"INSERT INTO `tblloginserversettings` (type, value, category, description, defaults)"
			"VALUES"
			"('access_log_table', '', 'schema', 'location for access logs, failed logins and goodIP.', 'tblaccountaccesslog'),"
			"('account_table', '', 'schema', 'location of all client account info for login server only.', 'tblLoginServerAccounts'),"
			"('auto_account_activate', '', 'options', 'set this to TRUE to allow new accounts to log in.', 'TRUE'),"
			"('auto_account_create', '', 'options', 'set this to TRUE to auto create accounts on player first log in.', 'TRUE'),"
			"('port', '', 'Old', 'port for clients to connect to.', '6000'),"
			"('dump_packets_in', '', 'options', 'debugging', 'FALSE'),"
			"('dump_packets_out', '', 'options', 'debugging', 'FALSE'),"
			"('failed_login_log', '', 'options', 'set this to TRUE to log failed log in attempts.', 'TRUE'),"
			"('good_loginIP_log', '', 'options', 'set this to TRUE to log successful account log ins.', 'TRUE'),"
			"('listen_port', '', 'options', 'this is the port we listen on for world connection.', '5998'),"
			"('local_network', '', 'options', 'set to the network ip that world server is on.', '127.0.0.1'),"
			"('mode', '', 'security', 'encryption mode the plugin uses.', '5'),"
			"('network_ip', '', 'options', 'set to the network ip that world server is on.', '127.0.0.1'),"
			"('opcodes', '', 'Old', 'opcode file for client compatibility. (Old means classic/mac)', 'login_opcodes_oldver.conf'),"
			"('plugin', '', 'security', 'the encryption type the login server uses.', 'EQEmuAuthCrypto'),"
			"('pop_count', '', 'options', '0 to only display UP or DOWN or 1 to show population count in server select.', '0'),"
			"('reject_duplicate_servers', '', 'options', 'set this to TRUE to force unique server name connections.', 'TRUE'),"
			"('salt', '', 'options', 'for account security make this a numeric random number.', '12345678'),"
			"('ticker', '', 'options', 'Sets the welcome message in server select.', 'Welcome to EQMacEmu'),"
			"('trace', '', 'options', 'debugging', 'FALSE'),"
			"('unregistered_allowed', '', 'options', 'set this to TRUE to allow any server to connect.', 'TRUE'),"
			"('world_admin_registration_table', '', 'schema', 'location of administrator account info for this login server.', 'tblServerAdminRegistration'),"
			"('world_registration_table', '', 'schema', 'location of registered or connection records of servers connecting to this loginserver.', 'tblWorldServerRegistration'),"
			"('world_server_type_table', '', 'schema', 'location of server type descriptions.', 'tblServerListType'),"
			"('world_trace', '', 'options', 'debugging', 'FALSE');");

		auto results2 = QueryDatabase(query2);

		if (!results2.Success())
		{
			server_log->Log(log_database_error, "CreateServerSettings Mysql query failed: %s", query2.c_str());
			return false;
		}			
			
		// type, category, default
		bool failed = false;
		failed |= !SetServerSettings("access_log_table", "schema", "tblaccountaccesslog");
		failed |= !SetServerSettings("account_table", "schema", "tblLoginServerAccounts");
		failed |= !SetServerSettings("auto_account_activate", "options", "TRUE");
		failed |= !SetServerSettings("auto_account_create", "options", "TRUE");
		failed |= !SetServerSettings("port", "Old", "6000");
		failed |= !SetServerSettings("dump_packets_in", "options", "FALSE");
		failed |= !SetServerSettings("dump_packets_out", "options", "FALSE");
		failed |= !SetServerSettings("failed_login_log", "options", "TRUE");
		failed |= !SetServerSettings("good_loginIP_log", "options", "TRUE");
		failed |= !SetServerSettings("listen_port", "options", "5998");
		failed |= !SetServerSettings("local_network", "options", "127.0.0.1");
		failed |= !SetServerSettings("mode", "security", "5");
		failed |= !SetServerSettings("network_ip", "options", "127.0.0.1");
		failed |= !SetServerSettings("opcodes", "Old", "login_opcodes_oldver.conf");
		failed |= !SetServerSettings("plugin", "security", "EQEmuAuthCrypto");
		failed |= !SetServerSettings("pop_count", "options", "0");
		failed |= !SetServerSettings("reject_duplicate_servers", "options", "TRUE");
		failed |= !SetServerSettings("salt", "options", "12345678");
		failed |= !SetServerSettings("ticker", "options", "Welcome to EQMacEmu");
		failed |= !SetServerSettings("trace", "options", "FALSE");
		failed |= !SetServerSettings("unregistered_allowed", "options", "TRUE");
		failed |= !SetServerSettings("world_admin_registration_table", "schema", "tblServerAdminRegistration");
		failed |= !SetServerSettings("world_registration_table", "schema", "tblWorldServerRegistration");
		failed |= !SetServerSettings("world_server_type_table", "schema", "tblServerListType");
		failed |= !SetServerSettings("world_trace", "options", "FALSE");

		if (failed)
		{
			return false;
		}
		server_log->Log(log_database_trace, "Server Settings table created, continuing.");
	}
	else
	{
		server_log->Log(log_database_trace, "CreateServerSettings found existing settings, continuing on.");
	}
	if (GetServerSettings())
	{
		return true;
	}
	return false;
}
Esempio n. 18
0
void DelayProcess::VUpdate(unsigned int elapsedTime)
{
	m_timeDelayed += elapsedTime;
	if(m_timeDelayed >= m_timeToDelay)
		Success();
}
Esempio n. 19
0
bool SpawnConditionManager::LoadSpawnConditions(const char* zone_name, uint32 instance_id)
{
	//clear out old stuff..
	spawn_conditions.clear();

	std::string query = StringFormat("SELECT id, onchange, value "
                                    "FROM spawn_conditions "
                                    "WHERE zone = '%s'", zone_name);
    auto results = database.QueryDatabase(query);
    if (!results.Success()) {
		return false;
    }

    for (auto row = results.begin(); row != results.end(); ++row) {
        //load spawn conditions
        SpawnCondition cond;

        cond.condition_id = atoi(row[0]);
        cond.value = atoi(row[2]);
        cond.on_change = (SpawnCondition::OnChange) atoi(row[1]);
        spawn_conditions[cond.condition_id] = cond;

        Log(Logs::Detail, Logs::Spawns, "Loaded spawn condition %d with value %d and on_change %d", cond.condition_id, cond.value, cond.on_change);
    }

	//load values
	query = StringFormat("SELECT id, value FROM spawn_condition_values "
                        "WHERE zone = '%s' AND instance_id = %u",
                        zone_name, instance_id);
    results = database.QueryDatabase(query);
    if (!results.Success()) {
		spawn_conditions.clear();
		return false;
    }

    for (auto row = results.begin(); row != results.end(); ++row) {
        auto iter = spawn_conditions.find(atoi(row[0]));

        if(iter != spawn_conditions.end())
            iter->second.value = atoi(row[1]);
    }

	//load spawn events
    query = StringFormat("SELECT id, cond_id, period, next_minute, next_hour, "
                        "next_day, next_month, next_year, enabled, action, argument, strict "
                        "FROM spawn_events WHERE zone = '%s'", zone_name);
    results = database.QueryDatabase(query);
    if (!results.Success()) {
		return false;
    }

    for (auto row = results.begin(); row != results.end(); ++row) {
        SpawnEvent event;

        event.id = atoi(row[0]);
        event.condition_id = atoi(row[1]);
        event.period = atoi(row[2]);

        if(event.period == 0) {
            Log(Logs::General, Logs::Error, "Refusing to load spawn event #%d because it has a period of 0\n", event.id);
            continue;
        }

        event.next.minute = atoi(row[3]);
        event.next.hour = atoi(row[4]);
        event.next.day = atoi(row[5]);
        event.next.month = atoi(row[6]);
        event.next.year = atoi(row[7]);

        event.enabled = atoi(row[8])==0?false:true;
        event.action = (SpawnEvent::Action) atoi(row[9]);
        event.argument = atoi(row[10]);
        event.strict = atoi(row[11])==0?false:true;

        spawn_events.push_back(event);

        Log(Logs::Detail, Logs::Spawns, "(LoadSpawnConditions) Loaded %s spawn event %d on condition %d with period %d, action %d, argument %d, strict %d", event.enabled? "enabled": "disabled", event.id, event.condition_id, event.period, event.action, event.argument, event.strict);
    }

	//now we need to catch up on events that happened while we were away
	//and use them to alter just the condition variables.

	//each spawn2 will then use its correct condition value when
	//it decides what to do. This essentially forces a 'depop' action
	//on spawn points which are turned off, and a 'repop' action on
	//spawn points which get turned on. Im too lazy to figure out a
	//better solution, and I just dont care thats much.
	//get our current time
	TimeOfDay_Struct tod;
	zone->zone_time.GetCurrentEQTimeOfDay(&tod);

	for(auto cur = spawn_events.begin(); cur != spawn_events.end(); ++cur) {
		SpawnEvent &cevent = *cur;

		bool StrictCheck = false;
		if(cevent.strict &&
			cevent.next.hour == tod.hour &&
			cevent.next.day == tod.day &&
			cevent.next.month == tod.month &&
			cevent.next.year == tod.year)
			StrictCheck = true;

		//If event is disabled, or we failed the strict check, set initial spawn_condition to 0.
		if(!cevent.enabled || !StrictCheck)
			SetCondition(zone->GetShortName(), zone->GetInstanceID(),cevent.condition_id,0);

		if(!cevent.enabled)
            continue;

        //watch for special case of all 0s, which means to reset next to now
        if(cevent.next.year == 0 && cevent.next.month == 0 && cevent.next.day == 0 && cevent.next.hour == 0 && cevent.next.minute == 0) {
            Log(Logs::Detail, Logs::Spawns, "Initial next trigger time set for spawn event %d", cevent.id);
            memcpy(&cevent.next, &tod, sizeof(cevent.next));
            //add one period
            EQTime::AddMinutes(cevent.period, &cevent.next);
            //save it in the db.
            UpdateDBEvent(cevent);
            continue;	//were done with this event.
        }

        bool ran = false;
        while(EQTime::IsTimeBefore(&tod, &cevent.next)) {
            Log(Logs::Detail, Logs::Spawns, "Catch up triggering on event %d", cevent.id);
            //this event has been triggered.
            //execute the event
            if(!cevent.strict || StrictCheck)
                ExecEvent(cevent, false);

            //add the period of the event to the trigger time
            EQTime::AddMinutes(cevent.period, &cevent.next);
            ran = true;
        }

        //only write it out if the event actually ran
        if(ran)
            UpdateDBEvent(cevent); //save the event in the DB
	}

	//now our event timers are all up to date, find our closest event.
	FindNearestEvent();

	return true;
}
Esempio n. 20
0
bool ZoneDatabase::PopulateZoneSpawnList(uint32 zoneid, LinkedList<Spawn2*> &spawn2_list, int16 version, uint32 repopdelay) {

	std::unordered_map<uint32, uint32> spawn_times;

	timeval tv;
	gettimeofday(&tv, nullptr);

	/* Bulk Load NPC Types Data into the cache */
	database.LoadNPCTypesData(0, true);

	std::string spawn_query = StringFormat(
		"SELECT "
		"respawn_times.id, "
		"respawn_times.`start`, "
		"respawn_times.duration "
		"FROM "
		"respawn_times "
		"WHERE instance_id = %u",
		zone->GetInstanceID()
	);
	auto results = QueryDatabase(spawn_query);
	for (auto row = results.begin(); row != results.end(); ++row) {
		uint32 start_duration = atoi(row[1]) > 0 ? atoi(row[1]) : 0;
		uint32 end_duration = atoi(row[2]) > 0 ? atoi(row[2]) : 0;

		/* Our current time was expired */
		if ((start_duration + end_duration) <= tv.tv_sec) {
			spawn_times[atoi(row[0])] = 0;
		}
		/* We still have time left on this timer */
		else {
			spawn_times[atoi(row[0])] = ((start_duration + end_duration) - tv.tv_sec) * 1000;
		}
	}

	const char *zone_name = database.GetZoneName(zoneid);
	std::string query = StringFormat(
		"SELECT "
		"id, "
		"spawngroupID, "
		"x, "
		"y, "
		"z, "
		"heading, "
		"respawntime, "
		"variance, "
		"pathgrid, "
		"_condition, "
		"cond_value, "
		"enabled, "
		"animation "
		"FROM "
		"spawn2 "
		"WHERE zone = '%s' AND  (version = %u OR version = -1)",
		zone_name,
		version
	);
	results = QueryDatabase(query);

	if (!results.Success()) {
		return false;
	}

	for (auto row = results.begin(); row != results.end(); ++row) {

		uint32 spawn_time_left = 0; 
		Spawn2* new_spawn = 0; 
		bool perl_enabled = atoi(row[11]) == 1 ? true : false;

		if (spawn_times.count(atoi(row[0])) != 0)
			spawn_time_left = spawn_times[atoi(row[0])];

		new_spawn = new Spawn2(							   // 
			atoi(row[0]), 								   // uint32 in_spawn2_id
			atoi(row[1]), 								   // uint32 spawngroup_id
			atof(row[2]), 								   // float in_x
			atof(row[3]), 								   // float in_y
			atof(row[4]),								   // float in_z
			atof(row[5]), 								   // float in_heading
			atoi(row[6]), 								   // uint32 respawn
			atoi(row[7]), 								   // uint32 variance
			spawn_time_left,							   // uint32 timeleft
			atoi(row[8]),								   // uint32 grid
			atoi(row[9]), 								   // uint16 in_cond_id
			atoi(row[10]), 								   // int16 in_min_value
			perl_enabled, 								   // bool in_enabled
			(EmuAppearance)atoi(row[12])				   // EmuAppearance anim
		);

		spawn2_list.Insert(new_spawn);
	}

	NPC::SpawnZoneController();

	return true;
}
Esempio n. 21
0
bool Generator::Process()
{
   if (GetDuration() < 0.0)
      return false;


   // Set up mOutputTracks.
   // This effect needs Track::All for sync-lock grouping.
   this->CopyInputTracks(Track::All);

   // Iterate over the tracks
   bool bGoodResult = true;
   int ntrack = 0;
   TrackListIterator iter(mOutputTracks);
   Track* t = iter.First();

   while (t != NULL)
   {
      if (t->GetKind() == Track::Wave && t->GetSelected()) {
         WaveTrack* track = (WaveTrack*)t;

         bool editClipCanMove;
         gPrefs->Read(wxT("/GUI/EditClipCanMove"), &editClipCanMove, true);

         //if we can't move clips, and we're generating into an empty space,
         //make sure there's room.
         if (!editClipCanMove &&
             track->IsEmpty(mT0, mT1+1.0/track->GetRate()) &&
             !track->IsEmpty(mT0, mT0+GetDuration()-(mT1-mT0)-1.0/track->GetRate()))
         {
            wxMessageBox(
                  _("There is not enough room available to generate the audio"),
                  _("Error"), wxICON_STOP);
            Failure();
            return false;
         }

         if (GetDuration() > 0.0)
         {
            AudacityProject *p = GetActiveProject();
            // Create a temporary track
            std::unique_ptr<WaveTrack> tmp(
               mFactory->NewWaveTrack(track->GetSampleFormat(),
               track->GetRate())
            );
            BeforeTrack(*track);
            BeforeGenerate();

            // Fill it with data
            if (!GenerateTrack(&*tmp, *track, ntrack))
               bGoodResult = false;
            else {
               // Transfer the data from the temporary track to the actual one
               tmp->Flush();
               SetTimeWarper(new StepTimeWarper(mT0+GetDuration(), GetDuration()-(mT1-mT0)));
               bGoodResult = track->ClearAndPaste(p->GetSel0(), p->GetSel1(), &*tmp, true,
                     false, GetTimeWarper());
            }

            if (!bGoodResult) {
               Failure();
               return false;
            }
         }
         else
         {
            // If the duration is zero, there's no need to actually
            // generate anything
            track->Clear(mT0, mT1);
         }

         ntrack++;
      }
      else if (t->IsSyncLockSelected()) {
         t->SyncLockAdjust(mT1, mT0 + GetDuration());
      }
      // Move on to the next track
      t = iter.Next();
   }

   Success();

   this->ReplaceProcessedTracks(bGoodResult);

   mT1 = mT0 + GetDuration(); // Update selection.

   return true;
}
Esempio n. 22
0
//------------------------- Processing methods -------------------------
bool EffectSineSweepGenerator::Process()
{
   // taken `as is` from Audacity`s Generator.cpp to resolve
   // a vc++ linking problem...
   
   if (mDuration < 0.0)
      return false;

   BeforeGenerate();

   // Set up mOutputTracks. This effect needs Track::All for grouping
   this->CopyInputTracks(Track::All);

   // Iterate over the tracks
   bool bGoodResult = true;
   int ntrack = 0;
   TrackListIterator iter(mOutputTracks);
   Track* t = iter.First();

   while (t != NULL)
   {
      if (t->GetKind() == Track::Wave && t->GetSelected()) 
      {
         WaveTrack* track = (WaveTrack*)t;
         
         bool editClipCanMove = true;
         //gPrefs->Read(wxT("/GUI/EditClipCanMove"), &editClipCanMove, true);

         //if we can't move clips, and we're generating into an empty space,
         //make sure there's room.
         if (!editClipCanMove &&
             track->IsEmpty(mT0, mT1+1.0/track->GetRate()) &&
             !track->IsEmpty(mT0, mT0+mDuration-(mT1-mT0)-1.0/track->GetRate()))
         {
             wxMessageBox(_("There is not enough room available to generate the audio"),
                          _("Error"), wxICON_STOP);   
            Failure();
            return false;
         }

         if (mDuration > 0.0)
         {
            // Create a temporary track
            WaveTrack *tmp = mFactory->NewWaveTrack(track->GetSampleFormat(),
                                                    track->GetRate());
            //BeforeTrack(*track);

            // Fill it with data
            if (!GenerateTrack(tmp, *track, ntrack))
               bGoodResult = false;
            else 
            {
               // Transfer the data from the temporary track to the actual one
               tmp->Flush();
               SetTimeWarper(new AFStepTimeWarper(mT0+mDuration, mDuration-(mT1-mT0)));
               bGoodResult = track->ClearAndPaste(mT0, mT1, tmp, true,
                     false, GetTimeWarper());
               delete tmp;
            }

            if (!bGoodResult) 
            {
               Failure();
               return false;
            }
         }
         else
         {
            // If the duration is zero, there's no need to actually
            // generate anything
            track->Clear(mT0, mT1);
         }

         ntrack++;
      }
      else if (t->IsSyncLockSelected()) 
      {
         t->SyncLockAdjust(mT1, mT0 + mDuration);
      }
      // Move on to the next track
      t = iter.Next();
   }

   Success();

   this->ReplaceProcessedTracks(bGoodResult);

   mT1 = mT0 + mDuration; // Update selection.

   return true;
}
Esempio n. 23
0
Error getCppCompletions(const core::json::JsonRpcRequest& request,
                        core::json::JsonRpcResponse* pResponse)
{
   // get params
   std::string docPath, userText;
   int line, column;
   Error error = json::readParams(request.params,
                                  &docPath,
                                  &line,
                                  &column,
                                  &userText);
   if (error)
      return error;

   // resolve the docPath if it's aliased
   FilePath filePath = module_context::resolveAliasedPath(docPath);

   // get the translation unit and do the code completion
   std::string filename = filePath.absolutePath();
   TranslationUnit tu = rSourceIndex().getTranslationUnit(filename);

   if (!tu.empty())
   {
      std::string lastTypedText;
      json::Array completionsJson;
      boost::shared_ptr<CodeCompleteResults> pResults =
                              tu.codeCompleteAt(filename, line, column);
      if (!pResults->empty())
      {
         // get results
         for (unsigned i = 0; i<pResults->getNumResults(); i++)
         {
            CodeCompleteResult result = pResults->getResult(i);

            // filter on user text if we have it
            if (!userText.empty() &&
                !boost::algorithm::starts_with(result.getTypedText(), userText))
            {
               continue;
            }

            // check whether this completion is valid and bail if not
            if (result.getAvailability() != CXAvailability_Available)
            {
               continue;
            }

            std::string typedText = result.getTypedText();

            // if we have the same typed text then just ammend previous result
            if ((typedText == lastTypedText) && !completionsJson.empty())
            {
               json::Object& res = completionsJson.back().get_obj();
               json::Array& text = res["text"].get_array();
               text.push_back(friendlyCompletionText(result));
            }
            else
            {
               completionsJson.push_back(toJson(result));
            }

            lastTypedText = typedText;
         }
      }

      json::Object resultJson;
      resultJson["completions"] = completionsJson;
      pResponse->setResult(resultJson);
   }
   else
   {
      // set null result indicating this file doesn't support completions
      pResponse->setResult(json::Value());
   }

   return Success();
}
Esempio n. 24
0
bool ZoneDatabase::LoadDoors(int32 door_count, Door *into, const char *zone_name, int16 version) {
	Log(Logs::General, Logs::Status, "Loading Doors from database...");

	std::string query = StringFormat(
			" SELECT "
			" 	id, "
			" 	doorid, "
			" 	zone, "
			" 	NAME, "
			" 	pos_x, "
			" 	pos_y, "
			" 	pos_z, "
			" 	heading, "
			" 	opentype, "
			" 	guild, "
			" 	lockpick, "
			" 	keyitem, "
			" 	nokeyring, "
			" 	triggerdoor, "
			" 	triggertype, "
			" 	dest_zone, "
			" 	dest_instance, "
			" 	dest_x, "
			" 	dest_y, "
			" 	dest_z, "
			" 	dest_heading, "
			" 	door_param, "
			" 	invert_state, "
			" 	incline, "
			" 	size, "
			" 	is_ldon_door, "
			" 	client_version_mask, "
			" 	disable_timer  "
			" FROM "
			" 	doors  "
			" WHERE "
			" 	zone = '%s'  "
			" 	AND ( version = % u OR version = - 1 )  "
			" ORDER BY "
			" 	doorid ASC ",
			zone_name,
			version
	);
	auto results = QueryDatabase(query);
	if (!results.Success()) {
		return false;
	}

	int32 row_index = 0;
	for (auto row = results.begin(); row != results.end(); ++row, ++row_index) {
		if (row_index >= door_count) {
			std::cerr << "Error, Door Count of " << door_count << " exceeded." << std::endl;
			break;
		}

		memset(&into[row_index], 0, sizeof(Door));

		strn0cpy(into[row_index].zone_name, row[2], 32);
		strn0cpy(into[row_index].door_name, row[3], 32);
		strn0cpy(into[row_index].dest_zone, row[15], 32);

		into[row_index].db_id               = static_cast<uint32>(atoi(row[0]));
		into[row_index].door_id             = static_cast<uint8>(atoi(row[1]));
		into[row_index].pos_x               = (float) atof(row[4]);
		into[row_index].pos_y               = (float) atof(row[5]);
		into[row_index].pos_z               = (float) atof(row[6]);
		into[row_index].heading             = (float) atof(row[7]);
		into[row_index].opentype            = static_cast<uint8>(atoi(row[8]));
		into[row_index].guild_id            = static_cast<uint32>(atoi(row[9]));
		into[row_index].lock_pick           = static_cast<uint16>(atoi(row[10]));
		into[row_index].keyitem             = static_cast<uint32>(atoi(row[11]));
		into[row_index].nokeyring           = static_cast<uint8>(atoi(row[12]));
		into[row_index].trigger_door        = static_cast<uint8>(atoi(row[13]));
		into[row_index].trigger_type        = static_cast<uint8>(atoi(row[14]));
		into[row_index].dest_instance_id    = static_cast<uint32>(atoi(row[16]));
		into[row_index].dest_x              = (float) atof(row[17]);
		into[row_index].dest_y              = (float) atof(row[18]);
		into[row_index].dest_z              = (float) atof(row[19]);
		into[row_index].dest_heading        = (float) atof(row[20]);
		into[row_index].door_param          = static_cast<uint32>(atoi(row[21]));
		into[row_index].invert_state        = atoi(row[22]);
		into[row_index].incline             = atoi(row[23]);
		into[row_index].size                = static_cast<uint16>(atoi(row[24]));
		into[row_index].is_ldon_door        = static_cast<uint8>(atoi(row[25]));
		into[row_index].client_version_mask = (uint32) strtoul(row[26], nullptr, 10);
		into[row_index].disable_timer       = static_cast<uint8>(atoi(row[27]));

		Log(Logs::Detail, Logs::Doors, "Door Load: db id: %u, door_id %u disable_timer: %i",
			into[row_index].db_id,
			into[row_index].door_id,
			into[row_index].disable_timer
		);
	}

	return true;
}
Esempio n. 25
0
void CommandBuilder::BuildCommand(const wxString &cmdName,
                                  const wxString &cmdParamsArg)
{
   // Stage 1: create a Command object of the right type

   auto scriptOutput = ScriptCommandRelay::GetResponseTarget();
   auto output
      = std::make_unique<CommandOutputTargets>(std::make_unique<NullProgressTarget>(),
                                scriptOutput,
                                scriptOutput);

#ifdef OLD_BATCH_SYSTEM
   OldStyleCommandType *factory = CommandDirectory::Get()->LookUp(cmdName);

   if (factory == NULL)
   {
      // Fall back to hoping the Batch Command system can handle it
#endif
      OldStyleCommandType *type = CommandDirectory::Get()->LookUp(wxT("BatchCommand"));
      wxASSERT(type != NULL);
      mCommand = type->Create(nullptr);
      mCommand->SetParameter(wxT("CommandName"), cmdName);
      mCommand->SetParameter(wxT("ParamString"), cmdParamsArg);
      auto aCommand = std::make_shared<ApplyAndSendResponse>(mCommand, output);
      Success(aCommand);
      return;
#ifdef OLD_BATCH_SYSTEM
   }

   CommandSignature &signature = factory->GetSignature();
   mCommand = factory->Create(nullptr);
   //mCommand->SetOutput( std::move(output) );
   // Stage 2: set the parameters

   ShuttleCli shuttle;
   shuttle.mParams = cmdParamsArg;
   shuttle.mbStoreInClient = true;

   ParamValueMap::const_iterator iter;
   ParamValueMap params = signature.GetDefaults();

   // Iterate through the parameters defined by the command
   for (iter = params.begin(); iter != params.end(); ++iter)
   {
      wxString paramString;
      // IF there is a match in the args actually used
      if (shuttle.TransferString(iter->first, paramString, wxT("")))
      {
         // Then set that parameter.
         if (!mCommand->SetParameter(iter->first, paramString))
         {
            Failure();
            return;
         }
      }
   }

   // Check for unrecognised parameters

   wxString cmdParams(cmdParamsArg);

   while (!cmdParams.empty())
   {
      cmdParams.Trim(true);
      cmdParams.Trim(false);
      int splitAt = cmdParams.Find(wxT('='));
      if (splitAt < 0 && !cmdParams.empty())
      {
         Failure(wxT("Parameter string is missing '='"));
         return;
      }
      wxString paramName = cmdParams.Left(splitAt);
      if (params.find(paramName) == params.end())
      {
         Failure(wxT("Unrecognized parameter: '") + paramName + wxT("'"));
         return;
      }
      // Handling of quoted strings is quite limitted.
      // You start and end with a " or a '.
      // There is no escaping in the string.
      cmdParams = cmdParams.Mid(splitAt+1);
      if( cmdParams.empty() )
         splitAt =-1;
      else if( cmdParams[0] == '\"' ){
         cmdParams = cmdParams.Mid(1);
         splitAt = cmdParams.Find(wxT('\"'))+1;
      }
      else if( cmdParams[0] == '\'' ){
         cmdParams = cmdParams.Mid(1);
         splitAt = cmdParams.Find(wxT('\''))+1;
      }
      else
         splitAt = cmdParams.Find(wxT(' '))+1;
      if (splitAt < 1)
      {
         splitAt = cmdParams.length();
      }
      cmdParams = cmdParams.Mid(splitAt);
   }
   auto aCommand = std::make_shared<ApplyAndSendResponse>(mCommand, output);
   Success(aCommand);
#endif
}
Esempio n. 26
0
Error parseDcfFile(const FilePath& dcfFilePath,
                   bool preserveKeyCase,
                   std::map<std::string,std::string>* pFields,
                   std::string* pUserErrMsg)
{
   // read the file
   std::string dcfFileContents;
   Error error = readStringFromFile(dcfFilePath,
                                    &dcfFileContents);
   if (error)
   {
      error.addProperty("dcf-file", dcfFilePath.absolutePath());
      *pUserErrMsg = error.summary();
      return error;
   }

   // split into lines
   std::vector<std::string> dcfLines;
   boost::algorithm::split(dcfLines,
                           dcfFileContents,
                           boost::algorithm::is_any_of("\r\n"));

   // iterate over lines
   int lineNumber = 0;
   std::string currentKey;
   std::string currentValue;
   for(std::vector<std::string>::const_iterator it = dcfLines.begin();
       it != dcfLines.end();
       ++it)
   {
      lineNumber++;

      // skip blank lines
      if (it->empty() || boost::algorithm::trim_copy(*it).empty())
         continue;

      // skip comment lines
      if (it->at(0) == '#')
         continue;

      // define regexes
      boost::regex keyValueRegx("([^\\s]+?)\\s*\\:\\s*(.*)$");
      boost::regex continuationRegex("[\t\\s](.*)");

       // look for a key-value pair line
      boost::smatch keyValueMatch, continuationMatch;
      if (regex_match(*it, keyValueMatch, keyValueRegx))
      {
         // if we have a pending key & value then resolve it
         if (!currentKey.empty())
         {
            pFields->insert(std::make_pair(currentKey,currentValue));
            currentKey.clear();
            currentValue.clear();
         }

         // update the current key and value
         currentKey = preserveKeyCase ?
                                 keyValueMatch[1] :
                                 string_utils::toLower(keyValueMatch[1]);
         currentValue = keyValueMatch[2];
      }

      // look for a continuation
      else if (!currentKey.empty() &&
               regex_match(*it, continuationMatch, continuationRegex))
      {
         currentValue.append("\n");
         currentValue.append(continuationMatch[1]);
      }

      // invalid line
      else
      {
         Error error = systemError(boost::system::errc::protocol_error,
                                   ERROR_LOCATION);
         boost::format fmt("file line number %1% is invalid");
         *pUserErrMsg = boost::str(fmt % lineNumber);
         error.addProperty("parse-error", *pUserErrMsg);
         error.addProperty("line-contents", *it);
         return error;
      }
   }

   // resolve any pending key and value
   if (!currentKey.empty())
      pFields->insert(std::make_pair(currentKey,currentValue));

   return Success();
}
Esempio n. 27
0
Error initialize()
{
   loadLearningState();
   return Success();
}
 virtual Error cleanup()
 {
    return Success();
 }
Esempio n. 29
0
Error completeEmbeddedRInitialization()
{
   return Success();
}
Bool BonkEnc::CDDBBatch::ReadEntries()
{
	String	 inputFormat = String::SetInputFormat("UTF-8");
	String	 outputFormat = String::SetOutputFormat("UTF-8");

	// Read saved queries from XML

	XML::Document	*document = new XML::Document();

	if (document->LoadFile(String(config->configDir).Append("cddb\\queries.xml")) == Success())
	{
		XML::Node	*root = document->GetRootNode();

		if (root != NIL)
		{
			for (Int i = 0; i < root->GetNOfNodes(); i++)
			{
				XML::Node	*node = root->GetNthNode(i);

				if (node->GetName() == "query") queries.Add(node->GetContent());
			}
		}
	}

	delete document;

	// Read saved submits from XML and database cache

	document = new XML::Document();

	if (document->LoadFile(String(config->configDir).Append("cddb\\submits.xml")) == Success())
	{
		XML::Node	*root = document->GetRootNode();

		if (root != NIL)
		{
			for (Int i = 0; i < root->GetNOfNodes(); i++)
			{
				XML::Node	*node = root->GetNthNode(i);

				if (node->GetName() == "submit")
				{
					InStream	*in = new InStream(STREAM_FILE, String(config->configDir).Append("cddb\\").Append(node->GetAttributeByName("category")->GetContent()).Append("\\").Append(node->GetContent()), IS_READONLY);

					if (in->Size() > 0)
					{
						String	 result = in->InputString(in->Size());
						CDDBInfo cddbInfo;

						ParseCDDBRecord(result, cddbInfo);

						cddbInfo.category = node->GetAttributeByName("category")->GetContent();

						for (Int i = 0; i < submits.Length(); i++)
						{
							if (submits.GetNth(i) == cddbInfo)
							{
								submits.Remove(submits.GetNthIndex(i));

								break;
							}
						}

						submits.Add(cddbInfo);
					}

					delete in;
				}
			}
		}
	}

	delete document;

	String::SetInputFormat(inputFormat);
	String::SetOutputFormat(outputFormat);

	return True;
}