Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <map>
- #include <mysql++/mysql++.h>
- #include <stdlib.h>
- #include "interface.h"
- #include "filesystem.h"
- #include "engine/iserverplugin.h"
- #include "dlls/iplayerinfo.h"
- #include "eiface.h"
- #include "igameevents.h"
- #include "convar.h"
- #include "Color.h"
- #include "vstdlib/random.h"
- #include "engine/IEngineTrace.h"
- // memdbgon must be the last include file in a .cpp file!!!
- #include "tier0/memdbgon.h"
- // Interfaces from the engine
- IVEngineServer *engine = NULL; // helper functions (messaging clients, loading content, making entities, running commands, etc)
- IFileSystem *filesystem = NULL; // file I/O
- IGameEventManager *gameeventmanager = NULL; // game events interface
- IPlayerInfoManager *playerinfomanager = NULL; // game dll interface to interact with players
- IBotManager *botmanager = NULL; // game dll interface to interact with bots
- IServerPluginHelpers *helpers = NULL; // special 3rd party plugin helpers from the engine
- IUniformRandomStream *randomStr = NULL;
- IEngineTrace *enginetrace = NULL;
- mysqlpp::Connection conn(false);
- const char* db = "csrank", *server = "localhost", *user = "csrank", *pass = "132009828";
- CGlobalVars *gpGlobals = NULL;
- // function to initialize any cvars/command in this plugin
- void InitCVars( CreateInterfaceFn cvarFactory );
- // useful helper func
- inline bool FStrEq(const char *sz1, const char *sz2)
- {
- return(Q_stricmp(sz1, sz2) == 0);
- }
- class User
- {
- public:
- User( char const *UserName, char const *UserPassword );
- ~User();
- virtual int RecheckAuth (char const *UserName, char const *UserPassword);
- virtual int GetSessionID (void);
- virtual int GetDataBaseID (void);
- virtual int BecomeNobody (void);
- virtual int CloseSession (int session, char const *Reason); //TODO move to plugin namespace
- virtual int player_death (int attacker_sessionid, char const *weapon, bool headshot);
- virtual int player_hurt (int attacker_sessionid, int health, int armor, char const *weapon, int dmg_health, int dmg_armor, int hitgroup);
- virtual int hostage_killed (void);
- virtual int hostage_rescued(void);
- virtual int bomb_defused(int site);
- virtual int bomb_exploded(int site);
- virtual int player_team(int newteam);
- private:
- int SessionID;
- int DataBaseID;
- virtual int TestUserInfo (char const *UserName, char const *UserPassword);
- virtual int UpdateUserID (int NewUserID);
- virtual int CreateSession (int ownerid); //TODO move to plugin namespace
- };
- int User::player_death (int attacker_sessionid, char const *weapon, bool headshot)
- {
- mysqlpp::Query query = conn.query();
- query << "INSERT INTO player_death VALUES (0," << SessionID << ", " << attacker_sessionid << ", " << mysqlpp::quote << weapon <<", " << headshot << ");";
- return query.exec();
- }
- int User::player_hurt (int attacker_sessionid, int health, int armor, char const *weapon, int dmg_health, int dmg_armor, int hitgroup)
- {
- mysqlpp::Query query = conn.query();
- query << "INSERT INTO player_hurt VALUES (0," << SessionID << ", " << attacker_sessionid << ", " << health << ", " << armor << ", " << mysqlpp::quote << weapon <<", " << dmg_health << ", " << dmg_armor << ", " << hitgroup << ");";
- return query.exec();
- }
- int User::hostage_killed (void)
- {
- mysqlpp::Query query = conn.query();
- query << "INSERT INTO hostage_killed VALUES (0, " << SessionID << ");";
- return query.exec();
- }
- int User::hostage_rescued (void)
- {
- mysqlpp::Query query = conn.query();
- query << "INSERT INTO hostage_rescued VALUES (0, " << SessionID << ");";
- return query.exec();
- }
- int User::bomb_defused(int site)
- {
- mysqlpp::Query query = conn.query();
- query << "INSERT INTO bomb_defused VALUES (0, " << SessionID << ", " << site << ");";
- return query.exec();
- }
- int User::bomb_exploded(int site)
- {
- mysqlpp::Query query = conn.query();
- query << "INSERT INTO bomb_exploded VALUES (0, " << SessionID << ", " << site << ");";
- return query.exec();
- }
- int User::player_team(int newteam)
- {
- mysqlpp::Query query = conn.query();
- query << "INSERT INTO player_team VALUES (0, " << SessionID << ", " << newteam << ");";
- return query.exec();
- }
- int User::BecomeNobody (void)
- {
- return UpdateUserID (1);
- }
- int User::CloseSession (int session, char const *Reason)
- {
- mysqlpp::Query query = conn.query();
- query << "UPDATE session SET session_end = now() , reason = " << mysqlpp::quote << Reason << "WHERE id = " << session;
- return query.exec();
- }
- int User::UpdateUserID (int NewUserID)
- {
- mysqlpp::Query query = conn.query();
- DataBaseID = NewUserID;
- query << "UPDATE session SET user_id = " << NewUserID << " WHERE id = " << SessionID;
- return query.exec();
- }
- int User::RecheckAuth (char const *UserName, char const *UserPassword)
- {
- int newid = TestUserInfo(UserName, UserPassword);
- if (newid == 1)
- return false;
- else
- if (newid == DataBaseID)
- return true;
- else
- UpdateUserID (newid);
- }
- int User::TestUserInfo (char const *UserName, char const *UserPassword)
- {
- mysqlpp::Query query = conn.query();
- query << "select id from user where login = " << mysqlpp::quote << UserName << " and pass = " << mysqlpp::quote << UserPassword;
- mysqlpp::UseQueryResult res = query.use();
- if (res) {
- if (mysqlpp::Row row = res.fetch_row())
- return row["id"];
- else
- return 1;
- } else
- return 1;
- }
- int User::GetDataBaseID (void)
- {
- return DataBaseID;
- }
- int User::GetSessionID (void)
- {
- return SessionID;
- }
- int User::CreateSession (int ownerid)
- {
- mysqlpp::Query query = conn.query();
- query << "INSERT INTO session VALUES (0," << ownerid << ", now(), '0000-00-00 00:00:00', '0', '0', '0', '0', '');";
- query.execute();
- return query.insert_id();
- }
- User::User (char const *UserName, char const *UserPassword)
- {
- DataBaseID= TestUserInfo(UserName, UserPassword);
- SessionID = CreateSession(DataBaseID);
- }
- User::~User ()
- {
- //CloseSession(SessionID, Reason);
- }
- // userid User
- std::map<int, User*> users;
- // userid edict
- std::map<int, edict_t*> edicts;
- //---------------------------------------------------------------------------------
- // Purpose: a sample 3rd party plugin class
- //---------------------------------------------------------------------------------
- class CEmptyServerPlugin: public IServerPluginCallbacks, public IGameEventListener
- {
- public:
- CEmptyServerPlugin();
- ~CEmptyServerPlugin();
- // IServerPluginCallbacks methods
- virtual bool Load( CreateInterfaceFn interfaceFactory, CreateInterfaceFn gameServerFactory );
- virtual void Unload( void );
- virtual void Pause( void );
- virtual void UnPause( void );
- virtual const char *GetPluginDescription( void );
- virtual void LevelInit( char const *pMapName );
- virtual void ServerActivate( edict_t *pEdictList, int edictCount, int clientMax );
- virtual void GameFrame( bool simulating );
- virtual void LevelShutdown( void );
- virtual void ClientActive( edict_t *pEntity );
- virtual void ClientDisconnect( edict_t *pEntity );
- virtual void ClientPutInServer( edict_t *pEntity, char const *playername );
- virtual void SetCommandClient( int index );
- virtual void ClientSettingsChanged( edict_t *pEdict );
- virtual PLUGIN_RESULT ClientConnect( bool *bAllowConnect, edict_t *pEntity, const char *pszName, const char *pszAddress, char *reject, int maxrejectlen );
- virtual PLUGIN_RESULT ClientCommand( edict_t *pEntity );
- virtual PLUGIN_RESULT NetworkIDValidated( const char *pszUserName, const char *pszNetworkID );
- // IGameEventListener Interface
- virtual void FireGameEvent( KeyValues * event );
- virtual int GetCommandIndex() { return m_iClientCommandIndex; }
- private:
- int m_iClientCommandIndex;
- };
- //
- // The plugin is a static singleton that is exported as an interface
- //
- CEmptyServerPlugin g_EmtpyServerPlugin;
- EXPOSE_SINGLE_INTERFACE_GLOBALVAR(CEmptyServerPlugin, IServerPluginCallbacks, INTERFACEVERSION_ISERVERPLUGINCALLBACKS, g_EmtpyServerPlugin );
- //---------------------------------------------------------------------------------
- // Purpose: constructor/destructor
- //---------------------------------------------------------------------------------
- CEmptyServerPlugin::CEmptyServerPlugin()
- {
- m_iClientCommandIndex = 0;
- }
- CEmptyServerPlugin::~CEmptyServerPlugin()
- {
- }
- //---------------------------------------------------------------------------------
- // Purpose: called when the plugin is loaded, load the interface we need from the engine
- //---------------------------------------------------------------------------------
- bool CEmptyServerPlugin::Load( CreateInterfaceFn interfaceFactory, CreateInterfaceFn gameServerFactory )
- {
- playerinfomanager = (IPlayerInfoManager *)gameServerFactory(INTERFACEVERSION_PLAYERINFOMANAGER,NULL);
- if ( !playerinfomanager )
- {
- Warning( "Unable to load playerinfomanager, ignoring\n" ); // this isn't fatal, we just won't be able to access specific player data
- }
- botmanager = (IBotManager *)gameServerFactory(INTERFACEVERSION_PLAYERBOTMANAGER, NULL);
- if ( !botmanager )
- {
- Warning( "Unable to load botcontroller, ignoring\n" ); // this isn't fatal, we just won't be able to access specific bot functions
- }
- // get the interfaces we want to use
- if( !(engine = (IVEngineServer*)interfaceFactory(INTERFACEVERSION_VENGINESERVER, NULL)) ||
- !(gameeventmanager = (IGameEventManager *)interfaceFactory(INTERFACEVERSION_GAMEEVENTSMANAGER,NULL)) ||
- !(filesystem = (IFileSystem*)interfaceFactory(FILESYSTEM_INTERFACE_VERSION, NULL)) ||
- !(helpers = (IServerPluginHelpers*)interfaceFactory(INTERFACEVERSION_ISERVERPLUGINHELPERS, NULL)) ||
- !(enginetrace = (IEngineTrace *)interfaceFactory(INTERFACEVERSION_ENGINETRACE_SERVER,NULL)) ||
- !(randomStr = (IUniformRandomStream *)interfaceFactory(VENGINE_SERVER_RANDOM_INTERFACE_VERSION, NULL))
- )
- {
- return false; // we require all these interface to function
- }
- if ( playerinfomanager )
- {
- gpGlobals = playerinfomanager->GetGlobalVars();
- }
- InitCVars( interfaceFactory ); // register any cvars we have defined
- MathLib_Init( 2.2f, 2.2f, 0.0f, 2.0f );
- if (conn.connect(db, server, user, pass)) {
- Msg ("Rank: DB connected\n");
- } else {
- Msg ("Rank: DB connection failed!\n");
- }
- return true;
- }
- //------------------------------------ ---------------------------------------------
- // Purpose: called when the plugin is unloaded (turned off)
- //---------------------------------------------------------------------------------
- void CEmptyServerPlugin::Unload( void )
- {
- gameeventmanager->RemoveListener( this ); // make sure we are unloaded from the event system
- }
- //---------------------------------------------------------------------------------
- // Purpose: called when the plugin is paused (i.e should stop running but isn't unloaded)
- //---------------------------------------------------------------------------------
- void CEmptyServerPlugin::Pause( void )
- {
- }
- //---------------------------------------------------------------------------------
- // Purpose: called when the plugin is unpaused (i.e should start executing again)
- //---------------------------------------------------------------------------------
- void CEmptyServerPlugin::UnPause( void )
- {
- }
- //---------------------------------------------------------------------------------
- // Purpose: the name of this plugin, returned in "plugin_print" command
- //---------------------------------------------------------------------------------
- const char *CEmptyServerPlugin::GetPluginDescription( void )
- {
- return "Rank: DB module.";
- }
- //---------------------------------------------------------------------------------
- // Purpose: called on level start
- //---------------------------------------------------------------------------------
- void CEmptyServerPlugin::LevelInit( char const *pMapName )
- {
- // Msg( "Level \"%s\" has been loaded\n", pMapName );
- gameeventmanager->AddListener( this, true );
- }
- //---------------------------------------------------------------------------------
- // Purpose: called on level start, when the server is ready to accept client connections
- // edictCount is the number of entities in the level, clientMax is the max client count
- //---------------------------------------------------------------------------------
- void CEmptyServerPlugin::ServerActivate( edict_t *pEdictList, int edictCount, int clientMax )
- {
- // Msg(" Server Activated \n");
- }
- //---------------------------------------------------------------------------------
- // Purpose: called once per server frame, do recurring work here (like checking for timeouts)
- //---------------------------------------------------------------------------------
- void CEmptyServerPlugin::GameFrame( bool simulating )
- {
- }
- //---------------------------------------------------------------------------------
- // Purpose: called on level end (as the server is shutting down or going to a new map)
- //---------------------------------------------------------------------------------
- void CEmptyServerPlugin::LevelShutdown( void ) // !!!!this can get called multiple times per map change
- {
- // Msg("Level shutdown \n");
- gameeventmanager->RemoveListener( this );
- }
- //---------------------------------------------------------------------------------
- // Purpose: called when a client spawns into a server (i.e as they begin to play)
- //---------------------------------------------------------------------------------
- void CEmptyServerPlugin::ClientActive( edict_t *pEntity )
- {
- }
- //---------------------------------------------------------------------------------
- // Purpose: called when a client leaves a server (or is timed out)
- //---------------------------------------------------------------------------------
- void CEmptyServerPlugin::ClientDisconnect( edict_t *pEntity )
- {
- int userid = engine->GetPlayerUserId(pEntity);
- edicts.erase(userid);
- }
- //---------------------------------------------------------------------------------
- // Purpose: called on
- //---------------------------------------------------------------------------------
- void CEmptyServerPlugin::ClientPutInServer( edict_t *pEntity, char const *playername )
- {
- }
- //---------------------------------------------------------------------------------
- // Purpose: called on level start
- //---------------------------------------------------------------------------------
- void CEmptyServerPlugin::SetCommandClient( int index )
- {
- m_iClientCommandIndex = index;
- }
- //---------------------------------------------------------------------------------
- // Purpose: called on level start
- //---------------------------------------------------------------------------------
- void CEmptyServerPlugin::ClientSettingsChanged( edict_t *pEdict )
- {
- }
- //---------------------------------------------------------------------------------
- // Purpose: called when a client joins a server
- //---------------------------------------------------------------------------------
- PLUGIN_RESULT CEmptyServerPlugin::ClientConnect( bool *bAllowConnect, edict_t *pEntity, const char *pszName, const char *pszAddress, char *reject, int maxrejectlen )
- {
- int userid = engine->GetPlayerUserId(pEntity);
- edicts[userid] = pEntity;
- if (!users[userid])
- {
- const char *ranklogin = engine->GetClientConVarValue( engine->IndexOfEdict(pEntity), "rankname" );
- const char *rankpassword = engine->GetClientConVarValue( engine->IndexOfEdict(pEntity), "rankpassword" );
- User *MyUser = new User(ranklogin, rankpassword);
- users[userid] = MyUser;
- Msg ("Rank: Joined %i as %i to %i \n", userid, MyUser->GetDataBaseID(), MyUser->GetSessionID());
- }
- return PLUGIN_CONTINUE;
- }
- //---------------------------------------------------------------------------------
- // Purpose: called when a client types in a command (only a subset of commands however, not CON_COMMAND's)
- //---------------------------------------------------------------------------------
- PLUGIN_RESULT CEmptyServerPlugin::ClientCommand( edict_t *pEntity )
- {
- const char *pcmd = engine->Cmd_Argv(0);
- if ( !pEntity || pEntity->IsFree() )
- {
- return PLUGIN_CONTINUE;
- }
- if ( FStrEq( pcmd, "rank_join" ) )
- {
- char msg[128];
- if (engine->Cmd_Argc() == 3)
- {
- const char *ranklogin = engine->Cmd_Argv(1);
- const char *rankpassword = engine->Cmd_Argv(2);
- if (users[engine->GetPlayerUserId(pEntity)]->RecheckAuth(ranklogin, rankpassword))
- Q_snprintf( msg, sizeof(msg), "Успех. Вы авторизованы как %s \n", ranklogin );
- else
- Q_snprintf( msg, sizeof(msg), "Пользователь %s не существует, или пароль не верен. \n", ranklogin );
- } else
- Q_snprintf( msg, sizeof(msg), "ОШИБКА: Не верный запрос!\nИспользование: rank_join ВАШ_ЛОГИН ВАШ_ПАРОЛЬ \n" );
- engine->ClientPrintf( pEntity, msg );
- return PLUGIN_STOP;
- } else
- if ( FStrEq( pcmd, "rank_leave" ) )
- {
- if (users[engine->GetPlayerUserId(pEntity)]->BecomeNobody())
- engine->ClientPrintf( pEntity, "ПРЕДУПРЕЖДЕНИЕ: Ваша сессия будет потеряна! \n" );
- return PLUGIN_STOP;
- } else
- if ( FStrEq( pcmd, "rank_recheck") )
- {
- const char *ranklogin = engine->GetClientConVarValue( engine->IndexOfEdict(pEntity), "rankname" );
- const char *rankpassword = engine->GetClientConVarValue( engine->IndexOfEdict(pEntity), "rankpassword" );
- char msg[128];
- if (users[engine->GetPlayerUserId(pEntity)]->RecheckAuth(ranklogin, rankpassword))
- Q_snprintf( msg, sizeof(msg), "Успех. Вы авторизованы как %s \n", ranklogin );
- else
- Q_snprintf( msg, sizeof(msg), "Пользователь %s не существует, или пароль не верен. \n", ranklogin );
- engine->ClientPrintf( pEntity, msg );
- return PLUGIN_STOP;
- } else
- if ( FStrEq( pcmd, "rank_whoiam") )
- {
- mysqlpp::Query query = conn.query();
- query << "select login from user where id = " << users[engine->GetPlayerUserId(pEntity)]->GetDataBaseID();
- char msg[128];
- const char *login;
- mysqlpp::UseQueryResult res = query.use();
- if (res)
- if (mysqlpp::Row row = res.fetch_row())
- {
- const char *login = row["login"];
- Q_snprintf( msg, sizeof(msg), "Вы авторизованы как %s \n", login );
- }
- engine->ClientPrintf( pEntity, msg );
- return PLUGIN_STOP;
- } else
- return PLUGIN_CONTINUE;
- }
- //---------------------------------------------------------------------------------
- // Purpose: called when a client is authenticated
- //---------------------------------------------------------------------------------
- PLUGIN_RESULT CEmptyServerPlugin::NetworkIDValidated( const char *pszUserName, const char *pszNetworkID )
- {
- return PLUGIN_CONTINUE;
- }
- // virtual int player_death (int attacker_sessionid, char const *weapon, bool headshot);
- // virtual int player_hurt (int attacker_sessionid, int health, int armor, char const *weapon, int dmg_health, int dmg_armor, int hitgroup);
- // virtual int hostage_killed (void);
- // virtual int hostage_rescued(void);
- // virtual int bomb_defused(int site);
- // virtual int bomb_exploded(int site);
- //---------------------------------------------------------------------------------
- // Purpose: called when an event is fired
- //---------------------------------------------------------------------------------
- void CEmptyServerPlugin::FireGameEvent( KeyValues * event )
- {
- const char * name = event->GetName();
- if (!users[event->GetInt("userid", 0)])
- return;
- if ( FStrEq( name, "player_hurt" ) )
- {
- users[event->GetInt("userid", 0)]->player_hurt(users[event->GetInt("attacker")]->GetSessionID(), event->GetInt("health", 0), event->GetInt("armor", 0), event->GetString("weapon", ""), event->GetInt("dmg_health", 0), event->GetInt("dmg_armor", 0), event->GetInt("hitgroup", 0));
- } else
- if ( FStrEq( name, "player_death" ) )
- {
- users[event->GetInt("userid", 0)]->player_death(users[event->GetInt("attacker")]->GetSessionID(), event->GetString("weapon", ""), event->GetInt("headshot", 0));
- } else
- if ( FStrEq( name, "hostage_killed" ) )
- {
- users[event->GetInt("userid", 0)]->hostage_killed();
- } else
- if ( FStrEq( name, "hostage_rescued" ) )
- {
- users[event->GetInt("userid", 0)]->hostage_rescued();
- } else
- if ( FStrEq( name, "bomb_defused" ) )
- {
- users[event->GetInt("userid", 0)]->bomb_defused(event->GetInt("site", 0));
- } else
- if ( FStrEq( name, "bomb_exploded" ) )
- {
- users[event->GetInt("userid", 0)]->bomb_exploded(event->GetInt("site", 0));
- } else
- if ( FStrEq( name, "player_team" ) )
- {
- users[event->GetInt("userid", 0)]->player_team(event->GetInt("team", 0));
- } else
- /*
- if ( FStrEq( name, " " ) )
- {
- users[event->GetInt("userid", 0)]-> (users[event->GetInt("attacker")]->GetSessionID(), );
- } else */
- if ( FStrEq( name, "player_disconnect") )
- {
- int userid = event->GetInt("userid", 0);
- const char * reason = event->GetString("reason", "");
- if (users[userid])
- {
- users[userid]->CloseSession(users[userid]->GetSessionID(), reason);
- delete (users[userid]);
- users.erase(userid);
- } else Msg ("Rank: Fault at erase %i user!\n", userid);
- }
- //else
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement