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