Example #1
0
std::pair<AString, AString> cWebPlugin::GetTabNameForRequest(const HTTPRequest & a_Request)
{
	AStringVector Split = StringSplit(a_Request.Path, "/");
	if (Split.empty())
	{
		return std::make_pair(AString(), AString());
	}

	cCSLock Lock(m_CSTabs);
	cTabPtr Tab;
	if (Split.size() > 2)  // If we got the tab name, show that page
	{
		for (auto itr = m_Tabs.cbegin(), end = m_Tabs.cend(); itr != end; ++itr)
		{
			if ((*itr)->m_SafeTitle.compare(Split[2]) == 0)  // This is the one!
			{
				return std::make_pair((*itr)->m_Title, (*itr)->m_SafeTitle);
			}
		}
		// Tab name not found, display an "empty" page:
		return std::make_pair(AString(), AString());
	}

	// Show the first tab:
	if (!m_Tabs.empty())
	{
		return std::make_pair(m_Tabs.front()->m_SafeTitle, m_Tabs.front()->m_SafeTitle);
	}

	// No tabs at all:
	return std::make_pair(AString(), AString());
}
Example #2
0
void cHTTPFormParser::ParseFormUrlEncoded(void)
{
	// Parse m_IncomingData for all the variables; no more data is incoming, since this is called from Finish()
	// This may not be the most performant version, but we don't care, the form data is small enough and we're not a full-fledged web server anyway
	AStringVector Lines = StringSplit(m_IncomingData, "&");
	for (AStringVector::iterator itr = Lines.begin(), end = Lines.end(); itr != end; ++itr)
	{
		AStringVector Components = StringSplit(*itr, "=");
		switch (Components.size())
		{
			default:
			{
				// Neither name nor value, or too many "="s, mark this as invalid form:
				m_IsValid = false;
				return;
			}
			case 1:
			{
				// Only name present
				(*this)[URLDecode(ReplaceAllCharOccurrences(Components[0], '+', ' '))] = "";
				break;
			}
			case 2:
			{
				// name=value format:
				(*this)[URLDecode(ReplaceAllCharOccurrences(Components[0], '+', ' '))] = URLDecode(ReplaceAllCharOccurrences(Components[1], '+', ' '));
				break;
			}
		}
	}  // for itr - Lines[]
	m_IncomingData.clear();
}
Example #3
0
void cPlayer::LoadPermissionsFromDisk()
{
    m_Groups.clear();
    m_Permissions.clear();

    cIniFile IniFile;
    if (IniFile.ReadFile("users.ini"))
    {
        std::string Groups = IniFile.GetValue(m_PlayerName, "Groups", "");
        if (!Groups.empty())
        {
            AStringVector Split = StringSplit( Groups, "," );
            for( unsigned int i = 0; i < Split.size(); i++ )
            {
                AddToGroup( Split[i].c_str() );
            }
        }
        else
        {
            AddToGroup("Default");
        }

        m_Color = IniFile.GetValue(m_PlayerName, "Color", "-")[0];
    }
    else
    {
        LOGWARN("Failed to read the users.ini file. The player will be added only to the Default group.");
        AddToGroup("Default");
    }
    ResolvePermissions();
}
Example #4
0
std::pair< AString, AString > cWebPlugin::GetTabNameForRequest(const HTTPRequest * a_Request)
{
	std::pair< AString, AString > Names;
	AStringVector Split = StringSplit(a_Request->Path, "/");

	if( Split.size() > 1 )
	{
		sWebPluginTab* Tab = 0;
		if( Split.size() > 2 )	// If we got the tab name, show that page
		{
			for( TabList::iterator itr = GetTabs().begin(); itr != GetTabs().end(); ++itr )
			{
				if( (*itr)->SafeTitle.compare( Split[2] ) == 0 ) // This is the one! Rawr
				{
					Tab = *itr;
					break;
				}
			}
		}
		else	// Otherwise show the first tab
		{
			if( GetTabs().size() > 0 )
				Tab = *GetTabs().begin();
		}

		if( Tab )
		{
			Names.first = Tab->Title;
			Names.second = Tab->SafeTitle;
		}
	}

	return Names;
}
Example #5
0
bool cPlayer::PermissionMatches(const AStringVector & a_Permission, const AStringVector & a_Template)
{
	// Check the sub-items if they are the same or there's a wildcard:
	size_t lenP = a_Permission.size();
	size_t lenT = a_Template.size();
	size_t minLen = std::min(lenP, lenT);
	for (size_t i = 0; i < minLen; i++)
	{
		if (a_Template[i] == "*")
		{
			// Has matched so far and now there's a wildcard in the template, so the permission matches:
			return true;
		}
		if (a_Permission[i] != a_Template[i])
		{
			// Found a mismatch
			return false;
		}
	}

	// So far all the sub-items have matched
	// If the sub-item count is the same, then the permission matches:
	if (lenP == lenT)
	{
		return true;
	}

	// There are more sub-items in either the permission or the template, not a match:
	return false;
}
Example #6
0
bool cCraftingRecipes::ParseItem(const AString & a_String, cItem & a_Item)
{
	// The caller provides error logging
	
	AStringVector Split = StringSplit(a_String, "^");
	if (Split.empty())
	{
		return false;
	}
	
	if (!StringToItem(Split[0], a_Item))
	{
		return false;
	}
	
	if (Split.size() > 1)
	{
		AString Damage = TrimString(Split[1]);
		if (!StringToInteger<short>(Damage.c_str(), a_Item.m_ItemDamage))
		{
			// Parsing the number failed
			return false;
		}
	}
	
	// Success
	return true;
}
Example #7
0
bool cGroupManager::CheckUsers()
{
	cIniFile IniFile;
	if (!IniFile.ReadFile("users.ini"))
	{
		GenerateDefaultUsersIni(IniFile);
		return true;
	}
	
	int NumKeys = IniFile.GetNumKeys();
	for (int i = 0; i < NumKeys; i++)
	{
		AString Player = IniFile.GetKeyName(i);
		AString Groups = IniFile.GetValue(Player, "Groups", "");
		if (Groups.empty())
		{
			continue;
		}
		AStringVector Split = StringSplitAndTrim(Groups, ",");
		for (AStringVector::const_iterator itr = Split.begin(), end = Split.end(); itr != end; ++itr)
		{
			if (!ExistsGroup(*itr))
			{
				LOGWARNING("The group %s for player %s was not found!", Split[i].c_str(), Player.c_str());
			}
		}  // for itr - Split[]
	}  // for i - ini file keys
	// Always return true for now, just but we can handle writefile fails later.
	return true;
}
Example #8
0
bool cPlugin_NewLua::OnExecuteCommand(cPlayer * a_Player, const AStringVector & a_Split)
{
	cCSLock Lock(m_CriticalSection);
	const char * FnName = GetHookFnName(cPluginManager::HOOK_EXECUTE_COMMAND);
	ASSERT(FnName != NULL);
	if (!PushFunction(FnName))
	{
		return false;
	}

	tolua_pushusertype(m_LuaState, a_Player, "cPlayer");

	// Push the split:
	lua_createtable(m_LuaState, a_Split.size(), 0);
	int newTable = lua_gettop(m_LuaState);
	int index = 1;
	std::vector<std::string>::const_iterator iter = a_Split.begin(), end = a_Split.end();
	while(iter != end)
	{
		tolua_pushstring(m_LuaState, (*iter).c_str());
		lua_rawseti(m_LuaState, newTable, index);
		++iter;
		++index;
	}

	if (!CallFunction(2, 1, FnName))
	{
		return false;
	}

	bool bRetVal = (tolua_toboolean(m_LuaState, -1, 0) > 0);
	lua_pop(m_LuaState, 1);
	return bRetVal;
}
Example #9
0
void cPrefab::ParseCharMap(CharMap & a_CharMapOut, const char * a_CharMapDef)
{
	ASSERT(a_CharMapDef != NULL);
	
	// Initialize the charmap to all-invalid values:
	for (size_t i = 0; i < ARRAYCOUNT(a_CharMapOut); i++)
	{
		a_CharMapOut[i].m_BlockType = 0;
		a_CharMapOut[i].m_BlockMeta = 16;  // Mark unassigned entries with a meta that is impossible otherwise
	}
	
	// Process the lines in the definition:
	AStringVector Lines = StringSplitAndTrim(a_CharMapDef, "\n");
	for (AStringVector::const_iterator itr = Lines.begin(), end = Lines.end(); itr != end; ++itr)
	{
		AStringVector CharDef = StringSplitAndTrim(*itr, ":");
		size_t NumElements = CharDef.size();
		if ((NumElements < 2) || CharDef[0].empty() || CharDef[1].empty())
		{
			LOGWARNING("Bad prefab CharMap definition line: \"%s\", skipping.", itr->c_str());
			continue;
		}
		unsigned char Src = (unsigned char)CharDef[0][0];
		ASSERT(a_CharMapOut[Src].m_BlockMeta == 16);  // This letter has not been assigned yet?
		a_CharMapOut[Src].m_BlockType = (BLOCKTYPE)atoi(CharDef[1].c_str());
		NIBBLETYPE BlockMeta = 0;
		if ((NumElements >= 3) && !CharDef[2].empty())
		{
			BlockMeta = (NIBBLETYPE)atoi(CharDef[2].c_str());
			ASSERT((BlockMeta <= 15));
		}
		a_CharMapOut[Src].m_BlockMeta = BlockMeta;
	}  // for itr - Lines[]
}
Example #10
0
AStringVector cPluginManager::GetFoldersToLoad(cSettingsRepositoryInterface & a_Settings)
{
	// Check if the Plugins section exists.
	if (!a_Settings.KeyExists("Plugins"))
	{
		InsertDefaultPlugins(a_Settings);
	}

	// Get the list of plugins to load:
	AStringVector res;
	auto Values = a_Settings.GetValues("Plugins");
	for (auto NameValue : Values)
	{
		AString ValueName = NameValue.first;
		if (ValueName.compare("Plugin") == 0)
		{
			AString PluginFile = NameValue.second;
			if (!PluginFile.empty())
			{
				res.push_back(PluginFile);
			}
		}
	}  // for i - ini values

	return res;
}
Example #11
0
sWebAdminPage cWebAdmin::GetPage(const HTTPRequest & a_Request)
{
	sWebAdminPage Page;
	AStringVector Split = StringSplit(a_Request.Path, "/");

	// Find the plugin that corresponds to the requested path
	AString FoundPlugin;
	if (Split.size() > 1)
	{
		for (PluginList::iterator itr = m_Plugins.begin(); itr != m_Plugins.end(); ++itr)
		{
			if ((*itr)->GetWebTitle() == Split[1])
			{
				Page.Content = (*itr)->HandleWebRequest(&a_Request);
				cWebPlugin * WebPlugin = *itr;
				FoundPlugin = WebPlugin->GetWebTitle();
				AString TabName = WebPlugin->GetTabNameForRequest(&a_Request).first;
				Page.PluginName = FoundPlugin;
				Page.TabName = TabName;
				break;
			}
		}
	}

	// Return the page contents
	return Page;
}
Example #12
0
void cPlayer::LoadPermissionsFromDisk()
{
	m_Groups.clear();
	m_Permissions.clear();

	cIniFile IniFile;
	if (IniFile.ReadFile("users.ini"))
	{
		AString Groups = IniFile.GetValueSet(GetName(), "Groups", "Default");
		AStringVector Split = StringSplitAndTrim(Groups, ",");

		for (AStringVector::const_iterator itr = Split.begin(), end = Split.end(); itr != end; ++itr)
		{
			if (!cRoot::Get()->GetGroupManager()->ExistsGroup(*itr))
			{
				LOGWARNING("The group %s for player %s was not found!", itr->c_str(), GetName().c_str());
			}
			AddToGroup(*itr);
		}

		AString Color = IniFile.GetValue(GetName(), "Color", "-");
		if (!Color.empty())
		{
			m_Color = Color[0];
		}
	}
	else
	{
		cGroupManager::GenerateDefaultUsersIni(IniFile);
		IniFile.AddValue("Groups", GetName(), "Default");
		AddToGroup("Default");
	}
	IniFile.WriteFile("users.ini");
	ResolvePermissions();
}
Example #13
0
void cPluginManager::FindPlugins(void)
{
	AString PluginsPath = FILE_IO_PREFIX + AString( "Plugins/" );

	// First get a clean list of only the currently running plugins, we don't want to mess those up
	for (PluginMap::iterator itr = m_Plugins.begin(); itr != m_Plugins.end();)
	{
		if (itr->second == NULL)
		{
			PluginMap::iterator thiz = itr;
			++thiz;
			m_Plugins.erase( itr );
			itr = thiz;
			continue;
		}
		++itr;
	}

	AStringVector Files = cFile::GetFolderContents(PluginsPath.c_str());
	for (AStringVector::const_iterator itr = Files.begin(); itr != Files.end(); ++itr)
	{
		if ((*itr == ".") || (*itr == "..") || (!cFile::IsFolder(PluginsPath + *itr)))
		{
			// We only want folders, and don't want "." or ".."
			continue;
		}

		// Add plugin name/directory to the list
		if (m_Plugins.find(*itr) == m_Plugins.end())
		{
			m_Plugins[*itr] = NULL;
		}
	}
}
Example #14
0
void cServer::ExecuteConsoleCommand(const AString & a_Cmd, cCommandOutputCallback & a_Output)
{
	AStringVector split = StringSplit(a_Cmd, " ");
	if (split.empty())
	{
		return;
	}
	
	// Special handling: "stop" and "restart" are built in
	if ((split[0].compare("stop") == 0) || (split[0].compare("restart") == 0))
	{
		return;
	}
	
	// "help" and "reload" are to be handled by MCS, so that they work no matter what
	if (split[0] == "help")
	{
		PrintHelp(split, a_Output);
		return;
	}
	if (split[0] == "reload")
	{
		cPluginManager::Get()->ReloadPlugins();
		return;
	}
	
	// There is currently no way a plugin can do these (and probably won't ever be):
	if (split[0].compare("chunkstats") == 0)
	{
		cRoot::Get()->LogChunkStats(a_Output);
		a_Output.Finished();
		return;
	}
	#if defined(_MSC_VER) && defined(_DEBUG) && defined(ENABLE_LEAK_FINDER)
	if (split[0].compare("dumpmem") == 0)
	{
		LeakFinderXmlOutput Output("memdump.xml");
		DumpUsedMemory(&Output);
		return;
	}
	
	if (split[0].compare("killmem") == 0)
	{
		while (true)
		{
			new char[100 * 1024 * 1024];  // Allocate and leak 100 MiB in a loop -> fill memory and kill MCS
		}
	}
	#endif
	
	if (cPluginManager::Get()->ExecuteConsoleCommand(split, a_Output))
	{
		a_Output.Finished();
		return;
	}
	
	a_Output.Out("Unknown command, type 'help' for all commands.");
	a_Output.Finished();
}
Example #15
0
AStringVector cFile::GetFolderContents(const AString & a_Folder)
{
	AStringVector AllFiles;

	#ifdef _WIN32

		// If the folder name doesn't contain the terminating slash / backslash, add it:
		AString FileFilter = a_Folder;
		if (
			!FileFilter.empty() &&
			(FileFilter[FileFilter.length() - 1] != '\\') &&
			(FileFilter[FileFilter.length() - 1] != '/')
		)
		{
			FileFilter.push_back('\\');
		}

		// Find all files / folders:
		FileFilter.append("*.*");
		HANDLE hFind;
		WIN32_FIND_DATAA FindFileData;
		if ((hFind = FindFirstFileA(FileFilter.c_str(), &FindFileData)) != INVALID_HANDLE_VALUE)
		{
			do
			{
				AllFiles.push_back(FindFileData.cFileName);
			} while (FindNextFileA(hFind, &FindFileData));
			FindClose(hFind);
		}

	#else  // _WIN32

		DIR * dp;
		AString Folder = a_Folder;
		if (Folder.empty())
		{
			Folder = ".";
		}
		if ((dp = opendir(Folder.c_str())) == nullptr)
		{
			LOGERROR("Error (%i) opening directory \"%s\"\n", errno, Folder.c_str());
		}
		else
		{
			struct dirent *dirp;
			while ((dirp = readdir(dp)) != nullptr)
			{
				AllFiles.push_back(dirp->d_name);
			}
			closedir(dp);
		}

	#endif  // else _WIN32

	return AllFiles;
}
Example #16
0
AStringVector cMojangAPI::GetUUIDsFromPlayerNames(const AStringVector & a_PlayerNames, bool a_UseOnlyCached)
{
	// Convert all playernames to lowercase:
	AStringVector PlayerNames;
	for (AStringVector::const_iterator itr = a_PlayerNames.begin(), end = a_PlayerNames.end(); itr != end; ++itr)
	{
		PlayerNames.push_back(StrToLower(*itr));
	}  // for itr - a_PlayerNames[]
	
	// Request the cache to populate any names not yet contained:
	if (!a_UseOnlyCached)
	{
		CacheNamesToUUIDs(PlayerNames);
	}
	
	// Retrieve from cache:
	size_t idx = 0;
	AStringVector res;
	res.resize(PlayerNames.size());
	cCSLock Lock(m_CSNameToUUID);
	for (AStringVector::const_iterator itr = PlayerNames.begin(), end = PlayerNames.end(); itr != end; ++itr, ++idx)
	{
		cProfileMap::const_iterator itrN = m_NameToUUID.find(*itr);
		if (itrN != m_NameToUUID.end())
		{
			res[idx] = itrN->second.m_UUID;
		}
	}  // for itr - PlayerNames[]
	return res;
}
void cComposableGenerator::InitFinishGens(cIniFile & a_IniFile)
{
	int Seed = m_ChunkGenerator.GetSeed();
	eDimension Dimension = StringToDimension(a_IniFile.GetValue("General", "Dimension", "Overworld"));

	AString Finishers = a_IniFile.GetValueSet("Generator", "Finishers", "SprinkleFoliage,Ice,Snow,Lilypads,BottomLava,DeadBushes,PreSimulator");
	AStringVector Str = StringSplitAndTrim(Finishers, ",");
	for (AStringVector::const_iterator itr = Str.begin(); itr != Str.end(); ++itr)
	{
		// Finishers, alpha-sorted:
		if (NoCaseCompare(*itr, "BottomLava") == 0)
		{
			int DefaultBottomLavaLevel = (Dimension == dimNether) ? 30 : 10;
			int BottomLavaLevel = a_IniFile.GetValueSetI("Generator", "BottomLavaLevel", DefaultBottomLavaLevel);
			m_FinishGens.push_back(new cFinishGenBottomLava(BottomLavaLevel));
		}
		else if (NoCaseCompare(*itr, "DeadBushes") == 0)
		{
			m_FinishGens.push_back(new cFinishGenSingleBiomeSingleTopBlock(Seed, E_BLOCK_DEAD_BUSH, biDesert, 2, E_BLOCK_SAND, E_BLOCK_SAND));
		}
		else if (NoCaseCompare(*itr, "Ice") == 0)
		{
			m_FinishGens.push_back(new cFinishGenIce);
		}
		else if (NoCaseCompare(*itr, "LavaSprings") == 0)
		{
			m_FinishGens.push_back(new cFinishGenFluidSprings(Seed, E_BLOCK_LAVA, a_IniFile, Dimension));
		}
		else if (NoCaseCompare(*itr, "Lilypads") == 0)
		{
			m_FinishGens.push_back(new cFinishGenSingleBiomeSingleTopBlock(Seed, E_BLOCK_LILY_PAD, biSwampland, 4, E_BLOCK_WATER, E_BLOCK_STATIONARY_WATER));
		}
		else if (NoCaseCompare(*itr, "NetherClumpFoliage") == 0)
		{
			m_FinishGens.push_back(new cFinishGenNetherClumpFoliage(Seed));
		}
		else if (NoCaseCompare(*itr, "PreSimulator") == 0)
		{
			m_FinishGens.push_back(new cFinishGenPreSimulator);
		}
		else if (NoCaseCompare(*itr, "Snow") == 0)
		{
			m_FinishGens.push_back(new cFinishGenSnow);
		}
		else if (NoCaseCompare(*itr, "SprinkleFoliage") == 0)
		{
			m_FinishGens.push_back(new cFinishGenSprinkleFoliage(Seed));
		}
		else if (NoCaseCompare(*itr, "WaterSprings") == 0)
		{
			m_FinishGens.push_back(new cFinishGenFluidSprings(Seed, E_BLOCK_WATER, a_IniFile, Dimension));
		}
	}  // for itr - Str[]
}
Example #18
0
AString cWebAdmin::GetBaseURL(const AStringVector & a_URLSplit)
{
	AString BaseURL = "./";
	if (a_URLSplit.size() > 1)
	{
		for (unsigned int i = 0; i < a_URLSplit.size(); i++)
		{
			BaseURL += "../";
		}
		BaseURL += "webadmin/";
	}
	return BaseURL;
}
Example #19
0
int CStartupInfo::ShowMessageLines(const char *message)
{
  AStringVector strings;
  SplitString(message, strings);
  const int kNumStringsMax = 20;
  const char *items[kNumStringsMax + 1] = { GetMsgString(NMessageID::kError) };
  int pos = 1;
  for (int i = 0; i < strings.Size() && pos < kNumStringsMax; i++)
    items[pos++] = strings[i];
  items[pos++] = GetMsgString(NMessageID::kOk);

  return ShowMessage(FMSG_WARNING, NULL, items, pos, 1);
}
Example #20
0
void cFireworkItem::FadeColoursFromString(const AString & a_String, cFireworkItem & a_FireworkItem)
{
	AStringVector Split = StringSplit(a_String, ";");

	for (size_t itr = 0; itr < Split.size(); ++itr)
	{
		if (Split[itr].empty())
		{
			continue;
		}

		a_FireworkItem.m_FadeColours.push_back(atoi(Split[itr].c_str()));
	}
}
Example #21
0
void cLuaState::Push(const AStringVector & a_Vector)
{
	ASSERT(IsValid());

	lua_createtable(m_LuaState, static_cast<int>(a_Vector.size()), 0);
	int newTable = lua_gettop(m_LuaState);
	int index = 1;
	for (AStringVector::const_iterator itr = a_Vector.begin(), end = a_Vector.end(); itr != end; ++itr, ++index)
	{
		tolua_pushstring(m_LuaState, itr->c_str());
		lua_rawseti(m_LuaState, newTable, index);
	}
	m_NumCurrentFunctionArgs += 1;
}
Example #22
0
bool cPlugin_NewLua::HandleConsoleCommand(const AStringVector & a_Split, cCommandOutputCallback & a_Output)
{
	ASSERT(!a_Split.empty());
	CommandMap::iterator cmd = m_ConsoleCommands.find(a_Split[0]);
	if (cmd == m_ConsoleCommands.end())
	{
		LOGWARNING("Console command handler is registered in cPluginManager but not in cPlugin, wtf? Console command \"%s\", plugin \"%s\".",
			a_Split[0].c_str(), GetName().c_str()
		);
		return false;
	}
	
	cCSLock Lock(m_CriticalSection);
	
	// Push the function to be called:
	lua_rawgeti(m_LuaState, LUA_REGISTRYINDEX, cmd->second);  // same as lua_getref()
	
	// Push the split:
	lua_createtable(m_LuaState, a_Split.size(), 0);
	int newTable = lua_gettop(m_LuaState);
	int index = 1;
	std::vector<std::string>::const_iterator iter = a_Split.begin(), end = a_Split.end();
	while(iter != end)
	{
		tolua_pushstring(m_LuaState, (*iter).c_str());
		lua_rawseti(m_LuaState, newTable, index);
		++iter;
		++index;
	}
	
	// Call function:
	int s = lua_pcall(m_LuaState, 1, 2, 0);
	if (report_errors(m_LuaState, s))
	{
		LOGERROR("Lua error. Stack size: %i", lua_gettop(m_LuaState));
		return false;
	}
	
	// Handle return values:
	if (lua_isstring(m_LuaState, -1))
	{
		AString str = tolua_tocppstring(m_LuaState, -1, "");
		a_Output.Out(str);
	}
	bool RetVal = (tolua_toboolean(m_LuaState, -2, 0) > 0);
	lua_pop(m_LuaState, 2);  // Pop return values
	
	return RetVal;
}
Example #23
0
	void AddToMap(const AString & a_Name, const AString & a_Value)
	{
		AStringVector Split = StringSplit(a_Value, ":");
		if (Split.size() == 1)
		{
			Split = StringSplit(a_Value, "^");
		}
		if (Split.empty())
		{
			return;
		}
		short ItemType = (short)atoi(Split[0].c_str());
		short ItemDamage = (Split.size() > 1) ? (short)atoi(Split[1].c_str()) : -1;
		m_Map[a_Name] = std::make_pair(ItemType, ItemDamage);
	}
