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