core/PlayerManager.cpp
author Ruben Gonzalez <drifter01620@gmail.com>
Thu May 22 09:49:27 2014 -0400 (2014-05-22)
changeset 4378 568f4497ef4a
parent 4344 c445c3266192
permissions -rw-r--r--
Update CS:GO team score gamedata.
     1 /**
     2  * vim: set ts=4 sw=4 tw=99 noet :
     3  * =============================================================================
     4  * SourceMod
     5  * Copyright (C) 2004-2009 AlliedModders LLC.  All rights reserved.
     6  * =============================================================================
     7  *
     8  * This program is free software; you can redistribute it and/or modify it under
     9  * the terms of the GNU General Public License, version 3.0, as published by the
    10  * Free Software Foundation.
    11  * 
    12  * This program is distributed in the hope that it will be useful, but WITHOUT
    13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
    14  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
    15  * details.
    16  *
    17  * You should have received a copy of the GNU General Public License along with
    18  * this program.  If not, see <http://www.gnu.org/licenses/>.
    19  *
    20  * As a special exception, AlliedModders LLC gives you permission to link the
    21  * code of this program (as well as its derivative works) to "Half-Life 2," the
    22  * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
    23  * by the Valve Corporation.  You must obey the GNU General Public License in
    24  * all respects for all other code used.  Additionally, AlliedModders LLC grants
    25  * this exception to all derivative works.  AlliedModders LLC defines further
    26  * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
    27  * or <http://www.sourcemod.net/license.php>.
    28  *
    29  * Version: $Id$
    30  */
    31 
    32 #include "PlayerManager.h"
    33 #include "AdminCache.h"
    34 #include "ConCmdManager.h"
    35 #include "MenuStyle_Valve.h"
    36 #include "MenuStyle_Radio.h"
    37 #include "sm_stringutil.h"
    38 #include "CoreConfig.h"
    39 #include "TimerSys.h"
    40 #include "Logger.h"
    41 #include "ChatTriggers.h"
    42 #include "HalfLife2.h"
    43 #include <inetchannel.h>
    44 #include <iclient.h>
    45 #include <IGameConfigs.h>
    46 #include "ConsoleDetours.h"
    47 #include "logic_bridge.h"
    48 #include <sourcemod_version.h>
    49 
    50 PlayerManager g_Players;
    51 bool g_OnMapStarted = false;
    52 IForward *PreAdminCheck = NULL;
    53 IForward *PostAdminCheck = NULL;
    54 IForward *PostAdminFilter = NULL;
    55 
    56 const unsigned int *g_NumPlayersToAuth = NULL;
    57 int lifestate_offset = -1;
    58 List<ICommandTargetProcessor *> target_processors;
    59 
    60 #if SOURCE_ENGINE == SE_DOTA
    61 SH_DECL_HOOK5(IServerGameClients, ClientConnect, SH_NOATTRIB, 0, bool, CEntityIndex, const char *, const char *, char *, int);
    62 SH_DECL_HOOK2_void(IServerGameClients, ClientPutInServer, SH_NOATTRIB, 0, CEntityIndex, const char *);
    63 SH_DECL_HOOK2_void(IServerGameClients, ClientDisconnect, SH_NOATTRIB, 0, CEntityIndex, int);
    64 SH_DECL_HOOK2_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, CEntityIndex, const CCommand &);
    65 SH_DECL_HOOK1_void(IServerGameClients, ClientSettingsChanged, SH_NOATTRIB, 0, CEntityIndex);
    66 #else
    67 SH_DECL_HOOK5(IServerGameClients, ClientConnect, SH_NOATTRIB, 0, bool, edict_t *, const char *, const char *, char *, int);
    68 SH_DECL_HOOK2_void(IServerGameClients, ClientPutInServer, SH_NOATTRIB, 0, edict_t *, const char *);
    69 SH_DECL_HOOK1_void(IServerGameClients, ClientDisconnect, SH_NOATTRIB, 0, edict_t *);
    70 #if SOURCE_ENGINE >= SE_ORANGEBOX
    71 SH_DECL_HOOK2_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *, const CCommand &);
    72 #else
    73 SH_DECL_HOOK1_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *);
    74 #endif
    75 SH_DECL_HOOK1_void(IServerGameClients, ClientSettingsChanged, SH_NOATTRIB, 0, edict_t *);
    76 #endif // SE_DOTA
    77 
    78 #if SOURCE_ENGINE == SE_DOTA
    79 SH_DECL_HOOK0_void(IServerGameDLL, ServerActivate, SH_NOATTRIB, 0);
    80 #else
    81 SH_DECL_HOOK3_void(IServerGameDLL, ServerActivate, SH_NOATTRIB, 0, edict_t *, int, int);
    82 #endif
    83 
    84 #if SOURCE_ENGINE == SE_DOTA
    85 SH_DECL_EXTERN2_void(ConCommand, Dispatch, SH_NOATTRIB, false, const CCommandContext &, const CCommand &);
    86 #elif SOURCE_ENGINE >= SE_ORANGEBOX
    87 SH_DECL_EXTERN1_void(ConCommand, Dispatch, SH_NOATTRIB, false, const CCommand &);
    88 #elif SOURCE_ENGINE == SE_DARKMESSIAH
    89 SH_DECL_EXTERN0_void(ConCommand, Dispatch, SH_NOATTRIB, false);
    90 #else
    91 # if SH_IMPL_VERSION >= 4
    92  extern int __SourceHook_FHAddConCommandDispatch(void *,bool,class fastdelegate::FastDelegate0<void>);
    93 # else
    94  extern bool __SourceHook_FHAddConCommandDispatch(void *,bool,class fastdelegate::FastDelegate0<void>);
    95 # endif
    96 extern bool __SourceHook_FHRemoveConCommandDispatch(void *,bool,class fastdelegate::FastDelegate0<void>);
    97 #endif
    98 
    99 ConCommand *maxplayersCmd = NULL;
   100 
   101 unsigned int g_PlayerSerialCount = 0;
   102 
   103 class KickPlayerTimer : public ITimedEvent
   104 {
   105 public:
   106 	ResultType OnTimer(ITimer *pTimer, void *pData)
   107 	{
   108 		int userid = (int)pData;
   109 		int client = g_Players.GetClientOfUserId(userid);
   110 		if (client)
   111 		{
   112 			CPlayer *player = g_Players.GetPlayerByIndex(client);
   113 			player->Kick("Your name is reserved by SourceMod; set your password to use it.");
   114 		}
   115 		return Pl_Stop;
   116 	}
   117 	void OnTimerEnd(ITimer *pTimer, void *pData)
   118 	{
   119 	}
   120 } s_KickPlayerTimer;
   121 
   122 PlayerManager::PlayerManager()
   123 {
   124 	m_AuthQueue = NULL;
   125 	m_FirstPass = false;
   126 	m_maxClients = 0;
   127 
   128 	m_SourceTVUserId = -1;
   129 	m_ReplayUserId = -1;
   130 
   131 	m_bAuthstringValidation = true; // use steam auth by default
   132 
   133 	m_UserIdLookUp = new int[USHRT_MAX+1];
   134 	memset(m_UserIdLookUp, 0, sizeof(int) * (USHRT_MAX+1));
   135 }
   136 
   137 PlayerManager::~PlayerManager()
   138 {
   139 	g_NumPlayersToAuth = NULL;
   140 
   141 	delete [] m_AuthQueue;
   142 	delete [] m_UserIdLookUp;
   143 }
   144 
   145 void PlayerManager::OnSourceModAllInitialized()
   146 {
   147 	SH_ADD_HOOK(IServerGameClients, ClientConnect, serverClients, SH_MEMBER(this, &PlayerManager::OnClientConnect), false);
   148 	SH_ADD_HOOK(IServerGameClients, ClientConnect, serverClients, SH_MEMBER(this, &PlayerManager::OnClientConnect_Post), true);
   149 	SH_ADD_HOOK(IServerGameClients, ClientPutInServer, serverClients, SH_MEMBER(this, &PlayerManager::OnClientPutInServer), true);
   150 	SH_ADD_HOOK(IServerGameClients, ClientDisconnect, serverClients, SH_MEMBER(this, &PlayerManager::OnClientDisconnect), false);
   151 	SH_ADD_HOOK(IServerGameClients, ClientDisconnect, serverClients, SH_MEMBER(this, &PlayerManager::OnClientDisconnect_Post), true);
   152 	SH_ADD_HOOK(IServerGameClients, ClientCommand, serverClients, SH_MEMBER(this, &PlayerManager::OnClientCommand), false);
   153 	SH_ADD_HOOK(IServerGameClients, ClientSettingsChanged, serverClients, SH_MEMBER(this, &PlayerManager::OnClientSettingsChanged), true);
   154 	SH_ADD_HOOK(IServerGameDLL, ServerActivate, gamedll, SH_MEMBER(this, &PlayerManager::OnServerActivate), true);
   155 
   156 	sharesys->AddInterface(NULL, this);
   157 
   158 	ParamType p1[] = {Param_Cell, Param_String, Param_Cell};
   159 	ParamType p2[] = {Param_Cell};
   160 
   161 	m_clconnect = forwardsys->CreateForward("OnClientConnect", ET_LowEvent, 3, p1);
   162 	m_clconnect_post = forwardsys->CreateForward("OnClientConnected", ET_Ignore, 1, p2);
   163 	m_clputinserver = forwardsys->CreateForward("OnClientPutInServer", ET_Ignore, 1, p2);
   164 	m_cldisconnect = forwardsys->CreateForward("OnClientDisconnect", ET_Ignore, 1, p2);
   165 	m_cldisconnect_post = forwardsys->CreateForward("OnClientDisconnect_Post", ET_Ignore, 1, p2);
   166 	m_clcommand = forwardsys->CreateForward("OnClientCommand", ET_Hook, 2, NULL, Param_Cell, Param_Cell);
   167 	m_clinfochanged = forwardsys->CreateForward("OnClientSettingsChanged", ET_Ignore, 1, p2);
   168 	m_clauth = forwardsys->CreateForward("OnClientAuthorized", ET_Ignore, 2, NULL, Param_Cell, Param_String);
   169 	m_onActivate = forwardsys->CreateForward("OnServerLoad", ET_Ignore, 0, NULL);
   170 	m_onActivate2 = forwardsys->CreateForward("OnMapStart", ET_Ignore, 0, NULL);
   171 
   172 	PreAdminCheck = forwardsys->CreateForward("OnClientPreAdminCheck", ET_Event, 1, p1);
   173 	PostAdminCheck = forwardsys->CreateForward("OnClientPostAdminCheck", ET_Ignore, 1, p1);
   174 	PostAdminFilter = forwardsys->CreateForward("OnClientPostAdminFilter", ET_Ignore, 1, p1);
   175 
   176 	m_bIsListenServer = !engine->IsDedicatedServer();
   177 	m_ListenClient = 0;
   178 
   179 	ConCommand *pCmd = FindCommand("maxplayers");
   180 	if (pCmd != NULL)
   181 	{
   182 		SH_ADD_HOOK(ConCommand, Dispatch, pCmd, SH_STATIC(CmdMaxplayersCallback), true);
   183 		maxplayersCmd = pCmd;
   184 	}
   185 }
   186 
   187 void PlayerManager::OnSourceModShutdown()
   188 {
   189 	SH_REMOVE_HOOK(IServerGameClients, ClientConnect, serverClients, SH_MEMBER(this, &PlayerManager::OnClientConnect), false);
   190 	SH_REMOVE_HOOK(IServerGameClients, ClientConnect, serverClients, SH_MEMBER(this, &PlayerManager::OnClientConnect_Post), true);
   191 	SH_REMOVE_HOOK(IServerGameClients, ClientPutInServer, serverClients, SH_MEMBER(this, &PlayerManager::OnClientPutInServer), true);
   192 	SH_REMOVE_HOOK(IServerGameClients, ClientDisconnect, serverClients, SH_MEMBER(this, &PlayerManager::OnClientDisconnect), false);
   193 	SH_REMOVE_HOOK(IServerGameClients, ClientDisconnect, serverClients, SH_MEMBER(this, &PlayerManager::OnClientDisconnect_Post), true);
   194 	SH_REMOVE_HOOK(IServerGameClients, ClientCommand, serverClients, SH_MEMBER(this, &PlayerManager::OnClientCommand), false);
   195 	SH_REMOVE_HOOK(IServerGameClients, ClientSettingsChanged, serverClients, SH_MEMBER(this, &PlayerManager::OnClientSettingsChanged), true);
   196 	SH_REMOVE_HOOK(IServerGameDLL, ServerActivate, gamedll, SH_MEMBER(this, &PlayerManager::OnServerActivate), true);
   197 
   198 	/* Release forwards */
   199 	forwardsys->ReleaseForward(m_clconnect);
   200 	forwardsys->ReleaseForward(m_clconnect_post);
   201 	forwardsys->ReleaseForward(m_clputinserver);
   202 	forwardsys->ReleaseForward(m_cldisconnect);
   203 	forwardsys->ReleaseForward(m_cldisconnect_post);
   204 	forwardsys->ReleaseForward(m_clcommand);
   205 	forwardsys->ReleaseForward(m_clinfochanged);
   206 	forwardsys->ReleaseForward(m_clauth);
   207 	forwardsys->ReleaseForward(m_onActivate);
   208 	forwardsys->ReleaseForward(m_onActivate2);
   209 
   210 	forwardsys->ReleaseForward(PreAdminCheck);
   211 	forwardsys->ReleaseForward(PostAdminCheck);
   212 	forwardsys->ReleaseForward(PostAdminFilter);
   213 
   214 	delete [] m_Players;
   215 
   216 	if (maxplayersCmd != NULL)
   217 	{
   218 		SH_REMOVE_HOOK(ConCommand, Dispatch, maxplayersCmd, SH_STATIC(CmdMaxplayersCallback), true);
   219 	}
   220 }
   221 
   222 ConfigResult PlayerManager::OnSourceModConfigChanged(const char *key, 
   223 												 const char *value, 
   224 												 ConfigSource source, 
   225 												 char *error, 
   226 												 size_t maxlength)
   227 {
   228 	if (strcmp(key, "PassInfoVar") == 0)
   229 	{
   230 		if (strcmp(value, "_password") != 0)
   231 		{
   232 			m_PassInfoVar.assign(value);
   233 		}
   234 		return ConfigResult_Accept;
   235 	} else if (strcmp(key, "AllowClLanguageVar") == 0) {
   236 		if (strcasecmp(value, "on") == 0)
   237 		{
   238 			m_QueryLang = true;
   239 		} else if (strcasecmp(value, "off") == 0) {
   240 			m_QueryLang = false;
   241 		} else {
   242 			UTIL_Format(error, maxlength, "Invalid value: must be \"on\" or \"off\"");
   243 			return ConfigResult_Reject;
   244 		}
   245 		return ConfigResult_Accept;
   246 	} else if (strcmp( key, "SteamAuthstringValidation" ) == 0) {
   247 		if (strcasecmp(value, "yes") == 0)
   248 		{
   249 			m_bAuthstringValidation = true;
   250 		} else if ( strcasecmp(value, "no") == 0) {
   251 			m_bAuthstringValidation = false;
   252 		} else {
   253 			UTIL_Format(error, maxlength, "Invalid value: must be \"yes\" or \"no\"");
   254 			return ConfigResult_Reject;
   255 		}
   256 		return ConfigResult_Accept;
   257 	}
   258 	return ConfigResult_Ignore;
   259 }
   260 
   261 #if SOURCE_ENGINE == SE_DOTA
   262 void PlayerManager::OnServerActivate()
   263 #else
   264 void PlayerManager::OnServerActivate(edict_t *pEdictList, int edictCount, int clientMax)
   265 #endif
   266 {
   267 	static ConVar *tv_enable = icvar->FindVar("tv_enable");
   268 #if SOURCE_ENGINE == SE_TF2
   269 	static ConVar *replay_enable = icvar->FindVar("replay_enable");
   270 #endif
   271 
   272 	// clientMax will not necessarily be correct here (such as on late SourceTV enable)
   273 	m_maxClients = gpGlobals->maxClients;
   274 
   275 	ICommandLine *commandLine = g_HL2.GetValveCommandLine();
   276 	m_bIsSourceTVActive = (tv_enable && tv_enable->GetBool() && (!commandLine || commandLine->FindParm("-nohltv") == 0));
   277 	m_bIsReplayActive = false;
   278 #if SOURCE_ENGINE == SE_TF2
   279 	m_bIsReplayActive = (replay_enable && replay_enable->GetBool());
   280 #endif
   281 	m_PlayersSinceActive = 0;
   282 	
   283 	if (!m_FirstPass)
   284 	{
   285 		/* Initialize all players */
   286 
   287 		m_PlayerCount = 0;
   288 		m_Players = new CPlayer[SM_MAXPLAYERS + 1];
   289 		m_AuthQueue = new unsigned int[SM_MAXPLAYERS + 1];
   290 		m_FirstPass = true;
   291 
   292 		memset(m_AuthQueue, 0, sizeof(unsigned int) * (SM_MAXPLAYERS + 1));
   293 
   294 		g_NumPlayersToAuth = &m_AuthQueue[0];
   295 	}
   296 
   297 	scripts->SyncMaxClients(m_maxClients);
   298 
   299 	g_OnMapStarted = true;
   300 
   301 #if SOURCE_ENGINE == SE_DOTA
   302 	extsys->CallOnCoreMapStart(gpGlobals->pEdicts, gpGlobals->maxEntities, gpGlobals->maxClients);
   303 #else
   304 	extsys->CallOnCoreMapStart(pEdictList, edictCount, m_maxClients);
   305 #endif
   306 
   307 	m_onActivate->Execute(NULL);
   308 	m_onActivate2->Execute(NULL);
   309 
   310 	List<IClientListener *>::iterator iter;
   311 	for (iter = m_hooks.begin(); iter != m_hooks.end(); iter++)
   312 	{
   313 		if ((*iter)->GetClientListenerVersion() >= 5)
   314 		{
   315 			(*iter)->OnServerActivated(m_maxClients);
   316 		}
   317 	}
   318 
   319 	SMGlobalClass *cls = SMGlobalClass::head;
   320 	while (cls)
   321 	{
   322 		cls->OnSourceModLevelActivated();
   323 		cls = cls->m_pGlobalClassNext;
   324 	}
   325 
   326 	SM_ExecuteAllConfigs();
   327 }
   328 
   329 bool PlayerManager::IsServerActivated()
   330 {
   331 	return m_FirstPass;
   332 }
   333 
   334 bool PlayerManager::CheckSetAdmin(int index, CPlayer *pPlayer, AdminId id)
   335 {
   336 	const char *password = g_Admins.GetAdminPassword(id);
   337 	if (password != NULL)
   338 	{
   339 		if (m_PassInfoVar.size() < 1)
   340 		{
   341 			return false;
   342 		}
   343 
   344 		/* Whoa... the user needs a password! */
   345 		const char *given = engine->GetClientConVarValue(index, m_PassInfoVar.c_str());
   346 		if (!given || strcmp(given, password) != 0)
   347 		{
   348 			return false;
   349 		}
   350 	}
   351 
   352 	pPlayer->SetAdminId(id, false);
   353 
   354 	return true;
   355 }
   356 
   357 bool PlayerManager::CheckSetAdminName(int index, CPlayer *pPlayer, AdminId id)
   358 {
   359 	const char *password = g_Admins.GetAdminPassword(id);
   360 	if (password == NULL)
   361 	{
   362 		return false;
   363 	}
   364 
   365 	if (m_PassInfoVar.size() < 1)
   366 	{
   367 		return false;
   368 	}
   369 
   370 	/* Whoa... the user needs a password! */
   371 	const char *given = engine->GetClientConVarValue(index, m_PassInfoVar.c_str());
   372 	if (!given || strcmp(given, password) != 0)
   373 	{
   374 		return false;
   375 	}
   376 
   377 	pPlayer->SetAdminId(id, false);
   378 
   379 	return true;
   380 }
   381 
   382 void PlayerManager::RunAuthChecks()
   383 {
   384 	CPlayer *pPlayer;
   385 	const char *authstr;
   386 	unsigned int removed = 0;
   387 	for (unsigned int i=1; i<=m_AuthQueue[0]; i++)
   388 	{
   389 		pPlayer = &m_Players[m_AuthQueue[i]];
   390 #if SOURCE_ENGINE == SE_DOTA
   391 		authstr = engine->GetPlayerNetworkIDString(pPlayer->m_iIndex - 1);
   392 #else
   393 		authstr = engine->GetPlayerNetworkIDString(pPlayer->m_pEdict);
   394 #endif
   395 		pPlayer->SetAuthString(authstr);
   396 
   397 		if (!pPlayer->IsAuthStringValidated())
   398 		{
   399 			continue; // we're using steam auth, and steam doesn't know about this player yet so we can't do anything about them for now
   400 		}
   401 
   402 		if (authstr && authstr[0] != '\0'
   403 			&& (strcmp(authstr, "STEAM_ID_PENDING") != 0))
   404 		{
   405 			/* Set authorization */
   406 			pPlayer->Authorize();
   407 
   408 			/* Mark as removed from queue */
   409 			unsigned int client = m_AuthQueue[i];
   410 			m_AuthQueue[i] = 0;
   411 			removed++;
   412 
   413 			/* Send to extensions */
   414 			List<IClientListener *>::iterator iter;
   415 			IClientListener *pListener;
   416 			for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
   417 			{
   418 				pListener = (*iter);
   419 				pListener->OnClientAuthorized(client, authstr);
   420 				if (!pPlayer->IsConnected())
   421 				{
   422 					break;
   423 				}
   424 			}
   425 
   426 			/* Send to plugins if player is still connected */
   427 			if (pPlayer->IsConnected() && m_clauth->GetFunctionCount())
   428 			{
   429 				/* :TODO: handle the case of a player disconnecting in the middle */
   430 				m_clauth->PushCell(client);
   431 				m_clauth->PushString(authstr);
   432 				m_clauth->Execute(NULL);
   433 			}
   434 
   435 			if (pPlayer->IsConnected())
   436 			{
   437 				pPlayer->Authorize_Post();
   438 			}
   439 		}
   440 	}
   441 
   442 	/* Clean up the queue */
   443 	if (removed)
   444 	{
   445 		/* We don't have to compact the list if it's empty */
   446 		if (removed != m_AuthQueue[0])
   447 		{
   448 			unsigned int diff = 0;
   449 			for (unsigned int i=1; i<=m_AuthQueue[0]; i++)
   450 			{
   451 				/* If this member is removed... */
   452 				if (m_AuthQueue[i] == 0)
   453 				{
   454 					/* Increase the differential */
   455 					diff++;
   456 				} else {
   457 					/* diff cannot increase faster than i+1 */
   458 					assert(i > diff);
   459 					assert(i - diff >= 1);
   460 					/* move this index down */
   461 					m_AuthQueue[i - diff] = m_AuthQueue[i];
   462 				}
   463 			}
   464 			m_AuthQueue[0] -= removed;
   465 		} else {
   466 			m_AuthQueue[0] = 0;
   467 		}
   468 	}
   469 }
   470 
   471 #if SOURCE_ENGINE == SE_DOTA
   472 bool PlayerManager::OnClientConnect(CEntityIndex index, const char *pszName, const char *pszAddress, char *reject, int maxrejectlen)
   473 {
   474 	int client = index.Get();
   475 	edict_t *pEntity = PEntityOfEntIndex(client);
   476 #else
   477 bool PlayerManager::OnClientConnect(edict_t *pEntity, const char *pszName, const char *pszAddress, char *reject, int maxrejectlen)
   478 {
   479 	int client = IndexOfEdict(pEntity);
   480 #endif
   481 	CPlayer *pPlayer = &m_Players[client];
   482 	++m_PlayersSinceActive;
   483 
   484 	pPlayer->Initialize(pszName, pszAddress, pEntity);
   485 	
   486 	/* Get the client's language */
   487 	if (m_QueryLang)
   488 	{
   489 		const char *name;
   490 		if (!pPlayer->IsFakeClient() && (name=engine->GetClientConVarValue(client, "cl_language")))
   491 		{
   492 			unsigned int langid;
   493 			pPlayer->m_LangId = (translator->GetLanguageByName(name, &langid)) ? langid : translator->GetServerLanguage();
   494 		} else {
   495 			pPlayer->m_LangId = translator->GetServerLanguage();
   496 		}
   497 	}
   498 	
   499 	List<IClientListener *>::iterator iter;
   500 	IClientListener *pListener = NULL;
   501 	for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
   502 	{
   503 		pListener = (*iter);
   504 		if (!pListener->InterceptClientConnect(client, reject, maxrejectlen))
   505 		{
   506 			RETURN_META_VALUE(MRES_SUPERCEDE, false);
   507 		}
   508 	}
   509 
   510 	cell_t res = 1;
   511 
   512 	m_clconnect->PushCell(client);
   513 	m_clconnect->PushStringEx(reject, maxrejectlen, SM_PARAM_STRING_UTF8 | SM_PARAM_STRING_COPY, SM_PARAM_COPYBACK);
   514 	m_clconnect->PushCell(maxrejectlen);
   515 	m_clconnect->Execute(&res);
   516 
   517 	if (res)
   518 	{
   519 		if (!pPlayer->IsAuthorized())
   520 		{
   521 			m_AuthQueue[++m_AuthQueue[0]] = client;
   522 		}
   523 
   524 		m_UserIdLookUp[GetPlayerUserId(pEntity)] = client;
   525 	}
   526 	else
   527 	{
   528 		if (!pPlayer->IsFakeClient())
   529 		{
   530 			RETURN_META_VALUE(MRES_SUPERCEDE, false);
   531 		}
   532 	}
   533 
   534 	return true;
   535 }
   536 
   537 #if SOURCE_ENGINE == SE_DOTA
   538 bool PlayerManager::OnClientConnect_Post(CEntityIndex index, const char *pszName, const char *pszAddress, char *reject, int maxrejectlen)
   539 {
   540 	int client = index.Get();
   541 	edict_t *pEntity = PEntityOfEntIndex(client);
   542 #else
   543 bool PlayerManager::OnClientConnect_Post(edict_t *pEntity, const char *pszName, const char *pszAddress, char *reject, int maxrejectlen)
   544 {
   545 	int client = IndexOfEdict(pEntity);
   546 #endif
   547 
   548 	bool orig_value = META_RESULT_ORIG_RET(bool);
   549 	CPlayer *pPlayer = &m_Players[client];
   550 
   551 	if (orig_value)
   552 	{
   553 		List<IClientListener *>::iterator iter;
   554 		IClientListener *pListener = NULL;
   555 		for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
   556 		{
   557 			pListener = (*iter);
   558 			pListener->OnClientConnected(client);
   559 			if (!pPlayer->IsConnected())
   560 			{
   561 				return true;
   562 			}
   563 		}
   564 
   565 		if (!pPlayer->IsFakeClient() 
   566 			&& m_bIsListenServer
   567 			&& strncmp(pszAddress, "127.0.0.1", 9) == 0)
   568 		{
   569 			m_ListenClient = client;
   570 		}
   571 
   572 		cell_t res;
   573 		m_clconnect_post->PushCell(client);
   574 		m_clconnect_post->Execute(&res, NULL);
   575 	}
   576 	else
   577 	{
   578 		InvalidatePlayer(pPlayer);
   579 	}
   580 
   581 	return true;
   582 }
   583 
   584 #if SOURCE_ENGINE == SE_DOTA
   585 void PlayerManager::OnClientPutInServer(CEntityIndex index, const char *playername)
   586 {
   587 	int client = index.Get();
   588 	edict_t *pEntity = PEntityOfEntIndex(client);
   589 #else
   590 void PlayerManager::OnClientPutInServer(edict_t *pEntity, const char *playername)
   591 {
   592 	int client = IndexOfEdict(pEntity);
   593 #endif
   594 
   595 	cell_t res;
   596 	CPlayer *pPlayer = &m_Players[client];
   597 
   598 	/* If they're not connected, they're a bot */
   599 	if (!pPlayer->IsConnected())
   600 	{
   601 		/* Run manual connection routines */
   602 		char error[255];
   603 		const char *authid;
   604 #if SOURCE_ENGINE == SE_DOTA
   605 		authid = engine->GetPlayerNetworkIDString(client - 1);
   606 #else
   607 		authid = engine->GetPlayerNetworkIDString(pEntity);
   608 #endif
   609 		pPlayer->SetAuthString(authid);
   610 		pPlayer->Authorize();
   611 		pPlayer->m_bFakeClient = true;
   612 
   613 		/*
   614 		 * While we're already filtered to just bots, we'll do other checks to
   615 		 * make sure that the requisite services are enabled and that the bots
   616 		 * have joined at the expected time.
   617 		 *
   618 		 * Checking playerinfo's IsHLTV and IsReplay would be better and less
   619 		 * error-prone but will always show false until later in the frame,
   620 		 * after PutInServer and Activate, and we want it now!
   621 		 *
   622 		 * These checks are hairy as hell due to differences between engines and games.
   623 		 * 
   624 		 * Most engines use "Replay" and "SourceTV" as bot names for these when they're
   625 		 * created. EP2V, CSS and Nuclear Dawn (but not L4D2) differ from this by now using
   626 		 * replay_/tv_name directly when creating the bot(s). To complicate it slightly
   627 		 * further, the cvar can be empty and the engine's fallback to "unnamed" will be used.
   628 		 * We can maybe just rip out the name checks at some point and rely solely on whether
   629 		 * they're enabled and the join order.
   630 		 */
   631 		
   632 		// This doesn't actually get incremented until OnClientConnect. Fake it to check.
   633 		int newCount = m_PlayersSinceActive + 1;
   634 
   635 		int userId = GetPlayerUserId(pEntity);
   636 #if (SOURCE_ENGINE == SE_CSS || SOURCE_ENGINE == SE_HL2DM || SOURCE_ENGINE == SE_DODS || SOURCE_ENGINE == SE_TF2 || SOURCE_ENGINE == SE_NUCLEARDAWN || SOURCE_ENGINE == SE_LEFT4DEAD2)
   637 		static ConVar *tv_name = icvar->FindVar("tv_name");
   638 #endif
   639 #if SOURCE_ENGINE == SE_TF2
   640 		static ConVar *replay_name = icvar->FindVar("replay_name");
   641 #endif
   642 
   643 #if SOURCE_ENGINE == SE_TF2
   644 		if (m_bIsReplayActive && newCount == 1
   645 			&& (m_ReplayUserId == userId
   646 				|| (replay_name && strcmp(playername, replay_name->GetString()) == 0) || (replay_name && replay_name->GetString()[0] == 0 && strcmp(playername, "unnamed") == 0)
   647 				)
   648 			)
   649 		{
   650 			pPlayer->m_bIsReplay = true;
   651 			m_ReplayUserId = userId;
   652 		}
   653 #endif
   654 
   655 		if (m_bIsSourceTVActive
   656 			&& ((!m_bIsReplayActive && newCount == 1)
   657 				|| (m_bIsReplayActive && newCount == 2))
   658 			&& (m_SourceTVUserId == userId
   659 #if SOURCE_ENGINE == SE_CSGO
   660 				|| strcmp(playername, "GOTV") == 0
   661 #elif (SOURCE_ENGINE == SE_CSS || SOURCE_ENGINE == SE_HL2DM || SOURCE_ENGINE == SE_DODS || SOURCE_ENGINE == SE_TF2 || SOURCE_ENGINE == SE_NUCLEARDAWN)
   662 				|| (tv_name && strcmp(playername, tv_name->GetString()) == 0) || (tv_name && tv_name->GetString()[0] == 0 && strcmp(playername, "unnamed") == 0)
   663 #else
   664 				|| strcmp(playername, "SourceTV") == 0
   665 #endif
   666 				)
   667 			)
   668 		{
   669 			pPlayer->m_bIsSourceTV = true;
   670 			m_SourceTVUserId = userId;
   671 		}
   672 
   673 #if SOURCE_ENGINE == SE_DOTA
   674 		if (!OnClientConnect(client, playername, "127.0.0.1", error, sizeof(error)))
   675 #else
   676 		if (!OnClientConnect(pEntity, playername, "127.0.0.1", error, sizeof(error)))
   677 #endif
   678 		{
   679 			/* :TODO: kick the bot if it's rejected */
   680 			return;
   681 		}
   682 		List<IClientListener *>::iterator iter;
   683 		IClientListener *pListener = NULL;
   684 		for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
   685 		{
   686 			pListener = (*iter);
   687 			pListener->OnClientConnected(client);
   688 			/* See if bot was kicked */
   689 			if (!pPlayer->IsConnected())
   690 			{
   691 				return;
   692 			}
   693 		}
   694 
   695 		cell_t res;
   696 		m_clconnect_post->PushCell(client);
   697 		m_clconnect_post->Execute(&res, NULL);
   698 
   699 		/* Now do authorization */
   700 		for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
   701 		{
   702 			pListener = (*iter);
   703 			pListener->OnClientAuthorized(client, authid);
   704 		}
   705 		/* Finally, tell plugins */
   706 		if (m_clauth->GetFunctionCount())
   707 		{
   708 			m_clauth->PushCell(client);
   709 			m_clauth->PushString(authid);
   710 			m_clauth->Execute(NULL);
   711 		}
   712 		pPlayer->Authorize_Post();
   713 	}
   714 
   715 	if (playerinfo)
   716 	{
   717 		pPlayer->m_Info = playerinfo->GetPlayerInfo(pEntity);
   718 	}
   719 
   720 	pPlayer->Connect();
   721 	m_PlayerCount++;
   722 
   723 	List<IClientListener *>::iterator iter;
   724 	IClientListener *pListener = NULL;
   725 	for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
   726 	{
   727 		pListener = (*iter);
   728 		pListener->OnClientPutInServer(client);
   729 	}
   730 
   731 	m_clputinserver->PushCell(client);
   732 	m_clputinserver->Execute(&res, NULL);
   733 
   734 	if (pPlayer->IsAuthorized())
   735 	{
   736 		pPlayer->DoPostConnectAuthorization();
   737 	}
   738 }
   739 
   740 void PlayerManager::OnSourceModLevelEnd()
   741 {
   742 	/* Disconnect all bots still in game */
   743 	for (int i=1; i<=m_maxClients; i++)
   744 	{
   745 		if (m_Players[i].IsConnected())
   746 		{
   747 #if SOURCE_ENGINE == SE_DOTA
   748 			OnClientDisconnect(m_Players[i].GetIndex(), 0);
   749 #else
   750 			OnClientDisconnect(m_Players[i].GetEdict());
   751 #endif
   752 		}
   753 	}
   754 	m_PlayerCount = 0;
   755 }
   756 
   757 #if SOURCE_ENGINE == SE_DOTA
   758 void PlayerManager::OnClientDisconnect(CEntityIndex index, int reason)
   759 {
   760 	int client = index.Get();
   761 	edict_t *pEntity = PEntityOfEntIndex(client);
   762 #else
   763 void PlayerManager::OnClientDisconnect(edict_t *pEntity)
   764 {
   765 	int client = IndexOfEdict(pEntity);
   766 #endif
   767 
   768 	cell_t res;
   769 	CPlayer *pPlayer = &m_Players[client];
   770 
   771 	if (pPlayer->IsConnected())
   772 	{
   773 		m_cldisconnect->PushCell(client);
   774 		m_cldisconnect->Execute(&res, NULL);
   775 	}
   776 	else
   777 	{
   778 		/* We don't care, prevent a double call */
   779 		return;
   780 	}
   781 
   782 	if (pPlayer->WasCountedAsInGame())
   783 	{
   784 		m_PlayerCount--;
   785 	}
   786 
   787 	List<IClientListener *>::iterator iter;
   788 	IClientListener *pListener = NULL;
   789 	for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
   790 	{
   791 		pListener = (*iter);
   792 		pListener->OnClientDisconnecting(client);
   793 	}
   794 
   795 	InvalidatePlayer(pPlayer);
   796 
   797 	if (m_ListenClient == client)
   798 	{
   799 		m_ListenClient = 0;
   800 	}
   801 }
   802 
   803 #if SOURCE_ENGINE == SE_DOTA
   804 void PlayerManager::OnClientDisconnect_Post(CEntityIndex index, int reason)
   805 {
   806 	int client = index.Get();
   807 	edict_t *pEntity = PEntityOfEntIndex(client);
   808 #else
   809 void PlayerManager::OnClientDisconnect_Post(edict_t *pEntity)
   810 {
   811 	int client = IndexOfEdict(pEntity);
   812 #endif
   813 
   814 	cell_t res;
   815 
   816 	m_cldisconnect_post->PushCell(client);
   817 	m_cldisconnect_post->Execute(&res, NULL);
   818 
   819 	List<IClientListener *>::iterator iter;
   820 	IClientListener *pListener = NULL;
   821 	for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
   822 	{
   823 		pListener = (*iter);
   824 		pListener->OnClientDisconnected(client);
   825 	}
   826 }
   827 
   828 void ClientConsolePrint(edict_t *e, const char *fmt, ...)
   829 {
   830 	char buffer[512];
   831 
   832 	va_list ap;
   833 	va_start(ap, fmt);
   834 	size_t len = vsnprintf(buffer, sizeof(buffer), fmt, ap);
   835 	va_end(ap);
   836 
   837 	if (len >= sizeof(buffer) - 1)
   838 	{
   839 		buffer[sizeof(buffer) - 2] = '\n';
   840 		buffer[sizeof(buffer) - 1] = '\0';
   841 	} else {
   842 		buffer[len++] = '\n';
   843 		buffer[len] = '\0';
   844 	}
   845 
   846 	CPlayer *pPlayer = g_Players.GetPlayerByIndex(IndexOfEdict(e));
   847 	if (!pPlayer)
   848 	{
   849 		return;
   850 	}
   851 	
   852 	pPlayer->PrintToConsole(buffer);
   853 }
   854 
   855 void ListExtensionsToClient(CPlayer *player, const CCommand &args)
   856 {
   857 	char buffer[256];
   858 	unsigned int id = 0;
   859 	unsigned int start = 0;
   860 
   861 	AutoExtensionList extensions(extsys);
   862 	if (!extensions->size())
   863 	{
   864 		ClientConsolePrint(player->GetEdict(), "[SM] No extensions found.");
   865 		return;
   866 	}
   867 
   868 	if (args.ArgC() > 2)
   869 	{
   870 		start = atoi(args.Arg(2));
   871 	}
   872 
   873 	size_t i = 0;
   874 	for (; i < extensions->size(); i++)
   875 	{
   876 		IExtension *ext = extensions->at(i);
   877 
   878 		char error[255];
   879 		if (!ext->IsRunning(error, sizeof(error)))
   880 		{
   881 			continue;
   882 		}
   883 
   884 		id++;
   885 		if (id < start)
   886 		{
   887 			continue;
   888 		}
   889 
   890 		if (id - start > 10)
   891 		{
   892 			break;
   893 		}
   894 
   895 		IExtensionInterface *api = ext->GetAPI();
   896 
   897 		const char *name = api->GetExtensionName();
   898 		const char *version = api->GetExtensionVerString();
   899 		const char *author = api->GetExtensionAuthor();
   900 		const char *description = api->GetExtensionDescription();
   901 
   902 		size_t len = UTIL_Format(buffer, sizeof(buffer), " \"%s\"", name);
   903 
   904 		if (version != NULL && version[0])
   905 		{
   906 			len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " (%s)", version);
   907 		}
   908 
   909 		if (author != NULL && author[0])
   910 		{
   911 			len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " by %s", author);
   912 		}
   913 
   914 		if (description != NULL && description[0])
   915 		{
   916 			len += UTIL_Format(&buffer[len], sizeof(buffer)-len, ": %s", description);
   917 		}
   918 
   919 
   920 		ClientConsolePrint(player->GetEdict(), "%s", buffer);
   921 	}
   922 
   923 	for (; i < extensions->size(); i++)
   924 	{
   925 		char error[255];
   926 		if (extensions->at(i)->IsRunning(error, sizeof(error)))
   927 		{
   928 			break;
   929 		}
   930 	}
   931 
   932 	if (i < extensions->size())
   933 	{
   934 		ClientConsolePrint(player->GetEdict(), "To see more, type \"sm exts %d\"", id);
   935 	}
   936 }
   937 
   938 void ListPluginsToClient(CPlayer *player, const CCommand &args)
   939 {
   940 	char buffer[256];
   941 	unsigned int id = 0;
   942 	edict_t *e = player->GetEdict();
   943 	unsigned int start = 0;
   944 
   945 	AutoPluginList plugins(scripts);
   946 	if (!plugins->size())
   947 	{
   948 		ClientConsolePrint(e, "[SM] No plugins found.");
   949 		return;
   950 	}
   951 
   952 	if (args.ArgC() > 2)
   953 	{
   954 		start = atoi(args.Arg(2));
   955 	}
   956 
   957 	SourceHook::List<SMPlugin *> m_FailList;
   958 
   959 	size_t i = 0;
   960 	for (; i < plugins->size(); i++)
   961 	{
   962 		SMPlugin *pl = plugins->at(i);
   963 
   964 		if (pl->GetStatus() != Plugin_Running)
   965 		{
   966 			continue;
   967 		}
   968 
   969 		/* Count valid plugins */
   970 		id++;
   971 		if (id < start)
   972 		{
   973 			continue;
   974 		}
   975 
   976 		if (id - start > 10)
   977 		{
   978 			break;
   979 		}
   980 
   981 		size_t len;
   982 		const sm_plugininfo_t *info = pl->GetPublicInfo();
   983 		len = UTIL_Format(buffer, sizeof(buffer), " \"%s\"", (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
   984 		if (IS_STR_FILLED(info->version))
   985 		{
   986 			len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " (%s)", info->version);
   987 		}
   988 		if (IS_STR_FILLED(info->author))
   989 		{
   990 			UTIL_Format(&buffer[len], sizeof(buffer)-len, " by %s", info->author);
   991 		}
   992 		else
   993 		{
   994 			UTIL_Format(&buffer[len], sizeof(buffer)-len, " %s", pl->GetFilename());
   995 		}
   996 		ClientConsolePrint(e, "%s", buffer);
   997 	}
   998 
   999 	/* See if we can get more plugins */
  1000 	for (; i < plugins->size(); i++)
  1001 	{
  1002 		if (plugins->at(i)->GetStatus() == Plugin_Running)
  1003 		{
  1004 			break;
  1005 		}
  1006 	}
  1007 
  1008 	/* Do we actually have more plugins? */
  1009 	if (i < plugins->size())
  1010 	{
  1011 		ClientConsolePrint(e, "To see more, type \"sm plugins %d\"", id);
  1012 	}
  1013 }
  1014 
  1015 #if SOURCE_ENGINE == SE_DOTA
  1016 void PlayerManager::OnClientCommand(CEntityIndex index, const CCommand &args)
  1017 {
  1018 	int client = index.Get();
  1019 	edict_t *pEntity = PEntityOfEntIndex(client);
  1020 #elif SOURCE_ENGINE >= SE_ORANGEBOX
  1021 void PlayerManager::OnClientCommand(edict_t *pEntity, const CCommand &args)
  1022 {
  1023 	int client = IndexOfEdict(pEntity);
  1024 #else
  1025 void PlayerManager::OnClientCommand(edict_t *pEntity)
  1026 {
  1027 	CCommand args;
  1028 
  1029 	int client = IndexOfEdict(pEntity);
  1030 #endif
  1031 	
  1032 	cell_t res = Pl_Continue;
  1033 	CPlayer *pPlayer = &m_Players[client];
  1034 
  1035 	if (!pPlayer->IsConnected())
  1036 	{
  1037 		return;
  1038 	}
  1039 
  1040 	if (strcmp(args.Arg(0), "sm") == 0)
  1041 	{
  1042 		if (args.ArgC() > 1 && strcmp(args.Arg(1), "plugins") == 0)
  1043 		{
  1044 			ListPluginsToClient(pPlayer, args);
  1045 			RETURN_META(MRES_SUPERCEDE);
  1046 		}
  1047 		else if (args.ArgC() > 1 && strcmp(args.Arg(1), "exts") == 0)
  1048 		{
  1049 			ListExtensionsToClient(pPlayer, args);
  1050 			RETURN_META(MRES_SUPERCEDE);
  1051 		}
  1052 		else if (args.ArgC() > 1 && strcmp(args.Arg(1), "credits") == 0)
  1053 		{
  1054  			ClientConsolePrint(pEntity,
  1055  				"SourceMod would not be possible without:");
  1056  			ClientConsolePrint(pEntity,
  1057 				" David \"BAILOPAN\" Anderson, Matt \"pRED\" Woodrow");
  1058  			ClientConsolePrint(pEntity,
  1059 				" Scott \"DS\" Ehlert, Fyren");
  1060  			ClientConsolePrint(pEntity,
  1061 				" Nicholas \"psychonic\" Hastings, Asher \"asherkin\" Baker");
  1062 			ClientConsolePrint(pEntity,
  1063 				" Borja \"faluco\" Ferrer, Pavol \"PM OnoTo\" Marko");
  1064 			ClientConsolePrint(pEntity,
  1065 				"SourceMod is open source under the GNU General Public License.");
  1066 			RETURN_META(MRES_SUPERCEDE);
  1067 		}
  1068 
  1069 		ClientConsolePrint(pEntity,
  1070 			"SourceMod %s, by AlliedModders LLC", SOURCEMOD_VERSION);
  1071 		ClientConsolePrint(pEntity,
  1072 			"To see running plugins, type \"sm plugins\"");
  1073 		ClientConsolePrint(pEntity,
  1074 			"To see credits, type \"sm credits\"");
  1075 		ClientConsolePrint(pEntity,
  1076 			"Visit http://www.sourcemod.net/");
  1077 		RETURN_META(MRES_SUPERCEDE);
  1078 	}
  1079 
  1080 	g_HL2.PushCommandStack(&args);
  1081 
  1082 	int argcount = args.ArgC() - 1;
  1083 	const char *cmd = g_HL2.CurrentCommandName();
  1084 
  1085 	bool result = g_ValveMenuStyle.OnClientCommand(client, cmd, args);
  1086 	if (result)
  1087 	{
  1088 		res = Pl_Handled;
  1089 	} else {
  1090 		result = g_RadioMenuStyle.OnClientCommand(client, cmd, args);
  1091 		if (result)
  1092 		{
  1093 			res = Pl_Handled;
  1094 		}
  1095 	}
  1096 
  1097 	if (g_ConsoleDetours.IsEnabled())
  1098 	{
  1099 		cell_t res2 = g_ConsoleDetours.InternalDispatch(client, args);
  1100 		if (res2 >= Pl_Stop)
  1101 		{
  1102 			g_HL2.PopCommandStack();
  1103 			RETURN_META(MRES_SUPERCEDE);
  1104 		}
  1105 		else if (res2 > res)
  1106 		{
  1107 			res = res2;
  1108 		}
  1109 	}
  1110 
  1111 	cell_t res2 = Pl_Continue;
  1112 	if (pPlayer->IsInGame())
  1113 	{
  1114 		m_clcommand->PushCell(client);
  1115 		m_clcommand->PushCell(argcount);
  1116 		m_clcommand->Execute(&res2, NULL);
  1117 	}
  1118 
  1119 	if (res2 > res)
  1120 	{
  1121 		res = res2;
  1122 	}
  1123 
  1124 	if (res >= Pl_Stop)
  1125 	{
  1126 		g_HL2.PopCommandStack();
  1127 		RETURN_META(MRES_SUPERCEDE);
  1128 	}
  1129 
  1130 	res = g_ConCmds.DispatchClientCommand(client, cmd, argcount, (ResultType)res);
  1131 
  1132 	g_HL2.PopCommandStack();
  1133 
  1134 	if (res >= Pl_Handled)
  1135 	{
  1136 		RETURN_META(MRES_SUPERCEDE);
  1137 	}
  1138 }
  1139 
  1140 #if SOURCE_ENGINE == SE_DOTA
  1141 void PlayerManager::OnClientSettingsChanged(CEntityIndex index)
  1142 {
  1143 	int client = index.Get();
  1144 	edict_t *pEntity = PEntityOfEntIndex(client);
  1145 #else
  1146 void PlayerManager::OnClientSettingsChanged(edict_t *pEntity)
  1147 {
  1148 	int client = IndexOfEdict(pEntity);
  1149 #endif
  1150 
  1151 	cell_t res;
  1152 	CPlayer *pPlayer = &m_Players[client];
  1153 
  1154 	if (!pPlayer->IsConnected())
  1155 	{
  1156 		return;
  1157 	}
  1158 
  1159 	m_clinfochanged->PushCell(client);
  1160 	m_clinfochanged->Execute(&res, NULL);
  1161 
  1162 	if (pPlayer->IsFakeClient())
  1163 	{
  1164 		return;
  1165 	}
  1166 
  1167 	IPlayerInfo *info = pPlayer->GetPlayerInfo();
  1168 	const char *new_name = info ? info->GetName() : engine->GetClientConVarValue(client, "name");
  1169 	const char *old_name = pPlayer->m_Name.c_str();
  1170 
  1171 #if SOURCE_ENGINE >= SE_LEFT4DEAD
  1172 	const char *networkid_force;
  1173 	if ((networkid_force = engine->GetClientConVarValue(client, "networkid_force")) && networkid_force[0] != '\0')
  1174 	{
  1175 		unsigned int accountId = pPlayer->GetSteamAccountID();
  1176 		g_Logger.LogMessage("\"%s<%d><STEAM_1:%d:%d><>\" has bad networkid (id \"%s\") (ip \"%s\")",
  1177 			new_name, pPlayer->GetUserId(), accountId & 1, accountId >> 1, networkid_force, pPlayer->GetIPAddress());
  1178 
  1179 		pPlayer->Kick("NetworkID spoofing detected.");
  1180 		RETURN_META(MRES_IGNORED);
  1181 	}
  1182 #endif
  1183 
  1184 	if (strcmp(old_name, new_name) != 0)
  1185 	{
  1186 		AdminId id = g_Admins.FindAdminByIdentity("name", new_name);
  1187 		if (id != INVALID_ADMIN_ID && pPlayer->GetAdminId() != id)
  1188 		{
  1189 			if (!CheckSetAdminName(client, pPlayer, id))
  1190 			{
  1191 				char kickMsg[128];
  1192 				logicore.CoreTranslate(kickMsg, sizeof(kickMsg), "%T", 2, NULL, "Name Reserved", &client);
  1193 				pPlayer->Kick(kickMsg);
  1194 				RETURN_META(MRES_IGNORED);
  1195 			}
  1196 		} else if ((id = g_Admins.FindAdminByIdentity("name", old_name)) != INVALID_ADMIN_ID) {
  1197 			if (id == pPlayer->GetAdminId())
  1198 			{
  1199 				/* This player is changing their name; force them to drop admin privileges! */
  1200 				pPlayer->SetAdminId(INVALID_ADMIN_ID, false);
  1201 			}
  1202 		}
  1203 		pPlayer->SetName(new_name);
  1204 	}
  1205 	
  1206 	if (m_PassInfoVar.size() > 0)
  1207 	{
  1208 		/* Try for a password change */
  1209 		const char *old_pass = pPlayer->m_LastPassword.c_str();
  1210 		const char *new_pass = engine->GetClientConVarValue(client, m_PassInfoVar.c_str());
  1211 		if (strcmp(old_pass, new_pass) != 0)
  1212 		{
  1213 			pPlayer->m_LastPassword.assign(new_pass);
  1214 			if (pPlayer->IsInGame() && pPlayer->IsAuthorized())
  1215 			{
  1216 				/* If there is already an admin id assigned, this will just bail out. */
  1217 				pPlayer->DoBasicAdminChecks();
  1218 			}
  1219 		}
  1220 	}
  1221 	/* Notify Extensions */
  1222 	List<IClientListener *>::iterator iter;
  1223 	IClientListener *pListener = NULL;
  1224 	for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
  1225 	{
  1226 		pListener = (*iter);
  1227 		if (pListener->GetClientListenerVersion() >= 13)
  1228 		{
  1229 			pListener->OnClientSettingsChanged(client);
  1230 		}
  1231 	}
  1232 }
  1233 
  1234 int PlayerManager::GetMaxClients()
  1235 {
  1236 	return m_maxClients;
  1237 }
  1238 
  1239 CPlayer *PlayerManager::GetPlayerByIndex(int client) const
  1240 {
  1241 	if (client > m_maxClients || client < 1)
  1242 	{
  1243 		return NULL;
  1244 	}
  1245 	return &m_Players[client];
  1246 }
  1247 
  1248 int PlayerManager::GetNumPlayers()
  1249 {
  1250 	return m_PlayerCount;
  1251 }
  1252 
  1253 int PlayerManager::GetClientOfUserId(int userid)
  1254 {
  1255 	if (userid < 0 || userid > USHRT_MAX)
  1256 	{
  1257 		return 0;
  1258 	}
  1259 	
  1260 	int client = m_UserIdLookUp[userid];
  1261 
  1262 	/* Verify the userid.  The cache can get messed up with older
  1263 	 * Valve engines.  :TODO: If this gets fixed, do an old engine 
  1264 	 * check before invoking this backwards compat code.
  1265 	 */
  1266 	if (client)
  1267 	{
  1268 		CPlayer *player = GetPlayerByIndex(client);
  1269 		if (player && player->IsConnected())
  1270 		{
  1271 			int realUserId = GetPlayerUserId(player->GetEdict());
  1272 			if (realUserId == userid)
  1273 			{
  1274 				return client;
  1275 			}
  1276 		}
  1277 	}
  1278 
  1279 	/* If we can't verify the userid, we have to do a manual loop */
  1280 	CPlayer *player;
  1281 	for (int i = 1; i <= m_maxClients; i++)
  1282 	{
  1283 		player = GetPlayerByIndex(i);
  1284 		if (!player || !player->IsConnected())
  1285 		{
  1286 			continue;
  1287 		}
  1288 		if (GetPlayerUserId(player->GetEdict()) == userid)
  1289 		{
  1290 			m_UserIdLookUp[userid] = i;
  1291 			return i;
  1292 		}
  1293 	}
  1294 
  1295 	return 0;
  1296 }
  1297 
  1298 void PlayerManager::AddClientListener(IClientListener *listener)
  1299 {
  1300 	m_hooks.push_back(listener);
  1301 }
  1302 
  1303 void PlayerManager::RemoveClientListener(IClientListener *listener)
  1304 {
  1305 	m_hooks.remove(listener);
  1306 }
  1307 
  1308 IGamePlayer *PlayerManager::GetGamePlayer(edict_t *pEdict)
  1309 {
  1310 	int index = IndexOfEdict(pEdict);
  1311 	return GetGamePlayer(index);
  1312 }
  1313 
  1314 IGamePlayer *PlayerManager::GetGamePlayer(int client)
  1315 {
  1316 	return GetPlayerByIndex(client);
  1317 }
  1318 
  1319 void PlayerManager::ClearAdminId(AdminId id)
  1320 {
  1321 	for (int i=1; i<=m_maxClients; i++)
  1322 	{
  1323 		if (m_Players[i].m_Admin == id)
  1324 		{
  1325 			m_Players[i].DumpAdmin(true);
  1326 		}
  1327 	}
  1328 }
  1329 
  1330 void PlayerManager::ClearAllAdmins()
  1331 {
  1332 	for (int i=1; i<=m_maxClients; i++)
  1333 	{
  1334 		m_Players[i].DumpAdmin(true);
  1335 	}
  1336 }
  1337 
  1338 const char *PlayerManager::GetPassInfoVar()
  1339 {
  1340 	return m_PassInfoVar.c_str();
  1341 }
  1342 
  1343 void PlayerManager::RecheckAnyAdmins()
  1344 {
  1345 	for (int i=1; i<=m_maxClients; i++)
  1346 	{
  1347 		if (m_Players[i].IsInGame() && m_Players[i].IsAuthorized())
  1348 		{
  1349 			m_Players[i].DoBasicAdminChecks();
  1350 		}
  1351 	}
  1352 }
  1353 
  1354 unsigned int PlayerManager::GetReplyTo()
  1355 {
  1356 	return g_ChatTriggers.GetReplyTo();
  1357 }
  1358 
  1359 unsigned int PlayerManager::SetReplyTo(unsigned int reply)
  1360 {
  1361 	return g_ChatTriggers.SetReplyTo(reply);
  1362 }
  1363 
  1364 int PlayerManager::FilterCommandTarget(IGamePlayer *pAdmin, IGamePlayer *pTarget, int flags)
  1365 {
  1366 	return InternalFilterCommandTarget((CPlayer *)pAdmin, (CPlayer *)pTarget, flags);
  1367 }
  1368 
  1369 void PlayerManager::RegisterCommandTargetProcessor(ICommandTargetProcessor *pHandler)
  1370 {
  1371 	target_processors.push_back(pHandler);
  1372 }
  1373 
  1374 void PlayerManager::UnregisterCommandTargetProcessor(ICommandTargetProcessor *pHandler)
  1375 {
  1376 	target_processors.remove(pHandler);
  1377 }
  1378 
  1379 void PlayerManager::InvalidatePlayer(CPlayer *pPlayer)
  1380 {
  1381 	/**
  1382 	* Remove client from auth queue if necessary
  1383 	*/
  1384 	if (!pPlayer->IsAuthorized())
  1385 	{
  1386 		for (unsigned int i=1; i<=m_AuthQueue[0]; i++)
  1387 		{
  1388 			if (m_AuthQueue[i] == (unsigned)pPlayer->m_iIndex)
  1389 			{
  1390 				/* Move everything ahead of us back by one */
  1391 				for (unsigned int j=i+1; j<=m_AuthQueue[0]; j++)
  1392 				{
  1393 					m_AuthQueue[j-1] = m_AuthQueue[j];
  1394 				}
  1395 				/* Remove us and break */
  1396 				m_AuthQueue[0]--;
  1397 				break;
  1398 			}
  1399 		}
  1400 	}
  1401 	
  1402 	m_UserIdLookUp[GetPlayerUserId(pPlayer->m_pEdict)] = 0;
  1403 	pPlayer->Disconnect();
  1404 }
  1405 
  1406 int PlayerManager::InternalFilterCommandTarget(CPlayer *pAdmin, CPlayer *pTarget, int flags)
  1407 {
  1408 	if ((flags & COMMAND_FILTER_CONNECTED) == COMMAND_FILTER_CONNECTED
  1409 		&& !pTarget->IsConnected())
  1410 	{
  1411 		return COMMAND_TARGET_NONE;
  1412 	}
  1413 	else if ((flags & COMMAND_FILTER_CONNECTED) != COMMAND_FILTER_CONNECTED && 
  1414 		!pTarget->IsInGame())
  1415 	{
  1416 		return COMMAND_TARGET_NOT_IN_GAME;
  1417 	}
  1418 
  1419 	if ((flags & COMMAND_FILTER_NO_BOTS) == COMMAND_FILTER_NO_BOTS
  1420 		&& pTarget->IsFakeClient())
  1421 	{
  1422 		return COMMAND_TARGET_NOT_HUMAN;
  1423 	}
  1424 
  1425 	if (pAdmin != NULL)
  1426 	{
  1427 		if ((flags & COMMAND_FILTER_NO_IMMUNITY) != COMMAND_FILTER_NO_IMMUNITY
  1428 			&& !g_Admins.CanAdminTarget(pAdmin->GetAdminId(), pTarget->GetAdminId()))
  1429 		{
  1430 			return COMMAND_TARGET_IMMUNE;
  1431 		}
  1432 	}
  1433 
  1434 	if ((flags & COMMAND_FILTER_ALIVE) == COMMAND_FILTER_ALIVE 
  1435 		&& pTarget->GetLifeState() != PLAYER_LIFE_ALIVE)
  1436 	{
  1437 		return COMMAND_TARGET_NOT_ALIVE;
  1438 	}
  1439 
  1440 	if ((flags & COMMAND_FILTER_DEAD) == COMMAND_FILTER_DEAD
  1441 		&& pTarget->GetLifeState() != PLAYER_LIFE_DEAD)
  1442 	{
  1443 		return COMMAND_TARGET_NOT_DEAD;
  1444 	}
  1445 
  1446 	return COMMAND_TARGET_VALID;
  1447 }
  1448 
  1449 void PlayerManager::ProcessCommandTarget(cmd_target_info_t *info)
  1450 {
  1451 	CPlayer *pTarget, *pAdmin;
  1452 	int max_clients, total = 0;
  1453 
  1454 	max_clients = GetMaxClients();
  1455 
  1456 	if (info->max_targets < 1)
  1457 	{
  1458 		info->reason = COMMAND_TARGET_NONE;
  1459 		info->num_targets = 0;
  1460 	}
  1461 
  1462 	if (info->admin == 0)
  1463 	{
  1464 		pAdmin = NULL;
  1465 	}
  1466 	else
  1467 	{
  1468 		pAdmin = GetPlayerByIndex(info->admin);
  1469 	}
  1470 
  1471 	if (info->pattern[0] == '#')
  1472 	{
  1473 		int userid = atoi(&info->pattern[1]);
  1474 		int client = GetClientOfUserId(userid);
  1475 
  1476 		/* See if a valid userid matched */
  1477 		if (client > 0)
  1478 		{
  1479 			IGamePlayer *pTarget = GetPlayerByIndex(client);
  1480 			if (pTarget != NULL)
  1481 			{
  1482 				if ((info->reason = FilterCommandTarget(pAdmin, pTarget, info->flags)) == COMMAND_TARGET_VALID)
  1483 				{
  1484 					info->targets[0] = client;
  1485 					info->num_targets = 1;
  1486 					strncopy(info->target_name, pTarget->GetName(), info->target_name_maxlength);
  1487 					info->target_name_style = COMMAND_TARGETNAME_RAW;
  1488 				}
  1489 				else
  1490 				{
  1491 					info->num_targets = 0;
  1492 				}
  1493 				return;
  1494 			}
  1495 		}
  1496 
  1497 		/* Do we need to look for a steam id? */
  1498 		if (strncmp(&info->pattern[1], "STEAM_", 6) == 0)
  1499 		{
  1500 			size_t p, len;
  1501 			char new_pattern[256];
  1502 
  1503 			strcpy(new_pattern, "STEAM_");
  1504 			len = strlen(&info->pattern[7]);
  1505 			for (p = 0; p < len; p++)
  1506 			{
  1507 				new_pattern[6 + p] = info->pattern[7 + p];
  1508 				if (new_pattern[6 + p] == '_')
  1509 				{
  1510 					new_pattern[6 + p] = ':';
  1511 				}
  1512 			}
  1513 			new_pattern[6 + p] = '\0';
  1514 
  1515 			for (int i = 1; i <= max_clients; i++)
  1516 			{
  1517 				if ((pTarget = GetPlayerByIndex(i)) == NULL)
  1518 				{
  1519 					continue;
  1520 				}
  1521 				if (!pTarget->IsConnected())
  1522 				{
  1523 					continue;
  1524 				}
  1525 				const char *authstr = pTarget->GetAuthString(false); // We want to make it easy for people to be kicked/banned, so don't require validation for command targets.
  1526 				if (authstr && strcmp(authstr, new_pattern) == 0)
  1527 				{
  1528 					if ((info->reason = FilterCommandTarget(pAdmin, pTarget, info->flags))
  1529 						== COMMAND_TARGET_VALID)
  1530 					{
  1531 						info->targets[0] = i;
  1532 						info->num_targets = 1;
  1533 						strncopy(info->target_name, pTarget->GetName(), info->target_name_maxlength);
  1534 						info->target_name_style = COMMAND_TARGETNAME_RAW;
  1535 					}
  1536 					else
  1537 					{
  1538 						info->num_targets = 0;
  1539 					}
  1540 					return;
  1541 				}
  1542 			}
  1543 		}
  1544 
  1545 		/* See if an exact name matches */
  1546 		for (int i = 1; i <= max_clients; i++)
  1547 		{
  1548 			if ((pTarget = GetPlayerByIndex(i)) == NULL)
  1549 			{
  1550 				continue;
  1551 			}
  1552 			if  (!pTarget->IsConnected())
  1553 			{
  1554 				continue;
  1555 			}
  1556 			if (strcmp(pTarget->GetName(), &info->pattern[1]) == 0)
  1557 			{
  1558 				if ((info->reason = FilterCommandTarget(pAdmin, pTarget, info->flags))
  1559 					== COMMAND_TARGET_VALID)
  1560 				{
  1561 					info->targets[0] = i;
  1562 					info->num_targets = 1;
  1563 					strncopy(info->target_name, pTarget->GetName(), info->target_name_maxlength);
  1564 					info->target_name_style = COMMAND_TARGETNAME_RAW;
  1565 				}
  1566 				else
  1567 				{
  1568 					info->num_targets = 0;
  1569 				}
  1570 				return;
  1571 			}
  1572 		}
  1573 	}
  1574 
  1575 	if (strcmp(info->pattern, "@me") == 0 && info->admin != 0)
  1576 	{
  1577 		info->reason = FilterCommandTarget(pAdmin, pAdmin, info->flags);
  1578 		if (info->reason == COMMAND_TARGET_VALID)
  1579 		{
  1580 			info->targets[0] = info->admin;
  1581 			info->num_targets = 1;
  1582 			strncopy(info->target_name, pAdmin->GetName(), info->target_name_maxlength);
  1583 			info->target_name_style = COMMAND_TARGETNAME_RAW;
  1584 		}
  1585 		else
  1586 		{
  1587 			info->num_targets = 0;
  1588 		}
  1589 		return;
  1590 	}
  1591 
  1592 	if ((info->flags & COMMAND_FILTER_NO_MULTI) != COMMAND_FILTER_NO_MULTI)
  1593 	{
  1594 		bool is_multi = false;
  1595 		bool bots_only = false;
  1596 		int skip_client = -1;
  1597 
  1598 		if (strcmp(info->pattern, "@all") == 0)
  1599 		{
  1600 			is_multi = true;
  1601 			strncopy(info->target_name, "all players", info->target_name_maxlength);
  1602 			info->target_name_style = COMMAND_TARGETNAME_ML;
  1603 		}
  1604 		else if (strcmp(info->pattern, "@dead") == 0)
  1605 		{
  1606 			is_multi = true;
  1607 			if ((info->flags & COMMAND_FILTER_ALIVE) == COMMAND_FILTER_ALIVE)
  1608 			{
  1609 				info->num_targets = 0;
  1610 				info->reason = COMMAND_TARGET_NOT_ALIVE;
  1611 				return;
  1612 			}
  1613 			info->flags |= COMMAND_FILTER_DEAD;
  1614 			strncopy(info->target_name, "all dead players", info->target_name_maxlength);
  1615 			info->target_name_style = COMMAND_TARGETNAME_ML;
  1616 		}
  1617 		else if (strcmp(info->pattern, "@alive") == 0)
  1618 		{
  1619 			is_multi = true;
  1620 			if ((info->flags & COMMAND_FILTER_DEAD) == COMMAND_FILTER_DEAD)
  1621 			{
  1622 				info->num_targets = 0;
  1623 				info->reason = COMMAND_TARGET_NOT_DEAD;
  1624 				return;
  1625 			}
  1626 			strncopy(info->target_name, "all alive players", info->target_name_maxlength);
  1627 			info->target_name_style = COMMAND_TARGETNAME_ML;
  1628 			info->flags |= COMMAND_FILTER_ALIVE;
  1629 		}
  1630 		else if (strcmp(info->pattern, "@bots") == 0)
  1631 		{
  1632 			is_multi = true;
  1633 			if ((info->flags & COMMAND_FILTER_NO_BOTS) == COMMAND_FILTER_NO_BOTS)
  1634 			{
  1635 				info->num_targets = 0;
  1636 				info->reason = COMMAND_TARGET_NOT_HUMAN;
  1637 				return;
  1638 			}
  1639 			strncopy(info->target_name, "all bots", info->target_name_maxlength);
  1640 			info->target_name_style = COMMAND_TARGETNAME_ML;
  1641 			bots_only = true;
  1642 		}
  1643 		else if (strcmp(info->pattern, "@humans") == 0)
  1644 		{
  1645 			is_multi = true;
  1646 			strncopy(info->target_name, "all humans", info->target_name_maxlength);
  1647 			info->target_name_style = COMMAND_TARGETNAME_ML;
  1648 			info->flags |= COMMAND_FILTER_NO_BOTS;
  1649 		}
  1650 		else if (strcmp(info->pattern, "@!me") == 0)
  1651 		{
  1652 			is_multi = true;
  1653 			strncopy(info->target_name, "all players", info->target_name_maxlength);
  1654 			info->target_name_style = COMMAND_TARGETNAME_ML;
  1655 			skip_client = info->admin;
  1656 		}
  1657 
  1658 		if (is_multi)
  1659 		{
  1660 			for (int i = 1; i <= max_clients && total < info->max_targets; i++)
  1661 			{
  1662 				if ((pTarget = GetPlayerByIndex(i)) == NULL)
  1663 				{
  1664 					continue;
  1665 				}
  1666 				if (FilterCommandTarget(pAdmin, pTarget, info->flags) > 0)
  1667 				{
  1668 					if ((!bots_only || pTarget->IsFakeClient())
  1669 						&& skip_client != i)
  1670 					{
  1671 						info->targets[total++] = i;
  1672 					}
  1673 				}
  1674 			}
  1675 
  1676 			info->num_targets = total;
  1677 			info->reason = (info->num_targets) ? COMMAND_TARGET_VALID : COMMAND_TARGET_EMPTY_FILTER;
  1678 			return;
  1679 		}
  1680 	}
  1681 
  1682 	List<ICommandTargetProcessor *>::iterator iter;
  1683 	for (iter = target_processors.begin(); iter != target_processors.end(); iter++)
  1684 	{
  1685 		ICommandTargetProcessor *pProcessor = (*iter);
  1686 		if (pProcessor->ProcessCommandTarget(info))
  1687 		{
  1688 			return;
  1689 		}
  1690 	}
  1691 
  1692 	/* Check partial names */
  1693 	int found_client = 0;
  1694 	CPlayer *pFoundClient = NULL;
  1695 	for (int i = 1; i <= max_clients; i++)
  1696 	{
  1697 		if ((pTarget = GetPlayerByIndex(i)) == NULL)
  1698 		{
  1699 			continue;
  1700 		}
  1701 
  1702 		if (logicore.stristr(pTarget->GetName(), info->pattern) != NULL)
  1703 		{
  1704 			if (found_client)
  1705 			{
  1706 				info->num_targets = 0;
  1707 				info->reason = COMMAND_TARGET_AMBIGUOUS;
  1708 				return;
  1709 			}
  1710 			else
  1711 			{
  1712 				found_client = i;
  1713 				pFoundClient = pTarget;
  1714 			}
  1715 		}
  1716 	}
  1717 
  1718 	if (found_client)
  1719 	{
  1720 		if ((info->reason = FilterCommandTarget(pAdmin, pFoundClient, info->flags)) 
  1721 			== COMMAND_TARGET_VALID)
  1722 		{
  1723 			info->targets[0] = found_client;
  1724 			info->num_targets = 1;
  1725 			strncopy(info->target_name, pFoundClient->GetName(), info->target_name_maxlength);
  1726 			info->target_name_style = COMMAND_TARGETNAME_RAW;
  1727 		}
  1728 		else
  1729 		{
  1730 			info->num_targets = 0;
  1731 		}
  1732 	}
  1733 	else
  1734 	{
  1735 		info->num_targets = 0;
  1736 		info->reason = COMMAND_TARGET_NONE;
  1737 	}
  1738 }
  1739 
  1740 void PlayerManager::OnSourceModMaxPlayersChanged( int newvalue )
  1741 {
  1742 	m_maxClients = newvalue;
  1743 }
  1744 
  1745 void PlayerManager::MaxPlayersChanged( int newvalue /*= -1*/ )
  1746 {
  1747 	if (!m_FirstPass)
  1748 	{
  1749 		return;
  1750 	}
  1751 
  1752 	if (newvalue == -1)
  1753 	{
  1754 		newvalue = gpGlobals->maxClients;
  1755 	}
  1756 
  1757 	if (newvalue == MaxClients())
  1758 	{
  1759 		return;
  1760 	}
  1761 
  1762 	/* Notify the rest of core */
  1763 	SMGlobalClass *pBase = SMGlobalClass::head;
  1764 	while (pBase)
  1765 	{
  1766 		pBase->OnSourceModMaxPlayersChanged(newvalue);
  1767 		pBase = pBase->m_pGlobalClassNext;
  1768 	}
  1769 
  1770 	/* Notify Extensions */
  1771 	List<IClientListener *>::iterator iter;
  1772 	IClientListener *pListener = NULL;
  1773 	for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
  1774 	{
  1775 		pListener = (*iter);
  1776 		if (pListener->GetClientListenerVersion() >= 8)
  1777 		{
  1778 			pListener->OnMaxPlayersChanged(newvalue);
  1779 		}
  1780 	}
  1781 }
  1782 
  1783 int PlayerManager::GetClientFromSerial(unsigned int serial)
  1784 {
  1785 	serial_t s;
  1786 	s.value = serial;
  1787 
  1788 	int client = s.bits.index;
  1789 
  1790 	IGamePlayer *pPlayer = GetGamePlayer(client);
  1791 
  1792 	if (!pPlayer)
  1793 	{
  1794 		return 0;
  1795 	}
  1796 
  1797 	if (serial == pPlayer->GetSerial())
  1798 	{
  1799 		return client;
  1800 	}
  1801 
  1802 	return 0;
  1803 }
  1804 
  1805 #if SOURCE_ENGINE == SE_DOTA
  1806 void CmdMaxplayersCallback(const CCommandContext &context, const CCommand &command)
  1807 {
  1808 #elif SOURCE_ENGINE >= SE_ORANGEBOX
  1809 void CmdMaxplayersCallback(const CCommand &command)
  1810 {
  1811 #else
  1812 void CmdMaxplayersCallback()
  1813 {
  1814 #endif
  1815 
  1816 	g_Players.MaxPlayersChanged();
  1817 }
  1818 
  1819 
  1820 /*******************
  1821  *** PLAYER CODE ***
  1822  *******************/
  1823 
  1824 CPlayer::CPlayer()
  1825 {
  1826 	m_IsConnected = false;
  1827 	m_IsInGame = false;
  1828 	m_IsAuthorized = false;
  1829 	m_pEdict = NULL;
  1830 	m_Admin = INVALID_ADMIN_ID;
  1831 	m_TempAdmin = false;
  1832 	m_Info = NULL;
  1833 	m_bAdminCheckSignalled = false;
  1834 	m_UserId = -1;
  1835 	m_bIsInKickQueue = false;
  1836 	m_LastPassword.clear();
  1837 	m_LangId = SOURCEMOD_LANGUAGE_ENGLISH;
  1838 	m_bFakeClient = false;
  1839 	m_bIsSourceTV = false;
  1840 	m_bIsReplay = false;
  1841 	m_Serial.value = -1;
  1842 	m_SteamAccountID = 0;
  1843 }
  1844 
  1845 void CPlayer::Initialize(const char *name, const char *ip, edict_t *pEntity)
  1846 {
  1847 	m_IsConnected = true;
  1848 	m_Name.assign(name);
  1849 	m_Ip.assign(ip);
  1850 	m_pEdict = pEntity;
  1851 	m_iIndex = IndexOfEdict(pEntity);
  1852 	m_LangId = translator->GetServerLanguage();
  1853 
  1854 	m_Serial.bits.index = m_iIndex;
  1855 	m_Serial.bits.serial = g_PlayerSerialCount++;
  1856 
  1857 	char ip2[24], *ptr;
  1858 	strncopy(ip2, ip, sizeof(ip2));
  1859 	if ((ptr = strchr(ip2, ':')) != NULL)
  1860 	{
  1861 		*ptr = '\0';
  1862 	}
  1863 	m_IpNoPort.assign(ip2);
  1864 }
  1865 
  1866 void CPlayer::Connect()
  1867 {
  1868 	if (m_IsInGame)
  1869 	{
  1870 		return;
  1871 	}
  1872 
  1873 	m_IsInGame = true;
  1874 
  1875 	const char *var = g_Players.GetPassInfoVar();
  1876 	int client = IndexOfEdict(m_pEdict);
  1877 	if (var[0] != '\0')
  1878 	{
  1879 		const char *pass = engine->GetClientConVarValue(client, var);
  1880 		m_LastPassword.assign(pass ? pass : "");
  1881 	}
  1882 	else
  1883 	{
  1884 		m_LastPassword.assign("");
  1885 	}
  1886 }
  1887 
  1888 void CPlayer::SetAuthString(const char *steamid)
  1889 {
  1890 	if (m_IsAuthorized)
  1891 	{
  1892 		return;
  1893 	}
  1894 
  1895 	m_AuthID.assign(steamid);
  1896 }
  1897 
  1898 // Ensure a valid AuthString is set before calling.
  1899 void CPlayer::Authorize()
  1900 {
  1901 	m_IsAuthorized = true;
  1902 }
  1903 
  1904 void CPlayer::Disconnect()
  1905 {
  1906 	DumpAdmin(false);
  1907 	m_IsConnected = false;
  1908 	m_IsInGame = false;
  1909 	m_IsAuthorized = false;
  1910 	m_Name.clear();
  1911 	m_Ip.clear();
  1912 	m_AuthID.clear();
  1913 	m_pEdict = NULL;
  1914 	m_Info = NULL;
  1915 	m_bAdminCheckSignalled = false;
  1916 	m_UserId = -1;
  1917 	m_bIsInKickQueue = false;
  1918 	m_bFakeClient = false;
  1919 	m_bIsSourceTV = false;
  1920 	m_bIsReplay = false;
  1921 	m_Serial.value = -1;
  1922 	m_SteamAccountID = 0;
  1923 }
  1924 
  1925 void CPlayer::SetName(const char *name)
  1926 {
  1927 	m_Name.assign(name);
  1928 }
  1929 
  1930 const char *CPlayer::GetName()
  1931 {
  1932 	if (m_Info && m_pEdict->GetUnknown())
  1933 	{
  1934 		return m_Info->GetName();
  1935 	}
  1936 	
  1937 	return m_Name.c_str();
  1938 }
  1939 
  1940 const char *CPlayer::GetIPAddress()
  1941 {
  1942 	return m_Ip.c_str();
  1943 }
  1944 
  1945 const char *CPlayer::GetAuthString(bool validated)
  1946 {
  1947 	if (validated && !IsAuthStringValidated())
  1948 	{
  1949 		return NULL;
  1950 	}
  1951 
  1952 	return m_AuthID.c_str();
  1953 }
  1954 
  1955 unsigned int CPlayer::GetSteamAccountID(bool validated)
  1956 {
  1957 	if (IsFakeClient() || (validated && !IsAuthStringValidated()))
  1958 	{
  1959 		return 0;
  1960 	}
  1961 
  1962 	if (m_SteamAccountID != 0)
  1963 	{
  1964 		return m_SteamAccountID;
  1965 	}
  1966 
  1967 #if SOURCE_ENGINE < SE_ORANGEBOX
  1968 	const char * pAuth = GetAuthString();
  1969 	/* STEAM_0:1:123123 | STEAM_ID_LAN | STEAM_ID_PENDING */
  1970 	if (pAuth && (strlen(pAuth) > 10) && pAuth[8] != '_')
  1971 	{
  1972 		m_SteamAccountID = (atoi(&pAuth[8]) | (atoi(&pAuth[10]) << 1));
  1973 	}
  1974 #else
  1975 	unsigned long long *steamId;
  1976 #if SOURCE_ENGINE == SE_DOTA
  1977 	steamId = (unsigned long long *)engine->GetClientSteamID(m_iIndex);
  1978 #else
  1979 	steamId = (unsigned long long *)engine->GetClientSteamID(m_pEdict);
  1980 #endif
  1981 
  1982 	if (steamId)
  1983 	{
  1984 		m_SteamAccountID = (*steamId & 0xFFFFFFFF);
  1985 	}
  1986 #endif
  1987 	return m_SteamAccountID;
  1988 }
  1989 
  1990 edict_t *CPlayer::GetEdict()
  1991 {
  1992 	return m_pEdict;
  1993 }
  1994 
  1995 int CPlayer::GetIndex() const
  1996 {
  1997 	return m_iIndex;
  1998 }
  1999 
  2000 bool CPlayer::IsInGame()
  2001 {
  2002 	return m_IsInGame && (m_pEdict->GetUnknown() != NULL);
  2003 }
  2004 
  2005 bool CPlayer::WasCountedAsInGame()
  2006 {
  2007 	return m_IsInGame;
  2008 }
  2009 
  2010 bool CPlayer::IsConnected()
  2011 {
  2012 	return m_IsConnected;
  2013 }
  2014 
  2015 bool CPlayer::IsAuthorized()
  2016 {
  2017 	return m_IsAuthorized;
  2018 }
  2019 
  2020 bool CPlayer::IsAuthStringValidated()
  2021 {     
  2022 #if SOURCE_ENGINE >= SE_ORANGEBOX
  2023 	if (!IsFakeClient() && g_Players.m_bAuthstringValidation && !g_HL2.IsLANServer())
  2024 	{
  2025 #if SOURCE_ENGINE == SE_DOTA
  2026 		return engine->IsClientFullyAuthenticated(m_iIndex);
  2027 #else
  2028 		return engine->IsClientFullyAuthenticated(m_pEdict);
  2029 #endif
  2030 	}
  2031 #endif
  2032 
  2033 	return true;
  2034 }
  2035 
  2036 IPlayerInfo *CPlayer::GetPlayerInfo()
  2037 {
  2038 	if (m_pEdict->GetUnknown())
  2039 	{
  2040 		return m_Info;
  2041 	}
  2042 
  2043 	return NULL;
  2044 }
  2045 
  2046 bool CPlayer::IsFakeClient()
  2047 {
  2048 	return m_bFakeClient;
  2049 }
  2050 
  2051 bool CPlayer::IsSourceTV() const
  2052 {
  2053 	return m_bIsSourceTV;
  2054 }
  2055 
  2056 bool CPlayer::IsReplay() const
  2057 {
  2058 	return m_bIsReplay;
  2059 }
  2060 
  2061 void CPlayer::SetAdminId(AdminId id, bool temporary)
  2062 {
  2063 	if (!m_IsConnected)
  2064 	{
  2065 		return;
  2066 	}
  2067 
  2068 	DumpAdmin(false);
  2069 
  2070 	m_Admin = id;
  2071 	m_TempAdmin = temporary;
  2072 }
  2073 
  2074 AdminId CPlayer::GetAdminId()
  2075 {
  2076 	return m_Admin;
  2077 }
  2078 
  2079 void CPlayer::DumpAdmin(bool deleting)
  2080 {
  2081 	if (m_Admin != INVALID_ADMIN_ID)
  2082 	{
  2083 		if (m_TempAdmin && !deleting)
  2084 		{
  2085 			g_Admins.InvalidateAdmin(m_Admin);
  2086 		}
  2087 		m_Admin = INVALID_ADMIN_ID;
  2088 		m_TempAdmin = false;
  2089 	}
  2090 }
  2091 
  2092 void CPlayer::Kick(const char *str)
  2093 {
  2094 	MarkAsBeingKicked();
  2095 	INetChannel *pNetChan = static_cast<INetChannel *>(engine->GetPlayerNetInfo(m_iIndex));
  2096 	if (pNetChan == NULL)
  2097 	{
  2098 		/* What does this even mean? Hell if I know. */
  2099 		int userid = GetUserId();
  2100 		if (userid > 0)
  2101 		{
  2102 			char buffer[255];
  2103 			UTIL_Format(buffer, sizeof(buffer), "kickid %d %s\n", userid, str);
  2104 			engine->ServerCommand(buffer);
  2105 		}
  2106 	}
  2107 	else
  2108 	{
  2109 		IClient *pClient = static_cast<IClient *>(pNetChan->GetMsgHandler());
  2110 #if SOURCE_ENGINE == SE_DOTA
  2111 		// Including network_connection.pb.h (and .cpp) is overkill for just this.  -p
  2112 		// Copied from ENetworkDisconnectionReason enum
  2113 		const int NETWORK_DISCONNECT_KICKED = 39;
  2114 		pClient->Disconnect(NETWORK_DISCONNECT_KICKED);
  2115 #elif SOURCE_ENGINE == SE_CSGO
  2116 		pClient->Disconnect(str);
  2117 #else
  2118 		pClient->Disconnect("%s", str);
  2119 #endif
  2120 	}
  2121 }
  2122 
  2123 void CPlayer::Authorize_Post()
  2124 {
  2125 	if (m_IsInGame)
  2126 	{
  2127 		DoPostConnectAuthorization();
  2128 	}
  2129 }
  2130 
  2131 void CPlayer::DoPostConnectAuthorization()
  2132 {
  2133 	bool delay = false;
  2134 
  2135 	List<IClientListener *>::iterator iter;
  2136 	for (iter = g_Players.m_hooks.begin();
  2137 		 iter != g_Players.m_hooks.end();
  2138 		 iter++)
  2139 	{
  2140 		IClientListener *pListener = (*iter);
  2141 #if defined MIN_API_FOR_ADMINCALLS
  2142 		if (pListener->GetClientListenerVersion() < MIN_API_FOR_ADMINCALLS)
  2143 		{
  2144 			continue;
  2145 		}
  2146 #endif
  2147 		if (!pListener->OnClientPreAdminCheck(m_iIndex))
  2148 		{
  2149 			delay = true;
  2150 		}
  2151 	}
  2152 	
  2153 	cell_t result = 0;
  2154 	PreAdminCheck->PushCell(m_iIndex);
  2155 	PreAdminCheck->Execute(&result);
  2156 
  2157 	/* Defer, for better or worse */
  2158 	if (delay || (ResultType)result >= Pl_Handled)
  2159 	{
  2160 		return;
  2161 	}
  2162 
  2163 	/* Sanity check */
  2164 	if (!IsConnected())
  2165 	{
  2166 		return;
  2167 	}
  2168 
  2169 	/* Otherwise, go ahead and do admin checks */
  2170 	DoBasicAdminChecks();
  2171 
  2172 	/* Send the notification out */
  2173 	NotifyPostAdminChecks();
  2174 }
  2175 
  2176 bool CPlayer::RunAdminCacheChecks()
  2177 {
  2178 	AdminId old_id = GetAdminId();
  2179 
  2180 	DoBasicAdminChecks();
  2181 
  2182 	return (GetAdminId() != old_id);
  2183 }
  2184 
  2185 void CPlayer::NotifyPostAdminChecks()
  2186 {
  2187 	if (m_bAdminCheckSignalled)
  2188 	{
  2189 		return;
  2190 	}
  2191 
  2192 	/* Block beforehand so they can't double-call */
  2193 	m_bAdminCheckSignalled = true;
  2194 
  2195 	List<IClientListener *>::iterator iter;
  2196 	for (iter = g_Players.m_hooks.begin();
  2197 		iter != g_Players.m_hooks.end();
  2198 		iter++)
  2199 	{
  2200 		IClientListener *pListener = (*iter);
  2201 #if defined MIN_API_FOR_ADMINCALLS
  2202 		if (pListener->GetClientListenerVersion() < MIN_API_FOR_ADMINCALLS)
  2203 		{
  2204 			continue;
  2205 		}
  2206 #endif
  2207 		pListener->OnClientPostAdminCheck(m_iIndex);
  2208 	}
  2209 
  2210 	PostAdminFilter->PushCell(m_iIndex);
  2211 	PostAdminFilter->Execute(NULL);
  2212 
  2213 	PostAdminCheck->PushCell(m_iIndex);
  2214 	PostAdminCheck->Execute(NULL);
  2215 }
  2216 
  2217 void CPlayer::DoBasicAdminChecks()
  2218 {
  2219 	if (GetAdminId() != INVALID_ADMIN_ID)
  2220 	{
  2221 		return;
  2222 	}
  2223 
  2224 	/* First check the name */
  2225 	AdminId id;
  2226 	int client = IndexOfEdict(m_pEdict);
  2227 
  2228 	if ((id = g_Admins.FindAdminByIdentity("name", GetName())) != INVALID_ADMIN_ID)
  2229 	{
  2230 		if (!g_Players.CheckSetAdminName(client, this, id))
  2231 		{
  2232 			int userid = GetPlayerUserId(m_pEdict);
  2233 			g_Timers.CreateTimer(&s_KickPlayerTimer, 0.1f, (void *)userid, 0);
  2234 		}
  2235 		return;
  2236 	}
  2237 	
  2238 	/* Check IP */
  2239 	if ((id = g_Admins.FindAdminByIdentity("ip", m_IpNoPort.c_str())) != INVALID_ADMIN_ID)
  2240 	{
  2241 		if (g_Players.CheckSetAdmin(client, this, id))
  2242 		{
  2243 			return;
  2244 		}
  2245 	}
  2246 
  2247 	/* Check steam id */
  2248 	if ((id = g_Admins.FindAdminByIdentity("steam", m_AuthID.c_str())) != INVALID_ADMIN_ID)
  2249 	{
  2250 		if (g_Players.CheckSetAdmin(client, this, id))
  2251 		{
  2252 			return;
  2253 		}
  2254 	}
  2255 }
  2256 
  2257 unsigned int CPlayer::GetLanguageId()
  2258 {
  2259 	return m_LangId;
  2260 }
  2261 
  2262 void CPlayer::SetLanguageId(unsigned int id)
  2263 {
  2264 	m_LangId = id;
  2265 }
  2266 
  2267 int CPlayer::GetUserId()
  2268 {
  2269 	if (m_UserId == -1)
  2270 	{
  2271 		m_UserId = GetPlayerUserId(GetEdict());
  2272 	}
  2273 
  2274 	return m_UserId;
  2275 }
  2276 
  2277 bool CPlayer::IsInKickQueue()
  2278 {
  2279 	return m_bIsInKickQueue;
  2280 }
  2281 
  2282 void CPlayer::MarkAsBeingKicked()
  2283 {
  2284 	m_bIsInKickQueue = true;
  2285 }
  2286 
  2287 int CPlayer::GetLifeState()
  2288 {
  2289 	if (lifestate_offset == -1)
  2290 	{
  2291 		if (!g_pGameConf->GetOffset("m_lifeState", &lifestate_offset))
  2292 		{
  2293 			lifestate_offset = -2;
  2294 		}
  2295 	}
  2296 
  2297 	if (lifestate_offset < 0)
  2298 	{
  2299 		IPlayerInfo *info = GetPlayerInfo();
  2300 		if (info == NULL)
  2301 		{
  2302 			return PLAYER_LIFE_UNKNOWN;
  2303 		}
  2304 		return info->IsDead() ? PLAYER_LIFE_DEAD : PLAYER_LIFE_ALIVE;
  2305 	}
  2306 
  2307 	if (m_pEdict == NULL)
  2308 	{
  2309 		return PLAYER_LIFE_UNKNOWN;
  2310 	}
  2311 
  2312 	CBaseEntity *pEntity;
  2313 	IServerUnknown *pUnknown = m_pEdict->GetUnknown();
  2314 	if (pUnknown == NULL || (pEntity = pUnknown->GetBaseEntity()) == NULL)
  2315 	{
  2316 		return PLAYER_LIFE_UNKNOWN;
  2317 	}
  2318 
  2319 	if (*((uint8_t *)pEntity + lifestate_offset) == LIFE_ALIVE)
  2320 	{
  2321 		return PLAYER_LIFE_ALIVE;
  2322 	}
  2323 	else
  2324 	{
  2325 		return PLAYER_LIFE_DEAD;
  2326 	}
  2327 }
  2328 
  2329 unsigned int CPlayer::GetSerial()
  2330 {
  2331 	return m_Serial.value;
  2332 }
  2333 
  2334 void CPlayer::PrintToConsole(const char *pMsg)
  2335 {
  2336 	if (m_IsConnected == false || m_bFakeClient == true)
  2337 	{
  2338 		return;
  2339 	}
  2340 
  2341 	INetChannel *pNetChan = static_cast<INetChannel *>(engine->GetPlayerNetInfo(m_iIndex));
  2342 	if (pNetChan == NULL)
  2343 	{
  2344 		return;
  2345 	}
  2346 
  2347 #if SOURCE_ENGINE == SE_DOTA
  2348 	engine->ClientPrintf(m_iIndex, pMsg);
  2349 #else
  2350 	engine->ClientPrintf(m_pEdict, pMsg);
  2351 #endif
  2352 }