Example #24
0
	bool ResolveItem(const AString & a_ItemName, cItem & a_Item)
	{
		// Split into parts divided by either ':' or '^'
		AStringVector Split = StringSplitAndTrim(a_ItemName, ":^");
		if (Split.empty())
		{
			return false;
		}

		ItemMap::iterator itr = m_Map.find(Split[0]);
		if (itr != m_Map.end())
		{
			// Resolved as a string, assign the type and the default damage / count
			a_Item.m_ItemType = itr->second.first;
			a_Item.m_ItemDamage = itr->second.second;
			if (a_Item.m_ItemDamage == -1)
			{
				a_Item.m_ItemDamage = 0;
			}
		}
		else
		{
			// Not a resolvable string, try pure numbers: "45:6", "45^6" etc.
			a_Item.m_ItemType = (short)atoi(Split[0].c_str());
			if ((a_Item.m_ItemType == 0) && (Split[0] != "0"))
			{
				// Parsing the number failed
				return false;
			}
		}
		
		// Parse the damage, if present:
		if (Split.size() < 2)
		{
			// Not present, set the item as valid and return success:
			a_Item.m_ItemCount = 1;
			return true;
		}
		
		a_Item.m_ItemDamage = (short)atoi(Split[1].c_str());
		if ((a_Item.m_ItemDamage == 0) && (Split[1] != "0"))
		{
			// Parsing the number failed
			return false;
		}
		a_Item.m_ItemCount = 1;
		return true;
	}
