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