Example #25
0
bool cPluginManager::ExecuteConsoleCommand(const AStringVector & a_Split, cCommandOutputCallback & a_Output, const AString & a_Command)
{
	if (a_Split.empty())
	{
		return false;
	}

	CommandMap::iterator cmd = m_ConsoleCommands.find(a_Split[0]);
	if (cmd == m_ConsoleCommands.end())
	{
		// Command not found
		// Still notify the plugins (so that plugins such as Aliases can intercept unknown commands).
		CommandResult res = crBlocked;
		CallHookExecuteCommand(nullptr, a_Split, a_Command, res);
		return (res == crExecuted);
	}

	if (cmd->second.m_Plugin == nullptr)
	{
		// This is a built-in command
		return false;
	}

	// Ask plugins first if a command is okay to execute the console command:
	CommandResult res = crBlocked;
	if (CallHookExecuteCommand(nullptr, a_Split, a_Command, res))
	{
		return (res == crExecuted);
	}

	return cmd->second.m_Handler->ExecuteCommand(a_Split, nullptr, a_Command, &a_Output);
}
Example #26
0
bool cPluginManager::ExecuteConsoleCommand(const AStringVector & a_Split, cCommandOutputCallback & a_Output)
{
	if (a_Split.empty())
	{
		return false;
	}
	
	CommandMap::iterator cmd = m_ConsoleCommands.find(a_Split[0]);
	if (cmd == m_ConsoleCommands.end())
	{
		// Command not found
		return false;
	}
	
	if (cmd->second.m_Plugin == NULL)
	{
		// This is a built-in command
		return false;
	}
	
	// Ask plugins first if a command is okay to execute the console command:
	if (CallHookExecuteCommand(NULL, a_Split))
	{
		a_Output.Out("Command \"%s\" was stopped by the HOOK_EXECUTE_COMMAND hook", a_Split[0].c_str());
		return false;
	}

	return cmd->second.m_Plugin->HandleConsoleCommand(a_Split, a_Output);	
}
Example #27
0
bool cPlugin_NewLua::HandleCommand(const AStringVector & a_Split, cPlayer * a_Player)
{
	ASSERT(!a_Split.empty());
	CommandMap::iterator cmd = m_Commands.find(a_Split[0]);
	if (cmd == m_Commands.end())
	{
		LOGWARNING("Command handler is registered in cPluginManager but not in cPlugin, wtf? Command \"%s\".", a_Split[0].c_str());
		return false;
	}
	
	cCSLock Lock(m_CriticalSection);
	
	// Push the function to be called:
	lua_rawgeti(m_LuaState, LUA_REGISTRYINDEX, cmd->second);  // same as lua_getref()
	
	// Push the split:
	lua_createtable(m_LuaState, a_Split.size(), 0);
	int newTable = lua_gettop(m_LuaState);
	int index = 1;
	std::vector<std::string>::const_iterator iter = a_Split.begin(), end = a_Split.end();
	while(iter != end)
	{
		tolua_pushstring(m_LuaState, (*iter).c_str());
		lua_rawseti(m_LuaState, newTable, index);
		++iter;
		++index;
	}
	
	// Push player:
	tolua_pushusertype(m_LuaState, a_Player, "cPlayer");
	
	// Call function:
	int s = lua_pcall(m_LuaState, 2, 1, 0);
	if (report_errors(m_LuaState, s))
	{
		LOGERROR("LUA error in %s. Stack size: %i", __FUNCTION__, lua_gettop(m_LuaState));
		return false;
	}
	
	// Handle return value:
	bool RetVal = (tolua_toboolean(m_LuaState, -1, 0) > 0);
	lua_pop(m_LuaState, 1);  // Pop return value
	
	return RetVal;
}
Example #28
0
	bool ResolveItem(const AString & a_ItemName, cItem & a_Item)
	{
		ItemMap::iterator itr = m_Map.find(a_ItemName);
		if (itr != m_Map.end())
		{
			a_Item.m_ItemType = itr->second.first;
			a_Item.m_ItemDamage = itr->second.second;
			if (a_Item.m_ItemDamage == -1)
			{
				a_Item.m_ItemDamage = 0;
			}
			a_Item.m_ItemCount = 1;
			return true;
		}

		// Not a resolvable string, try pure numbers: "45:6", "45^6" etc.
		AStringVector Split = StringSplit(a_ItemName, ":");
		if (Split.size() == 1)
		{
			Split = StringSplit(a_ItemName, "^");
		}
		if (Split.empty())
		{
			return false;
		}
		a_Item.m_ItemType = (short)atoi(Split[0].c_str());
		if ((a_Item.m_ItemType == 0) && (Split[0] != "0"))
		{
			// Parsing the number failed
			return false;
		}
		if (Split.size() < 2)
		{
			a_Item.m_ItemCount = 1;
			return true;
		}
		a_Item.m_ItemDamage = atoi(Split[1].c_str());
		if ((a_Item.m_ItemDamage == 0) && (Split[1] != "0"))
		{
			// Parsing the number failed
			return false;
		}
		a_Item.m_ItemCount = 1;
		return true;
	}
Example #29
0
void cPluginManager::RefreshPluginList(void)
{
	// Get a list of currently available folders:
	AString PluginsPath = GetPluginsPath() + "/";
	AStringVector Contents = cFile::GetFolderContents(PluginsPath.c_str());
	AStringVector Folders;
	for (auto & item: Contents)
	{
		if ((item == ".") || (item == "..") || (!cFile::IsFolder(PluginsPath + item)))
		{
			// We only want folders, and don't want "." or ".."
			continue;
		}
		Folders.push_back(item);
	}  // for item - Contents[]

	// Set all plugins with invalid folders as psNotFound:
	for (auto & plugin: m_Plugins)
	{
		if (std::find(Folders.cbegin(), Folders.cend(), plugin->GetFolderName()) == Folders.end())
		{
			plugin->m_Status = psNotFound;
		}
	}  // for plugin - m_Plugins[]

	// Add all newly discovered plugins:
	for (auto & folder: Folders)
	{
		bool hasFound = false;
		for (auto & plugin: m_Plugins)
		{
			if (plugin->GetFolderName() == folder)
			{
				hasFound = true;
				break;
			}
		}  // for plugin - m_Plugins[]
		if (!hasFound)
		{
			m_Plugins.push_back(std::make_shared<cPluginLua>(folder));
		}
	}  // for folder - Folders[]
}
Example #30
0
void cPrefab::ParseDepthWeight(const char * a_DepthWeightDef)
{
	// The member needn't be defined at all, if so, skip:
	if (a_DepthWeightDef == NULL)
	{
		return;
	}
	
	// Split into individual records: "Record | Record | Record"
	AStringVector Defs = StringSplitAndTrim(a_DepthWeightDef, "|");
	
	// Add each record's contents:
	for (AStringVector::const_iterator itr = Defs.begin(), end = Defs.end(); itr != end; ++itr)
	{
		// Split into components: "Depth : Weight"
		AStringVector Components = StringSplitAndTrim(*itr, ":");
		if (Components.size() != 2)
		{
			LOGWARNING("Bad prefab DepthWeight record: \"%s\", skipping.", itr->c_str());
			continue;
		}
		
		// Parse depth:
		int Depth = atoi(Components[0].c_str());
		if ((Depth == 0) && (Components[0] != "0"))
		{
			LOGWARNING("Bad prefab DepthWeight record, cannot parse depth \"%s\", skipping.", Components[0].c_str());
			continue;
		}
		
		// Parse weight:
		int Weight = atoi(Components[1].c_str());
		if ((Weight == 0) && (Components[1] != "0"))
		{
			LOGWARNING("Bad prefab DepthWeight record, cannot parse weight \"%s\", skipping.", Components[1].c_str());
			continue;
		}
		
		// Save to map:
		ASSERT(m_DepthWeight.find(Depth) == m_DepthWeight.end());  // Not a duplicate
		m_DepthWeight[Depth] = Weight;
	}  // for itr - Defs[]
}